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.

refactor(health): unify execution graph analysis (#1773)

Raghav Chamadiya0b463bae3182
diff --git a/packages/core/alembic/versions/0055_graph_edge_call_lines.py b/packages/core/alembic/versions/0055_graph_edge_call_lines.py
new file mode 100644
index 000000000..c3e900f03
--- /dev/null
+++ b/packages/core/alembic/versions/0055_graph_edge_call_lines.py
@@ -0,0 +1,34 @@
+"""Preserve call-site lines on resolved graph edges.
+
+Several calls between the same symbol pair collapse to one edge. The line list
+lets performance analysis bind a loop/lock call to that resolved edge instead
+of repeating a bare-name lookup. Existing rows default to an empty list and use
+the documented compatibility fallback until the next index refresh.
+
+Revision ID: 0055
+Revises: 0054
+Create Date: 2026-08-20
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "0055"
+down_revision: str | None = "0054"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "graph_edges",
+ sa.Column("call_lines_json", sa.Text(), nullable=False, server_default="[]"),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("graph_edges", "call_lines_json")
diff --git a/packages/core/src/repowise/core/analysis/execution_graph.py b/packages/core/src/repowise/core/analysis/execution_graph.py
new file mode 100644
index 000000000..a049ac53e
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/execution_graph.py
@@ -0,0 +1,351 @@
+"""One reliable, deterministic view of symbol-level execution edges.
+
+Test reachability and performance analysis ask different questions of the same
+resolved graph. This module owns the part they must never reinterpret:
+
+* which edge types can transfer control;
+* which resolver origins are too weak to count as execution evidence;
+* file-to-symbol declarations and forward/reverse execution adjacency;
+* source definition and call-site lookup; and
+* the bounded reverse walk used to explain a path to a sink.
+
+Construction is one node scan plus one edge scan. Adjacencies preserve the
+source graph's stable insertion order while removing duplicates, so consumers
+do not pay for their own graph build or sort.
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from collections.abc import Callable, Hashable, Iterable, Mapping
+from dataclasses import dataclass
+from typing import Any, Literal, TypeVar
+
+from repowise.core.ingestion.models import EXECUTION_EDGE_TYPES
+
+UNRELIABLE_EXECUTION_ORIGINS = frozenset({"global_unique"})
+CallTargetBasis = Literal["call-site", "name-fallback"]
+_KeyT = TypeVar("_KeyT", bound=Hashable)
+
+
+def file_of_symbol(symbol_id: str) -> str:
+ """Return the file component of a ``path::symbol`` node id."""
+ return symbol_id.split("::", 1)[0]
+
+
+def module_node_id(path: str) -> str:
+ """Return the synthetic module-scope symbol id for *path*."""
+ return f"{path}::__module__"
+
+
+def is_reliable_execution_edge(edge_type: str | None, resolution_origin: str | None = None) -> bool:
+ """Whether an edge is strong enough to support an execution claim."""
+ return (
+ edge_type in EXECUTION_EDGE_TYPES and resolution_origin not in UNRELIABLE_EXECUTION_ORIGINS
+ )
+
+
+def _append_unique(
+ adjacency: dict[_KeyT, list[str]],
+ source: _KeyT,
+ target: str,
+ seen: set[tuple[_KeyT, str]] | None = None,
+) -> None:
+ if seen is None:
+ adjacency.setdefault(source, []).append(target)
+ return
+ pair = (source, target)
+ if pair not in seen:
+ seen.add(pair)
+ adjacency.setdefault(source, []).append(target)
+
+
+def _line_values(attrs: Mapping[str, Any]) -> tuple[int, ...]:
+ raw = attrs.get("call_lines")
+ if raw is None:
+ raw = (attrs.get("call_line"),)
+ elif isinstance(raw, int):
+ raw = (raw,)
+ return tuple(line for line in raw if isinstance(line, int) and line > 0)
+
+
+class ExecutionGraphIndex:
+ """The shared read-only index over reliable execution edges.
+
+ ``graph`` is normally the in-memory NetworkX graph. ``declares`` and
+ ``calls`` exist only as a compatibility construction path for small tests
+ and callers that already own adjacency maps.
+ """
+
+ __slots__ = (
+ "_by_caller_line",
+ "_by_file_line",
+ "_call_only",
+ "_callers_with_site_metadata",
+ "_ranges",
+ "calls",
+ "declares",
+ "forward",
+ "in_degree",
+ "name",
+ "nodes",
+ "reverse",
+ )
+
+ def __init__(
+ self,
+ graph: Any | None = None,
+ *,
+ declares: Mapping[str, Iterable[str]] | None = None,
+ calls: Mapping[str, Iterable[str]] | None = None,
+ edge_rows: Iterable[tuple[str, str, str, str | None, Iterable[int] | None]] = (),
+ ) -> None:
+ self.nodes: set[str] = set()
+ self.name: dict[str, str] = {}
+ forward: dict[str, list[str]] = {}
+ reverse: dict[str, list[str]] = {}
+ call_only: dict[str, list[str]] = {}
+ declaration_map: dict[str, list[str]] = {}
+ by_caller_line: dict[tuple[str, int], list[str]] = {}
+ by_file_line_candidates: dict[tuple[str, int], list[str]] = {}
+ forward_seen: set[tuple[str, str]] = set()
+ reverse_seen: set[tuple[str, str]] = set()
+ declaration_seen: set[tuple[str, str]] = set()
+ caller_line_seen: set[tuple[tuple[str, int], str]] = set()
+ call_only_seen: set[tuple[str, str]] = set()
+ callers_with_site_metadata: set[str] = set()
+ ranges: dict[str, list[tuple[int, int, str]]] = {}
+
+ if graph is not None:
+ try:
+ graph_nodes = graph.nodes(data=True)
+ except Exception:
+ graph_nodes = ()
+ for node_id, attrs in graph_nodes:
+ self.nodes.add(node_id)
+ if attrs.get("node_type") != "symbol":
+ continue
+ self.name[node_id] = attrs.get("name") or ""
+ path = attrs.get("file_path")
+ start = attrs.get("start_line")
+ end = attrs.get("end_line")
+ if path and isinstance(start, int):
+ _append_unique(by_file_line_candidates, (path, start), node_id)
+ if isinstance(end, int):
+ ranges.setdefault(path, []).append((start, end, node_id))
+ try:
+ graph_edges = graph.edges(data=True)
+ except Exception:
+ graph_edges = ()
+ try:
+ deduplicate_graph = bool(graph.is_multigraph())
+ except Exception:
+ deduplicate_graph = True
+ for source, target, data in graph_edges:
+ attrs = data or {}
+ edge_type = attrs.get("edge_type")
+ self._ingest_edge(
+ declaration_map,
+ declaration_seen if deduplicate_graph else None,
+ forward,
+ forward_seen if deduplicate_graph else None,
+ reverse,
+ reverse_seen if deduplicate_graph else None,
+ by_caller_line,
+ caller_line_seen if deduplicate_graph else None,
+ call_only,
+ call_only_seen if deduplicate_graph else None,
+ callers_with_site_metadata,
+ source,
+ target,
+ edge_type,
+ attrs.get("resolution_origin"),
+ _line_values(attrs) if edge_type == "calls" else (),
+ )
+
+ for source, targets in (declares or {}).items():
+ for target in sorted(set(targets)):
+ _append_unique(declaration_map, source, target, declaration_seen)
+ for source, targets in (calls or {}).items():
+ for target in sorted(set(targets)):
+ _append_unique(forward, source, target, forward_seen)
+ _append_unique(reverse, target, source, reverse_seen)
+ _append_unique(call_only, source, target, call_only_seen)
+ for source, target, edge_type, origin, call_lines in edge_rows:
+ self._ingest_edge(
+ declaration_map,
+ declaration_seen,
+ forward,
+ forward_seen,
+ reverse,
+ reverse_seen,
+ by_caller_line,
+ caller_line_seen,
+ call_only,
+ call_only_seen,
+ callers_with_site_metadata,
+ source,
+ target,
+ edge_type,
+ origin,
+ tuple(call_lines or ()),
+ )
+
+ self.declares = {key: tuple(values) for key, values in declaration_map.items()}
+ self.forward = {key: tuple(values) for key, values in forward.items()}
+ self.calls = self.forward
+ self.reverse = {key: tuple(values) for key, values in reverse.items()}
+ self._by_caller_line = {key: tuple(values) for key, values in by_caller_line.items()}
+ self._call_only = {key: tuple(values) for key, values in call_only.items()}
+ self._callers_with_site_metadata = frozenset(callers_with_site_metadata)
+ self._by_file_line = {key: min(values) for key, values in by_file_line_candidates.items()}
+ self._ranges = {path: tuple(values) for path, values in ranges.items()}
+ self.in_degree = {node: len(callers) for node, callers in self.reverse.items()}
+
+ @staticmethod
+ def _ingest_edge(
+ declares: dict[str, list[str]],
+ declaration_seen: set[tuple[str, str]] | None,
+ forward: dict[str, list[str]],
+ forward_seen: set[tuple[str, str]] | None,
+ reverse: dict[str, list[str]],
+ reverse_seen: set[tuple[str, str]] | None,
+ by_caller_line: dict[tuple[str, int], list[str]],
+ caller_line_seen: set[tuple[tuple[str, int], str]] | None,
+ call_only: dict[str, list[str]],
+ call_only_seen: set[tuple[str, str]] | None,
+ callers_with_site_metadata: set[str],
+ source: str,
+ target: str,
+ edge_type: str | None,
+ origin: str | None,
+ call_lines: Iterable[int],
+ ) -> None:
+ if edge_type == "defines":
+ _append_unique(declares, source, target, declaration_seen)
+ return
+ if not is_reliable_execution_edge(edge_type, origin):
+ return
+ _append_unique(forward, source, target, forward_seen)
+ _append_unique(reverse, target, source, reverse_seen)
+ if edge_type == "calls":
+ _append_unique(call_only, source, target, call_only_seen)
+ for line in call_lines:
+ if isinstance(line, int) and line > 0:
+ callers_with_site_metadata.add(source)
+ _append_unique(by_caller_line, (source, line), target, caller_line_seen)
+
+ def resolve_function(self, path: str, func_start: int) -> str | None:
+ """Resolve a function definition, tolerating decorator line offsets."""
+ if func_start == 0:
+ module = module_node_id(path)
+ return module if module in self.nodes else None
+ exact = self._by_file_line.get((path, func_start))
+ if exact is not None:
+ return exact
+ best: str | None = None
+ best_start = -1
+ for start, end, node_id in self._ranges.get(path, ()):
+ if start <= func_start <= end and (
+ start > best_start or (start == best_start and (best is None or node_id < best))
+ ):
+ best, best_start = node_id, start
+ return best
+
+ def resolve_call_targets(
+ self, caller: str, call_line: int, target_name: str
+ ) -> tuple[tuple[str, ...], CallTargetBasis]:
+ """Resolve a direct call using exact site evidence, then old-index fallback.
+
+ New graphs preserve call lines. Rehydrated indexes created before that
+ fact existed have none, so they retain the previous resolved-callee name
+ match until the next index refresh.
+ """
+ at_site = self._by_caller_line.get((caller, call_line))
+ if at_site:
+ named = tuple(node for node in at_site if self.name.get(node) == target_name)
+ return named, "call-site"
+ if caller in self._callers_with_site_metadata:
+ # A refreshed caller can legitimately contain an unresolved site.
+ # Falling back here would let a different same-named call fabricate
+ # a target for it. Only callers with no site facts are legacy.
+ return (), "call-site"
+ return (
+ tuple(
+ node
+ for node in self._call_only.get(caller, ())
+ if self.name.get(node) == target_name
+ ),
+ "name-fallback",
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class ReachInfo:
+ distance: int
+ next_hop: str | None
+ sink: str
+
+
+def reachable_to_sink(
+ sink_nodes: Iterable[str],
+ predecessors: Callable[[str], Iterable[str]],
+ *,
+ max_depth: int = 3,
+) -> dict[str, ReachInfo]:
+ """Map every node within *max_depth* forward hops of a sink."""
+ if max_depth < 0:
+ return {}
+ info: dict[str, ReachInfo] = {}
+ queue: deque[str] = deque()
+ for sink in sink_nodes:
+ if sink not in info:
+ info[sink] = ReachInfo(distance=0, next_hop=None, sink=sink)
+ queue.append(sink)
+ while queue:
+ node = queue.popleft()
+ current = info[node]
+ if current.distance >= max_depth:
+ continue
+ for predecessor in predecessors(node):
+ if predecessor in info:
+ continue
+ info[predecessor] = ReachInfo(
+ distance=current.distance + 1,
+ next_hop=node,
+ sink=current.sink,
+ )
+ queue.append(predecessor)
+ return info
+
+
+def path_to_sink(node: str, info: Mapping[str, ReachInfo], *, max_len: int = 16) -> list[str]:
+ """Reconstruct ``[node, ..., sink]`` from a reverse-walk result."""
+ if node not in info:
+ return []
+ path = [node]
+ seen = {node}
+ current = info[node]
+ while current.next_hop is not None and len(path) < max_len:
+ next_hop = current.next_hop
+ if next_hop in seen:
+ break
+ path.append(next_hop)
+ seen.add(next_hop)
+ next_info = info.get(next_hop)
+ if next_info is None:
+ break
+ current = next_info
+ return path
+
+
+__all__ = [
+ "UNRELIABLE_EXECUTION_ORIGINS",
+ "ExecutionGraphIndex",
+ "ReachInfo",
+ "file_of_symbol",
+ "is_reliable_execution_edge",
+ "module_node_id",
+ "path_to_sink",
+ "reachable_to_sink",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 580b88677..49a5122c0 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -37,10 +37,7 @@ from ...ingestion.git_indexer.function_blame import (
from ...ingestion.package_roots import module_for as _module_for
from ...ingestion.package_roots import package_roots_from_paths as _package_roots
from ...ingestion.package_roots import scan_package_roots as _scan_package_roots
-from ..test_reachability import (
- call_graph_from_graph,
- files_reached_by_tests,
-)
+from ..test_reachability import files_reached_by_tests
from .biomarkers import FileContext, detect_all
from .biomarkers.base import HasEdge
from .complexity import FileComplexity, FunctionComplexity, walk_file
@@ -94,7 +91,9 @@ log = structlog.get_logger(__name__)
# file, so they should not wait out the decay timer.
# 3: that signal moved from the import graph to the call graph, so the same two
# values are wrong again on an index stamped 2 - this time in both directions.
-HEALTH_ANALYZER_VERSION = 3
+# 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
# 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.
@@ -336,6 +335,13 @@ class HealthAnalyzer:
self.repo_root = repo_root
self._package_roots_cache: set[str] | None = None
self._tests_reach_cache: set[str] | None = None
+ self._execution_graph_cache: CallGraphIndex | None = None
+
+ def _execution_graph(self) -> CallGraphIndex | None:
+ """Build the reliable execution index at most once per analysis."""
+ if self.graph is not None and self._execution_graph_cache is None:
+ self._execution_graph_cache = CallGraphIndex(self.graph)
+ return self._execution_graph_cache
def _files_reached_by_tests(self) -> set[str]:
"""Non-test files that some test file can execute into, per the call graph.
@@ -354,8 +360,9 @@ class HealthAnalyzer:
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(
- call_graph_from_graph(self.graph), test_files
+ index or CallGraphIndex(), test_files
)
return self._tests_reach_cache
@@ -772,7 +779,7 @@ class HealthAnalyzer:
"""Run the graph-dependent perf passes over the walked files, in place.
Four sources of extra ``perf_hits``, all sharing one
- :class:`CallGraphIndex` (built once over the resolved ``calls`` graph):
+ :class:`CallGraphIndex` (built once over reliable execution edges):
1. cross-function ``io_in_loop`` / N+1 (PR4);
2. cross-function ``blocking_io_under_lock`` (Phase 7b) — the lock→I/O
@@ -789,7 +796,7 @@ class HealthAnalyzer:
ship a centrality-gated marker we cannot establish centrality for).
"""
try:
- index = CallGraphIndex(self.graph) if self.graph is not None else None
+ index = self._execution_graph()
by_file: dict[str, list] = {}
if self.graph is not None and index is not None:
for src in (
diff --git a/packages/core/src/repowise/core/analysis/health/perf/callgraph.py b/packages/core/src/repowise/core/analysis/health/perf/callgraph.py
index 96c7029f6..af294ad37 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/callgraph.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/callgraph.py
@@ -1,91 +1,11 @@
-"""Shared one-pass index of the resolved ``calls`` graph.
+"""Compatibility imports for the shared execution-graph index.
-Both the cross-function N+1 bridge (:mod:`.crossfn`) and the centrality gate
-(:mod:`.ranking`, Primitive 2) need the same three things off the engine's
-resolved dependency graph: a symbol-node name lookup, a ``calls`` adjacency in
-both directions, and a resolver from ``(file, def-line)`` to a symbol-node id.
-Building it once and sharing it keeps the graph passes to a single ``O(V + E)``
-scan per ``analyze()`` instead of one per consumer.
-
-Extracted verbatim from ``crossfn._CallGraphIndex`` (the 6a/PR4 shape) so the
-behaviour the cross-function precision study measured is unchanged; the only
-difference is that it is now importable by the ranker too.
+The implementation lives outside the performance package so performance and
+test intelligence cannot drift on edge policy or graph construction.
"""
-from __future__ import annotations
-
-from typing import Any
-
-
-def module_node_id(path: str) -> str:
- """The synthetic ``::__module__`` symbol-node id for a file's module scope."""
- return f"{path}::__module__"
-
-
-class CallGraphIndex:
- """One-pass index of the dependency graph for the perf graph passes.
-
- Holds only what the passes need: symbol-node name lookup, a ``calls``
- adjacency in both directions, and a resolver from ``(file, def-line)`` to a
- symbol-node id. Built once; never mutates the source graph.
- """
-
- __slots__ = ("_by_file_line", "_ranges", "forward", "in_degree", "name", "nodes", "reverse")
-
- def __init__(self, graph: Any) -> None:
- self.nodes: set[str] = set()
- self.name: dict[str, str] = {}
- self.forward: dict[str, list[str]] = {}
- self.reverse: dict[str, list[str]] = {}
- # Exact (path, start_line) -> symbol id, plus a per-file range list for
- # the containment fallback when a def line doesn't match exactly.
- self._by_file_line: dict[tuple[str, int], str] = {}
- self._ranges: dict[str, list[tuple[int, int, str]]] = {}
-
- for node_id, attrs in graph.nodes(data=True):
- self.nodes.add(node_id)
- if attrs.get("node_type") != "symbol":
- continue
- self.name[node_id] = attrs.get("name") or ""
- path = attrs.get("file_path")
- if not path:
- continue
- start = attrs.get("start_line")
- end = attrs.get("end_line")
- if isinstance(start, int):
- self._by_file_line.setdefault((path, start), node_id)
- if isinstance(end, int):
- self._ranges.setdefault(path, []).append((start, end, node_id))
-
- for src, dst, data in graph.edges(data=True):
- if data.get("edge_type") != "calls":
- continue
- self.forward.setdefault(src, []).append(dst)
- self.reverse.setdefault(dst, []).append(src)
-
- # Distinct direct callers per node (the centrality proxy used by the
- # ranker). Computed off the reverse adjacency in one pass.
- self.in_degree: dict[str, int] = {
- node: len(set(callers)) for node, callers in self.reverse.items()
- }
+from repowise.core.analysis.execution_graph import ExecutionGraphIndex, module_node_id
- def resolve_function(self, path: str, func_start: int) -> str | None:
- """Symbol-node id for the function defined at ``func_start`` in ``path``.
+CallGraphIndex = ExecutionGraphIndex
- ``func_start == 0`` is module scope (the synthetic ``::__module__``
- node). Otherwise prefer an exact def-line match, then fall back to the
- innermost symbol whose line range contains ``func_start`` (tolerates a
- decorator/def off-by-one without matching an enclosing scope).
- """
- if func_start == 0:
- mod = module_node_id(path)
- return mod if mod in self.nodes else None
- exact = self._by_file_line.get((path, func_start))
- if exact is not None:
- return exact
- best: str | None = None
- best_start = -1
- for start, end, node_id in self._ranges.get(path, ()):
- if start <= func_start <= end and start > best_start:
- best, best_start = node_id, start
- return best
+__all__ = ["CallGraphIndex", "ExecutionGraphIndex", "module_node_id"]
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 c222ed6c0..db607c5c0 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
@@ -33,11 +33,10 @@ Soundness (honest limits — these cap recall, never precision):
loop-nested callee* to the sink (per the design); the loop owner ``A`` is
one further labelling hop in the reported path, not a counted reachability
hop. Chains longer than that from the callee are not followed.
- * **First-hop name match.** The loop-nested callee is matched to one of the
- loop owner's *resolved* graph callees by name. The resolver did the real
- binding; the name only selects which of the owner's calls were in a loop.
- Two distinct callees sharing a name under one function (rare) could let an
- out-of-loop edge stand in for the in-loop one.
+ * **First-hop compatibility.** New indexes retain the resolved call's source
+ line, so the loop-nested call selects the exact graph edge. Indexes created
+ before that fact existed fall back to matching the owner's resolved callees
+ by name until the next refresh.
* **Incremental runs.** When only a subset of files is walked, a sink-holding
callee that was not itself re-walked is absent from the sink set; full
detection requires a whole-repo analyze (the index recomputes there).
@@ -150,17 +149,13 @@ def _hits_for_function(
callees = index.forward.get(a_sid)
if not callees:
return []
- # Index the owner's resolved callees by name for the first-hop match.
- callees_by_name: dict[str, list[str]] = {}
- for c in callees:
- callees_by_name.setdefault(index.name.get(c, ""), []).append(c)
-
hits: list[PerfHit] = []
seen: set[str] = set()
for target_name, call_line in fact.loop_call_targets:
if target_name in seen:
continue
- for callee in callees_by_name.get(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:
continue
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 fce54036d..fd2d90afc 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/gated.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/gated.py
@@ -170,16 +170,13 @@ def _lock_hits_for_function(
callees = index.forward.get(a_sid)
if not callees:
return []
- callees_by_name: dict[str, list[str]] = {}
- for c in callees:
- callees_by_name.setdefault(index.name.get(c, ""), []).append(c)
-
hits: list[PerfHit] = []
seen: set[str] = set()
for target_name, call_line in fact.lock_call_targets:
if target_name in seen:
continue
- for callee in callees_by_name.get(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:
continue
diff --git a/packages/core/src/repowise/core/analysis/health/perf/ranking.py b/packages/core/src/repowise/core/analysis/health/perf/ranking.py
index 02250dc99..bca8fb28b 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/ranking.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/ranking.py
@@ -10,8 +10,8 @@ in a hot, request-reachable function. The gate fires those markers *only there*.
"Hot" combines two whole-program signals a file-local linter cannot compute:
* **centrality** — the function's symbol node has a top-quintile number of
- distinct direct callers in the resolved ``calls`` graph (the ``CallGraphIndex``
- in-degree). A widely-called function is on many request paths, so a latency
+ distinct direct predecessors in the reliable execution graph (the
+ ``CallGraphIndex`` in-degree). A widely-reached function is on many request paths, so a latency
or quadratic cost there is paid often. Direct in-degree is a deterministic,
``O(E)`` proxy for request-reachability; transitive fan-in would be stronger
but is quadratic to compute per function.
diff --git a/packages/core/src/repowise/core/analysis/health/perf/reachability.py b/packages/core/src/repowise/core/analysis/health/perf/reachability.py
index 7b0b871f8..2743f8fc9 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/reachability.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/reachability.py
@@ -1,119 +1,9 @@
-"""Bounded-depth reachability to a typed sink (sink-agnostic).
+"""Compatibility imports for shared execution-graph path reachability."""
-This is *Primitive 3* of the performance-pillar arc: the engine that answers
-"starting from this node and following call edges, does a path of at most
-``max_depth`` hops reach a node that satisfies a sink predicate?" — and, when
-it does, returns the path for explainability.
+from repowise.core.analysis.execution_graph import (
+ ReachInfo,
+ path_to_sink,
+ reachable_to_sink,
+)
-It is built for cross-function N+1 detection (a loop in function ``A`` calls a
-helper that, transitively, executes an I/O boundary), but **nothing here is
-performance-specific**. The two things that vary between use cases are both
-parameters:
-
- * **the sink set** — the caller passes the node ids that *are* sinks. For
- performance that is "functions holding a bare I/O sink"; the identical walk
- serves static security taint (``sink = dangerous API``) and architecture
- conformance (``sink = forbidden layer``) by passing a different set.
- * **the adjacency** — the caller passes a ``predecessors`` callable (the
- *reverse* of the edge direction being followed). The walk never imports a
- graph library; it only calls ``predecessors(node)``.
-
-**Why a reverse BFS from the sinks.** The question "can N reach a sink within K
-forward hops?" is answered for *every* N at once by a single multi-source BFS
-that starts at the sinks and walks edges backwards. Each node and edge within
-the depth bound is visited once, so the whole repo's reachability is computed
-in one ``O(V + E)`` pass (bounded by ``max_depth``) and is memoized by
-construction — there is no per-query re-walk and no risk of blow-up on a dense
-call graph. This is what keeps the cross-function pass inside the index-time
-budget.
-"""
-
-from __future__ import annotations
-
-from collections import deque
-from collections.abc import Callable, Iterable
-from dataclasses import dataclass
-
-
-@dataclass(frozen=True, slots=True)
-class ReachInfo:
- """How a node reaches its nearest sink along the bounded walk.
-
- ``distance`` is the number of forward hops to ``sink`` (0 when the node is
- itself a sink). ``next_hop`` is the successor one step closer to the sink
- (``None`` for a sink). Follow ``next_hop`` repeatedly to recover the path.
- """
-
- distance: int
- next_hop: str | None
- sink: str
-
-
-def reachable_to_sink(
- sink_nodes: Iterable[str],
- predecessors: Callable[[str], Iterable[str]],
- *,
- max_depth: int = 3,
-) -> dict[str, ReachInfo]:
- """Map every node within ``max_depth`` forward hops of a sink to a :class:`ReachInfo`.
-
- ``sink_nodes`` are the nodes that satisfy the (caller-defined) sink
- predicate. ``predecessors(node)`` yields the nodes with a forward edge
- *into* ``node`` (i.e. reverse adjacency). The result contains an entry for
- each sink (distance 0) and for each node that can reach some sink in
- ``1..max_depth`` forward hops; nodes that cannot reach a sink are absent.
-
- Deterministic: BFS visits nodes in non-decreasing distance, so the first
- (and recorded) distance for any node is the minimum, and the recorded
- ``sink`` is the nearest one (ties broken by BFS/seed order).
- """
- if max_depth < 0:
- return {}
-
- info: dict[str, ReachInfo] = {}
- queue: deque[str] = deque()
- for s in sink_nodes:
- if s not in info:
- info[s] = ReachInfo(distance=0, next_hop=None, sink=s)
- queue.append(s)
-
- while queue:
- node = queue.popleft()
- cur = info[node]
- if cur.distance >= max_depth:
- continue
- for pred in predecessors(node):
- if pred in info:
- continue # already reached at an equal-or-shorter distance
- info[pred] = ReachInfo(
- distance=cur.distance + 1,
- next_hop=node,
- sink=cur.sink,
- )
- queue.append(pred)
- return info
-
-
-def path_to_sink(node: str, info: dict[str, ReachInfo], *, max_len: int = 16) -> list[str]:
- """Reconstruct ``[node, ..., sink]`` by following ``next_hop`` pointers.
-
- Returns ``[]`` when ``node`` has no :class:`ReachInfo` (it does not reach a
- sink within the bound). ``max_len`` is a defensive cap so a corrupted
- pointer chain can never loop forever; it is never hit for a BFS-built map
- bounded at a small ``max_depth``.
- """
- if node not in info:
- return []
- path: list[str] = [node]
- cur = info[node]
- seen = {node}
- while cur.next_hop is not None and len(path) < max_len:
- nxt = cur.next_hop
- if nxt in seen: # impossible for a BFS map; defensive only
- break
- path.append(nxt)
- seen.add(nxt)
- cur = info.get(nxt)
- if cur is None:
- break
- return path
+__all__ = ["ReachInfo", "path_to_sink", "reachable_to_sink"]
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index 419a825bc..0012e0cf5 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -147,16 +147,19 @@ over data already in the database.
from __future__ import annotations
+import json
from dataclasses import dataclass
-from typing import Any, Literal
+from typing import Any, Literal, TypeAlias
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
-from repowise.core.ingestion.models import (
- EXECUTION_EDGE_TYPES,
- FILE_DEPENDENCY_EDGE_TYPES,
+from repowise.core.analysis.execution_graph import (
+ UNRELIABLE_EXECUTION_ORIGINS,
+ ExecutionGraphIndex,
+ file_of_symbol,
)
+from repowise.core.ingestion.models import EXECUTION_EDGE_TYPES, FILE_DEPENDENCY_EDGE_TYPES
from repowise.core.persistence.models import GraphNode
# How many call hops a test may take and still be said to reach a file. The walk
@@ -168,7 +171,7 @@ DEFAULT_CALL_DEPTH = 3
DEFAULT_MAX_DEPTH = 1
# Call edges whose resolver only matched a name. See the Confidence section.
-UNRELIABLE_CALL_ORIGINS = frozenset({"global_unique"})
+UNRELIABLE_CALL_ORIGINS = UNRELIABLE_EXECUTION_ORIGINS
# Cap on how many test files one target reports. The consumers all cut their
# own lists shorter; the cap exists so a helper called from every test in the
@@ -195,17 +198,7 @@ __all__ = [
]
-@dataclass(frozen=True)
-class CallGraphView:
- """The two adjacencies a call-graph reachability walk needs.
-
- ``declares`` bridges the file layer to the symbol layer - nothing points
- from a symbol back to a file, so without it a walk cannot start at a test
- file. ``calls`` is the symbol-to-symbol adjacency, already origin-filtered.
- """
-
- declares: dict[str, set[str]]
- calls: dict[str, set[str]]
+CallGraphView: TypeAlias = ExecutionGraphIndex
@dataclass(frozen=True)
@@ -224,11 +217,6 @@ class ReachedBy:
total: int = 0
-def _file_of(symbol_id: str) -> str:
- """The file a symbol node belongs to. Node ids are ``path::Name``."""
- return symbol_id.split("::", 1)[0]
-
-
def call_graph_from_graph(graph: Any) -> CallGraphView:
"""Build the call-reachability view from an in-memory NetworkX graph.
@@ -239,25 +227,7 @@ def call_graph_from_graph(graph: Any) -> CallGraphView:
Returns an empty view for ``None`` - the health engine runs without a graph
on some paths, and the documented outcome there is "no signal".
"""
- declares: dict[str, set[str]] = {}
- calls: dict[str, set[str]] = {}
- if graph is None:
- return CallGraphView(declares, calls)
- try:
- edges = graph.edges(data=True)
- except Exception:
- return CallGraphView(declares, calls)
- for src, dst, data in edges:
- attrs = data or {}
- edge_type = attrs.get("edge_type")
- if edge_type == "defines":
- declares.setdefault(src, set()).add(dst)
- elif (
- edge_type in EXECUTION_EDGE_TYPES
- and attrs.get("resolution_origin") not in UNRELIABLE_CALL_ORIGINS
- ):
- calls.setdefault(src, set()).add(dst)
- return CallGraphView(declares, calls)
+ return ExecutionGraphIndex(graph)
async def call_graph_from_db(session: AsyncSession, repo_id: str) -> CallGraphView:
@@ -273,25 +243,27 @@ async def call_graph_from_db(session: AsyncSession, repo_id: str) -> CallGraphVi
repository, and a per-level ``IN`` list over every file is the shape it was
explicitly not built for.
"""
- declares: dict[str, set[str]] = {}
- calls: dict[str, set[str]] = {}
wanted = ["defines", *sorted(EXECUTION_EDGE_TYPES)]
params: dict[str, Any] = {"repo_id": repo_id}
ets = _in_clause("e", wanted, params)
rows = await session.execute(
text(
- "SELECT source_node_id, target_node_id, edge_type, resolution_origin "
+ "SELECT source_node_id, target_node_id, edge_type, resolution_origin, "
+ "call_lines_json "
"FROM graph_edges WHERE repository_id = :repo_id "
- f"AND edge_type IN ({ets})"
+ f"AND edge_type IN ({ets}) "
+ "ORDER BY source_node_id, target_node_id, edge_type"
),
params,
)
- for src, dst, edge_type, origin in rows:
- if edge_type == "defines":
- declares.setdefault(src, set()).add(dst)
- elif origin not in UNRELIABLE_CALL_ORIGINS:
- calls.setdefault(src, set()).add(dst)
- return CallGraphView(declares, calls)
+ edge_rows = []
+ for src, dst, edge_type, origin, call_lines_json in rows:
+ try:
+ call_lines = json.loads(call_lines_json or "[]")
+ except (TypeError, ValueError):
+ call_lines = []
+ edge_rows.append((src, dst, edge_type, origin, call_lines))
+ return ExecutionGraphIndex(edge_rows=edge_rows)
def files_reached_by_tests(
@@ -315,7 +287,7 @@ def files_reached_by_tests(
frontier: set[str] = set()
for path in test_files:
- frontier |= view.declares.get(path, frozenset())
+ frontier.update(view.declares.get(path, ()))
seen = set(frontier)
# The seeds are what the tests *declare*, not what they reach. Counting them
# would make containment alone a claim of reaching.
@@ -323,14 +295,14 @@ def files_reached_by_tests(
for _ in range(max_depth):
nxt: set[str] = set()
for node in frontier:
- nxt |= view.calls.get(node, frozenset())
+ nxt.update(view.calls.get(node, ()))
nxt -= seen
if not nxt:
break
seen |= nxt
reached |= nxt
frontier = nxt
- return {_file_of(symbol) for symbol in reached} - test_files
+ return {file_of_symbol(symbol) for symbol in reached} - test_files
async def load_test_files(session: AsyncSession, repo_id: str) -> set[str]:
@@ -402,9 +374,7 @@ async def tests_reaching_by_tier(
unanswered = [seed for seed in seeds if seed not in out]
if unanswered and import_depth >= 1:
- found = await _import_reaching(
- session, repo_id, unanswered, test_files, import_depth
- )
+ found = await _import_reaching(session, repo_id, unanswered, test_files, import_depth)
for seed, tests in found.items():
out[seed] = ReachedBy(_cut(tests), "import-graph", len(tests))
return out
@@ -448,10 +418,10 @@ async def _call_reaching(
sorted(EXECUTION_EDGE_TYPES),
UNRELIABLE_CALL_ORIGINS,
):
- carried = origins.get(callee, frozenset())
+ carried = origins.get(callee)
if not carried:
continue
- owner = _file_of(caller)
+ owner = file_of_symbol(caller)
if owner in test_files:
for seed in carried:
found.setdefault(seed, set()).add(owner)
@@ -490,7 +460,7 @@ async def _import_reaching(
for dependent, dependency in await _edges_into(
session, repo_id, level, sorted(FILE_DEPENDENCY_EDGE_TYPES), frozenset()
):
- carried = origins.get(dependency, frozenset())
+ carried = origins.get(dependency)
if not carried:
continue
if dependent in test_files:
@@ -563,9 +533,7 @@ async def _edges_into(
# NULL means the row predates the vocabulary, not "unknown", so it has
# to survive the filter, and a bare NOT IN would drop it.
bad = _in_clause("o", sorted(excluded_origins), params)
- origin_filter = (
- f" AND (resolution_origin IS NULL OR resolution_origin NOT IN ({bad}))"
- )
+ origin_filter = f" AND (resolution_origin IS NULL OR resolution_origin NOT IN ({bad}))"
rows = await session.execute(
text(
"SELECT DISTINCT source_node_id, target_node_id FROM graph_edges "
diff --git a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
index 9e966a341..983c653d6 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_rehydrate.py
@@ -79,11 +79,7 @@ class RehydrateMixin:
node_id = node.get("node_id")
if node_id is None:
continue
- attrs = {
- key: node[key]
- for key in _NODE_ATTR_KEYS
- if node.get(key) is not None
- }
+ attrs = {key: node[key] for key in _NODE_ATTR_KEYS if node.get(key) is not None}
# ``parent_symbol_id`` is persisted under that name but the live
# graph uses ``parent_name`` (see GraphBuilder.add_file).
if "parent_symbol_id" in attrs:
@@ -113,6 +109,9 @@ class RehydrateMixin:
resolution_origin = edge.get("resolution_origin")
if resolution_origin:
edge_attrs["resolution_origin"] = resolution_origin
+ call_lines = edge.get("call_lines")
+ if call_lines:
+ edge_attrs["call_lines"] = list(call_lines)
graph.add_edge(source, target, **edge_attrs)
edge_count += 1
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 5d5085d26..49194e8e1 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -575,6 +575,7 @@ class ResolveMixin:
edge_type="calls",
confidence=rc.confidence,
resolution_origin=rc.origin,
+ call_lines=[rc.line],
)
total_resolved += 1
else:
@@ -582,6 +583,10 @@ class ResolveMixin:
# strongest wins, and the origin has to follow the
# confidence it explains.
existing = self._graph[rc.caller_id][rc.callee_id]
+ lines = existing.setdefault("call_lines", [])
+ if rc.line not in lines:
+ lines.append(rc.line)
+ lines.sort()
if rc.confidence > existing.get("confidence", 0):
existing["confidence"] = rc.confidence
existing["resolution_origin"] = rc.origin
diff --git a/packages/core/src/repowise/core/persistence/crud/graph.py b/packages/core/src/repowise/core/persistence/crud/graph.py
index b2caec17b..6246d79fb 100644
--- a/packages/core/src/repowise/core/persistence/crud/graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/graph.py
@@ -87,6 +87,9 @@ def _update_graph_edge(existing: GraphEdge, edge_data: dict) -> None:
# cohesion (a real import statement appears between two package siblings)
# must lose the stamp, or cycle detection keeps skipping it forever.
existing.hint_source = edge_data.get("hint_source")
+ call_lines = edge_data.get("call_lines_json")
+ if call_lines is not None:
+ existing.call_lines_json = call_lines
confidence = edge_data.get("confidence")
if confidence is not None:
# Keep the max on collision, mirroring the in-memory resolver
@@ -167,7 +170,7 @@ async def batch_upsert_graph_edges(
Each element of *edges* should have ``source_node_id``, ``target_node_id``,
``edge_type``, and optionally ``imported_names_json``, ``confidence``,
- ``hint_source`` and ``resolution_origin``.
+ ``hint_source``, ``resolution_origin`` and ``call_lines_json``.
The unique constraint is (repository_id, source, target, edge_type),
allowing multiple edge types between the same pair of nodes.
@@ -194,6 +197,7 @@ async def batch_upsert_graph_edges(
confidence=e.get("confidence", 1.0),
hint_source=e.get("hint_source"),
resolution_origin=e.get("resolution_origin"),
+ call_lines_json=e.get("call_lines_json", "[]"),
),
)
@@ -288,6 +292,7 @@ async def reconcile_edges_for_files(
confidence=e.get("confidence", 1.0),
hint_source=e.get("hint_source"),
resolution_origin=e.get("resolution_origin"),
+ call_lines_json=e.get("call_lines_json", "[]"),
)
)
await session.flush()
@@ -513,6 +518,10 @@ async def get_all_graph_edges(
imported_names = json.loads(row.imported_names_json or "[]")
except (ValueError, TypeError):
imported_names = []
+ try:
+ call_lines = json.loads(row.call_lines_json or "[]")
+ except (ValueError, TypeError):
+ call_lines = []
edges.append(
{
"source_node_id": row.source_node_id,
@@ -522,6 +531,7 @@ async def get_all_graph_edges(
"imported_names": imported_names,
"hint_source": row.hint_source,
"resolution_origin": row.resolution_origin,
+ "call_lines": call_lines,
}
)
return edges
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 5853c8067..c3fe89707 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -320,6 +320,12 @@ class GraphEdge(Base):
# Persisted because the graph is rehydrated from these rows, so an
# unpersisted origin would exist only on the indexing run that minted it.
resolution_origin: Mapped[str | None] = mapped_column(String(32), nullable=True)
+ # Resolved call sites collapse to one graph edge per symbol pair. Preserve
+ # every source line so consumers can identify the exact first hop without
+ # reparsing the repository. JSON keeps the additive migration portable.
+ call_lines_json: Mapped[str] = mapped_column(
+ Text, nullable=False, default="[]", server_default="[]"
+ )
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 2a499ea9e..aab7975f6 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -490,6 +490,7 @@ def _changed_file_edges(
"confidence": data.get("confidence", 1.0),
"hint_source": data.get("hint_source"),
"resolution_origin": data.get("resolution_origin"),
+ "call_lines_json": json.dumps(data.get("call_lines", [])),
}
)
return sorted(reconcile), edges
@@ -1368,6 +1369,7 @@ async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:
"confidence": data.get("confidence", 1.0),
"hint_source": data.get("hint_source"),
"resolution_origin": data.get("resolution_origin"),
+ "call_lines_json": json.dumps(data.get("call_lines", [])),
}
)
if edges:
diff --git a/tests/unit/analysis/test_execution_graph.py b/tests/unit/analysis/test_execution_graph.py
new file mode 100644
index 000000000..a4297cbe9
--- /dev/null
+++ b/tests/unit/analysis/test_execution_graph.py
@@ -0,0 +1,104 @@
+"""The execution graph is one policy and one index for every consumer."""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.analysis.execution_graph import (
+ ExecutionGraphIndex,
+ is_reliable_execution_edge,
+)
+from repowise.core.ingestion.models import EXECUTION_EDGE_TYPES
+
+
+def _symbol(graph, node_id, path, name, start, end):
+ graph.add_node(
+ node_id,
+ node_type="symbol",
+ file_path=path,
+ name=name,
+ start_line=start,
+ end_line=end,
+ )
+
+
+def test_execution_vocabulary_has_one_reliability_predicate():
+ for edge_type in EXECUTION_EDGE_TYPES:
+ assert is_reliable_execution_edge(edge_type, None)
+ assert is_reliable_execution_edge(edge_type, "same_file")
+ assert not is_reliable_execution_edge(edge_type, "global_unique")
+ assert not is_reliable_execution_edge("references", None)
+ assert not is_reliable_execution_edge("reads", None)
+ assert not is_reliable_execution_edge("imports", None)
+
+
+def test_index_builds_all_views_in_one_pass_and_deduplicates_edges():
+ graph = nx.MultiDiGraph()
+ _symbol(graph, "t.py::test", "t.py", "test", 2, 5)
+ _symbol(graph, "a.py::base", "a.py", "base", 10, 20)
+ _symbol(graph, "a.py::impl", "a.py", "impl", 22, 30)
+ graph.add_edge("t.py", "t.py::test", edge_type="defines")
+ graph.add_edge("t.py::test", "a.py::base", edge_type="calls", call_lines=[3])
+ graph.add_edge("a.py::base", "a.py::impl", edge_type="dispatches_to")
+ graph.add_edge("a.py::base", "a.py::impl", edge_type="dispatches_to")
+ graph.add_edge(
+ "t.py::test",
+ "bad.py::guess",
+ edge_type="calls",
+ resolution_origin="global_unique",
+ )
+ graph.add_edge("t.py::test", "a.py::mentioned", edge_type="references")
+
+ index = ExecutionGraphIndex(graph)
+
+ assert index.declares == {"t.py": ("t.py::test",)}
+ assert index.forward == {
+ "t.py::test": ("a.py::base",),
+ "a.py::base": ("a.py::impl",),
+ }
+ assert index.reverse["a.py::impl"] == ("a.py::base",)
+ assert index.in_degree["a.py::impl"] == 1
+ assert index.resolve_call_targets("t.py::test", 3, "base") == (
+ ("a.py::base",),
+ "call-site",
+ )
+
+
+def test_definition_lookup_prefers_exact_then_innermost_range():
+ graph = nx.DiGraph()
+ _symbol(graph, "a.py::outer", "a.py", "outer", 2, 20)
+ _symbol(graph, "a.py::inner", "a.py", "inner", 7, 10)
+ graph.add_node("a.py::__module__", node_type="symbol", name="__module__")
+ index = ExecutionGraphIndex(graph)
+
+ assert index.resolve_function("a.py", 7) == "a.py::inner"
+ assert index.resolve_function("a.py", 8) == "a.py::inner"
+ assert index.resolve_function("a.py", 15) == "a.py::outer"
+ assert index.resolve_function("a.py", 0) == "a.py::__module__"
+
+
+def test_old_index_without_call_lines_uses_labelled_name_fallback():
+ graph = nx.DiGraph()
+ _symbol(graph, "a.py::owner", "a.py", "owner", 1, 5)
+ _symbol(graph, "b.py::load", "b.py", "load", 1, 5)
+ _symbol(graph, "c.py::load", "c.py", "load", 1, 5)
+ graph.add_edge("a.py::owner", "b.py::load", edge_type="calls")
+ graph.add_edge("a.py::owner", "c.py::load", edge_type="dispatches_to")
+
+ assert ExecutionGraphIndex(graph).resolve_call_targets("a.py::owner", 4, "load") == (
+ ("b.py::load",),
+ "name-fallback",
+ )
+
+
+def test_refreshed_caller_does_not_fallback_for_an_unresolved_call_site():
+ graph = nx.DiGraph()
+ _symbol(graph, "a.py::owner", "a.py", "owner", 1, 8)
+ _symbol(graph, "db.py::load", "db.py", "load", 1, 5)
+ # db.load() resolved outside the loop; obj.load() at line 6 did not resolve.
+ graph.add_edge("a.py::owner", "db.py::load", edge_type="calls", call_lines=[3])
+
+ assert ExecutionGraphIndex(graph).resolve_call_targets("a.py::owner", 6, "load") == (
+ (),
+ "call-site",
+ )
diff --git a/tests/unit/analysis/test_test_reachability.py b/tests/unit/analysis/test_test_reachability.py
index 7b706593b..ec4a7ce0d 100644
--- a/tests/unit/analysis/test_test_reachability.py
+++ b/tests/unit/analysis/test_test_reachability.py
@@ -130,8 +130,8 @@ def test_containment_bridges_files_to_symbols_and_nothing_else():
]
)
view = call_graph_from_graph(graph)
- assert view.declares == {"tests/test_a.py": {"tests/test_a.py::test_x"}}
- assert view.calls == {"tests/test_a.py::test_x": {"src/a.py::run"}}
+ assert view.declares == {"tests/test_a.py": ("tests/test_a.py::test_x",)}
+ assert view.calls == {"tests/test_a.py::test_x": ("src/a.py::run",)}
def test_name_only_resolutions_are_dropped():
@@ -148,7 +148,7 @@ def test_name_only_resolutions_are_dropped():
("t.py::test", "c.py::h", {"edge_type": "calls"}),
]
)
- assert call_graph_from_graph(graph).calls == {"t.py::test": {"b.py::g", "c.py::h"}}
+ assert call_graph_from_graph(graph).calls == {"t.py::test": ("b.py::g", "c.py::h")}
def test_missing_graph_is_no_signal_not_an_error():
diff --git a/tests/unit/health/test_perf_crossfn.py b/tests/unit/health/test_perf_crossfn.py
index e31065919..8470431f2 100644
--- a/tests/unit/health/test_perf_crossfn.py
+++ b/tests/unit/health/test_perf_crossfn.py
@@ -14,11 +14,19 @@ Like the other walker tests, tree-sitter grammar availability is best-effort.
from __future__ import annotations
from pathlib import Path
+from types import SimpleNamespace
+
+import networkx as nx
from repowise.core.analysis.health.biomarkers.base import FileContext
from repowise.core.analysis.health.biomarkers.io_in_loop import IoInLoopDetector
from repowise.core.analysis.health.biomarkers.registry import detect_all
-from repowise.core.analysis.health.complexity import PerfHit, walk_file
+from repowise.core.analysis.health.complexity import (
+ FileComplexity,
+ PerfFnFacts,
+ PerfHit,
+ walk_file,
+)
from repowise.core.analysis.health.perf import (
collect_crossfn_io_in_loop,
path_to_sink,
@@ -27,6 +35,11 @@ from repowise.core.analysis.health.perf import (
from repowise.core.analysis.health.scoring import score_file
from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+def _pf(path: str):
+ return SimpleNamespace(file_info=SimpleNamespace(path=path))
+
+
# ---------------------------------------------------------------------------
# reachability — the sink-agnostic primitive
# ---------------------------------------------------------------------------
@@ -183,6 +196,20 @@ def test_crossfn_scheduler_pattern_is_caught(tmp_path):
assert h.path[-1].endswith("::_poll")
+def test_resolver_preserves_every_call_site_on_the_collapsed_edge(tmp_path):
+ source = (
+ "def load(x):\n"
+ " return x\n\n"
+ "def run(x):\n"
+ " load(x)\n"
+ " return load(x)\n"
+ )
+ _walked, graph = _build(tmp_path, {"calls.py": source})
+
+ edge = graph["calls.py::run"]["calls.py::load"]
+ assert edge["call_lines"] == [5, 6]
+
+
def test_crossfn_path_renders_in_the_biomarker(tmp_path):
walked, graph = _build(tmp_path, {"scheduler.py": _SCHEDULER})
res = collect_crossfn_io_in_loop(walked, graph)
@@ -251,9 +278,7 @@ def test_crossfn_through_star_import_barrel(tmp_path):
# a same-named method elsewhere defeats the Tier-3 global-unique match,
# so only the followed barrel edge can resolve the call.
"stores.py": (
- "class Store:\n"
- " def upsert_one(self, session, rid):\n"
- " return None\n"
+ "class Store:\n def upsert_one(self, session, rid):\n return None\n"
),
"service.py": (
"def persist_all(session, ids):\n"
@@ -300,6 +325,123 @@ def test_crossfn_no_graph_is_noop():
assert collect_crossfn_io_in_loop([], None) == {}
+def test_unreliable_call_cannot_create_a_cross_function_finding():
+ graph = nx.DiGraph()
+ graph.add_node(
+ "a.py::owner", node_type="symbol", name="owner", file_path="a.py", start_line=1, end_line=5
+ )
+ graph.add_node(
+ "b.py::load", node_type="symbol", name="load", file_path="b.py", start_line=1, end_line=5
+ )
+ graph.add_edge(
+ "a.py::owner",
+ "b.py::load",
+ edge_type="calls",
+ resolution_origin="global_unique",
+ call_lines=[3],
+ )
+ owner = FileComplexity(
+ functions=[],
+ classes=[],
+ perf_fn_facts=[
+ PerfFnFacts("owner", 1, (("load", 3),), None),
+ ],
+ )
+ sink = FileComplexity(
+ functions=[],
+ classes=[],
+ perf_fn_facts=[
+ PerfFnFacts("load", 1, (), "db"),
+ ],
+ )
+ assert collect_crossfn_io_in_loop([(_pf("a.py"), owner), (_pf("b.py"), sink)], graph) == {}
+
+
+def test_call_site_identity_prevents_same_name_first_hop_collision():
+ graph = nx.DiGraph()
+ for node_id, path, name in (
+ ("owner.py::run", "owner.py", "run"),
+ ("db.py::load", "db.py", "load"),
+ ("pure.py::load", "pure.py", "load"),
+ ):
+ graph.add_node(
+ node_id, node_type="symbol", name=name, file_path=path, start_line=1, end_line=8
+ )
+ # The DB call is outside the loop. The same-named pure call is inside it.
+ graph.add_edge("owner.py::run", "db.py::load", edge_type="calls", call_lines=[3])
+ graph.add_edge("owner.py::run", "pure.py::load", edge_type="calls", call_lines=[6])
+ owner = FileComplexity(
+ functions=[], classes=[], perf_fn_facts=[PerfFnFacts("run", 1, (("load", 6),), None)]
+ )
+ db_sink = FileComplexity(
+ functions=[], classes=[], perf_fn_facts=[PerfFnFacts("load", 1, (), "db")]
+ )
+ pure = FileComplexity(
+ functions=[], classes=[], perf_fn_facts=[PerfFnFacts("load", 1, (), None)]
+ )
+
+ assert (
+ collect_crossfn_io_in_loop(
+ [(_pf("owner.py"), owner), (_pf("db.py"), db_sink), (_pf("pure.py"), pure)],
+ graph,
+ )
+ == {}
+ )
+
+
+def test_unresolved_loop_call_does_not_reuse_same_name_outside_loop():
+ graph = nx.DiGraph()
+ for node_id, path, name in (
+ ("owner.py::run", "owner.py", "run"),
+ ("db.py::load", "db.py", "load"),
+ ):
+ graph.add_node(
+ node_id, node_type="symbol", name=name, file_path=path, start_line=1, end_line=8
+ )
+ # db.load() resolved outside the loop; obj.load() at line 6 did not resolve.
+ graph.add_edge("owner.py::run", "db.py::load", edge_type="calls", call_lines=[3])
+ owner = FileComplexity(
+ functions=[], classes=[], perf_fn_facts=[PerfFnFacts("run", 1, (("load", 6),), None)]
+ )
+ db_sink = FileComplexity(
+ functions=[], classes=[], perf_fn_facts=[PerfFnFacts("load", 1, (), "db")]
+ )
+
+ assert collect_crossfn_io_in_loop(
+ [(_pf("owner.py"), owner), (_pf("db.py"), db_sink)], graph
+ ) == {}
+
+
+def test_dispatch_edge_connects_a_resolved_call_to_its_sink():
+ graph = nx.DiGraph()
+ for node_id, path, name in (
+ ("owner.py::run", "owner.py", "run"),
+ ("api.py::load", "api.py", "load"),
+ ("impl.py::load", "impl.py", "load"),
+ ):
+ graph.add_node(
+ node_id, node_type="symbol", name=name, file_path=path, start_line=1, end_line=8
+ )
+ graph.add_edge("owner.py::run", "api.py::load", edge_type="calls", call_lines=[4])
+ graph.add_edge("api.py::load", "impl.py::load", edge_type="dispatches_to")
+ owner = FileComplexity(
+ functions=[], classes=[], perf_fn_facts=[PerfFnFacts("run", 1, (("load", 4),), None)]
+ )
+ interface = FileComplexity(
+ functions=[], classes=[], perf_fn_facts=[PerfFnFacts("load", 1, (), None)]
+ )
+ sink = FileComplexity(
+ functions=[], classes=[], perf_fn_facts=[PerfFnFacts("load", 1, (), "db")]
+ )
+
+ result = collect_crossfn_io_in_loop(
+ [(_pf("owner.py"), owner), (_pf("api.py"), interface), (_pf("impl.py"), sink)],
+ graph,
+ )
+ hit = next(hit for hits in result.values() for hit in hits)
+ assert hit.path == ("owner.py::run", "api.py::load", "impl.py::load")
+
+
# ---------------------------------------------------------------------------
# guardrail: cross-fn findings score performance only, never defect
# ---------------------------------------------------------------------------
diff --git a/tests/unit/health/test_reachability_wiring.py b/tests/unit/health/test_reachability_wiring.py
index 8cbe36941..7552902df 100644
--- a/tests/unit/health/test_reachability_wiring.py
+++ b/tests/unit/health/test_reachability_wiring.py
@@ -125,3 +125,14 @@ def test_the_stored_metric_agrees_with_the_biomarker(tmp_path):
).analyze()
metric = next(m for m in report.metrics if m.file_path == "src/parser.py")
assert metric.has_test_file is True
+
+
+def test_test_and_performance_passes_share_one_execution_index(tmp_path):
+ analyzer = HealthAnalyzer(_graph(calls=True), parsed_files=_tree(tmp_path))
+
+ first = analyzer._execution_graph()
+ analyzer._files_reached_by_tests()
+ analyzer._apply_crossfn_perf([])
+
+ assert first is not None
+ assert analyzer._execution_graph() is first
diff --git a/tests/unit/ingestion/test_graph_rehydrate.py b/tests/unit/ingestion/test_graph_rehydrate.py
index bfd85707e..be27fe49b 100644
--- a/tests/unit/ingestion/test_graph_rehydrate.py
+++ b/tests/unit/ingestion/test_graph_rehydrate.py
@@ -88,6 +88,9 @@ def _serialize(builder: GraphBuilder) -> tuple[list[dict], list[dict]]:
"edge_type": data.get("edge_type", "imports"),
"confidence": data.get("confidence", 1.0),
"imported_names": data.get("imported_names", []),
+ "hint_source": data.get("hint_source"),
+ "resolution_origin": data.get("resolution_origin"),
+ "call_lines": data.get("call_lines", []),
}
)
return nodes, edges
@@ -150,6 +153,17 @@ def test_resolution_origin_survives_rehydration():
assert "resolution_origin" not in graph[e["source_node_id"]][e["target_node_id"]]
+def test_call_lines_survive_rehydration():
+ original = _build_sample()
+ nodes, edges = _serialize(original)
+ edges[0] = {**edges[0], "edge_type": "calls", "call_lines": [7, 11]}
+
+ hydrated = GraphBuilder.from_persisted(nodes, edges, original.file_metrics_snapshot())
+ stamped = hydrated.graph()[edges[0]["source_node_id"]][edges[0]["target_node_id"]]
+
+ assert stamped["call_lines"] == [7, 11]
+
+
def test_rehydrate_without_metrics_falls_back_to_recompute():
"""No snapshot supplied → caches stay empty and metrics recompute on read."""
original = _build_sample()
diff --git a/tests/unit/persistence/test_incremental_edge_persist.py b/tests/unit/persistence/test_incremental_edge_persist.py
index 0a2bf5fcc..9f44f310e 100644
--- a/tests/unit/persistence/test_incremental_edge_persist.py
+++ b/tests/unit/persistence/test_incremental_edge_persist.py
@@ -145,6 +145,53 @@ async def test_incremental_edge_persist_leaves_unchanged_files_untouched(async_s
assert ("c.py", "a.py", "imports") in after
+async def test_full_and_incremental_persist_retain_call_site_lines(async_session, tmp_path):
+ """Both graph write paths preserve the exact sites behind a collapsed call edge."""
+ repo = await insert_repo(async_session)
+ source = "def load():\n pass\n\ndef run():\n load()\n"
+ (tmp_path / "calls.py").write_text(source)
+ gb1, parsed1 = _build_graph(tmp_path)
+
+ await persist_ingestion(
+ SimpleNamespace(
+ parsed_files=parsed1,
+ graph_builder=gb1,
+ external_systems=[],
+ execution_flow_report=None,
+ source_map={},
+ ),
+ async_session,
+ repo.id,
+ )
+ await async_session.commit()
+
+ call_edge = (
+ await async_session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo.id,
+ GraphEdge.edge_type == "calls",
+ )
+ )
+ ).scalar_one()
+ assert json.loads(call_edge.call_lines_json) == [5]
+
+ (tmp_path / "calls.py").write_text(source + " load()\n")
+ gb2, parsed2 = _build_graph(tmp_path)
+ await persist_graph_nodes(async_session, repo.id, gb2)
+ await persist_incremental_edges(async_session, repo.id, gb2, parsed2, ["calls.py"])
+ await async_session.commit()
+
+ call_edge = (
+ await async_session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo.id,
+ GraphEdge.edge_type == "calls",
+ )
+ )
+ ).scalar_one()
+ assert json.loads(call_edge.call_lines_json) == [5, 6]
+
+
async def _stored_fingerprint(session, repo_id: str) -> str | None:
return (
await session.execute(
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index 979b37291..0ea407b52 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -221,6 +221,7 @@ def test_graph_edge_has_expected_tablename():
def test_graph_edge_defaults():
col_defaults = {c.name: c.default for c in GraphEdge.__table__.columns if c.default is not None}
assert col_defaults["imported_names_json"].arg == "[]"
+ assert col_defaults["call_lines_json"].arg == "[]"
# ---------------------------------------------------------------------------
diff --git a/tests/unit/persistence/test_test_reachability_walk.py b/tests/unit/persistence/test_test_reachability_walk.py
index 990ba4c59..c28dc4ff7 100644
--- a/tests/unit/persistence/test_test_reachability_walk.py
+++ b/tests/unit/persistence/test_test_reachability_walk.py
@@ -13,8 +13,15 @@ and error on its missing arguments.
from __future__ import annotations
+import networkx as nx
+
+from repowise.core.analysis.test_reachability import call_graph_from_db, call_graph_from_graph
from repowise.core.analysis.test_reachability import tests_reaching as reaching
from repowise.core.analysis.test_reachability import tests_reaching_by_tier as by_tier
+from repowise.core.persistence.crud.graph import (
+ batch_upsert_graph_edges,
+ get_all_graph_edges,
+)
from repowise.core.persistence.models import GraphEdge, GraphNode
from tests.unit.persistence.helpers import insert_repo
@@ -23,9 +30,7 @@ async def _seed(session, repo_id, *, nodes, edges):
"""Seed file nodes and edges. An edge is ``(src, dst, type[, origin])``."""
for path, is_test in nodes.items():
session.add(
- GraphNode(
- repository_id=repo_id, node_id=path, node_type="file", is_test=is_test
- )
+ GraphNode(repository_id=repo_id, node_id=path, node_type="file", is_test=is_test)
)
# Deduped: two ``_calls`` into the same source file both declare its
# symbol, and graph_edges is unique on (repo, src, dst, type).
@@ -66,9 +71,7 @@ async def test_names_the_tests_that_call_a_changed_file(async_session):
nodes={"tests/test_a.py": True, "tests/test_z.py": True, "src/a.py": False},
edges=[*_calls("tests/test_a.py", "src/a.py")],
)
- assert await reaching(async_session, repo.id, ["src/a.py"]) == {
- "src/a.py": ["tests/test_a.py"]
- }
+ assert await reaching(async_session, repo.id, ["src/a.py"]) == {"src/a.py": ["tests/test_a.py"]}
async def test_transitive_execution_is_found(async_session):
@@ -132,9 +135,7 @@ async def test_the_import_tier_answers_only_where_calls_are_silent(async_session
("tests/test_imports_only.py", "src/imported.py", "imports"),
],
)
- result = await by_tier(
- async_session, repo.id, ["src/called.py", "src/imported.py"]
- )
+ result = await by_tier(async_session, repo.id, ["src/called.py", "src/imported.py"])
assert result["src/called.py"].tests == ["tests/test_called.py"]
assert result["src/called.py"].via == "call-graph"
assert result["src/imported.py"].tests == ["tests/test_imports_only.py"]
@@ -229,3 +230,48 @@ async def test_repo_with_no_test_nodes_returns_empty(async_session):
edges=[*_calls("src/b.py", "src/a.py")],
)
assert await reaching(async_session, repo.id, ["src/a.py"]) == {}
+
+
+async def test_database_and_memory_builders_apply_the_same_execution_policy(async_session):
+ repo = await insert_repo(async_session)
+ edges = [
+ ("tests/t.py", "tests/t.py::test", "defines"),
+ ("tests/t.py::test", "src/a.py::run", "calls", "same_file"),
+ ("src/a.py::run", "src/b.py::impl", "dispatches_to"),
+ ("tests/t.py::test", "src/guess.py::run", "calls", "global_unique"),
+ ("tests/t.py::test", "src/named.py::handler", "references"),
+ ]
+ await _seed(
+ async_session,
+ repo.id,
+ nodes={"tests/t.py": True, "src/a.py": False, "src/b.py": False},
+ edges=edges,
+ )
+ graph = nx.DiGraph()
+ for source, target, edge_type, *origin in edges:
+ attrs = {"edge_type": edge_type}
+ if origin and origin[0] is not None:
+ attrs["resolution_origin"] = origin[0]
+ graph.add_edge(source, target, **attrs)
+
+ memory = call_graph_from_graph(graph)
+ database = await call_graph_from_db(async_session, repo.id)
+
+ assert database.declares == memory.declares
+ assert database.forward == memory.forward
+ assert database.reverse == memory.reverse
+
+
+async def test_call_site_lines_round_trip_through_edge_persistence(async_session):
+ repo = await insert_repo(async_session)
+ edge = {
+ "source_node_id": "a.py::run",
+ "target_node_id": "b.py::load",
+ "edge_type": "calls",
+ "call_lines_json": "[4, 9]",
+ }
+
+ await batch_upsert_graph_edges(async_session, repo.id, [edge])
+ rows = await get_all_graph_edges(async_session, repo.id)
+
+ assert rows[0]["call_lines"] == [4, 9]