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(health): centrality-gated performance markers + reusable severity ranker (#539)

Raghav Chamadiyaa441d53626d9
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 84f504074..f15c10df3 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -156,6 +156,32 @@ category cap of 1.0, so the pillar stays advisory) are:
- **`membership_test_against_list_in_loop`**: `x in big_list` (or
`big_list.includes(x)`) inside a loop is O(n·m); a set makes each lookup O(1).
Fires only when the right operand is *provably* a list, never a set or dict.
+- **`nested_loop_with_io`**: an I/O sink in the inner body of a **nested** loop:
+ O(n·m) round-trips, the quadratic cousin of `io_in_loop`. The nesting itself
+ raises confidence the finding is real, so it surfaces alongside `io_in_loop`.
+- **`blocking_io_under_lock`**: an I/O round-trip reached while a block-scoped
+ lock is held (a C# `lock(){}` / Java `synchronized(){}` block, directly or
+ through a call). Every other thread blocks for the full I/O wait — a throughput
+ killer. The cross-function case reuses the same bounded-reachability engine as
+ the N+1 moat, with a `lock → io` entry set.
+
+Two markers use **centrality as a precision gate**, not just a sort key — a
+shape that is noisy when flagged everywhere only fires in a *hot* function (one
+with top-quintile call-graph in-degree, or in a churny/hotspot file), computed by
+a reusable severity ranker over the same call graph the N+1 pass uses:
+
+- **`hot_path_sync_io`**: a blocking **subprocess / filesystem** call in a hot,
+ request-reachable function — **even outside a loop**. Generalizes the pillar
+ beyond loops: its latency is paid on every call through the function. (DB and
+ network are excluded — both are awaited in async code, and the un-awaited calls
+ a static pass sees are result *materializers* or chained awaits, not blocking
+ round-trips; subprocess/filesystem are synchronous by construction.) Advisory —
+ a latency signal ranked by centrality, not a defect.
+- **`nested_loop_quadratic`**: a data-dependent loop nested inside another
+ (O(n²)) in a hot function. The centrality gate makes the list short and
+ reviewable (it cut a 13× volume of raw nested loops), but centrality answers
+ "is this function important", not "is n large" — so it ships **advisory /
+ informational** only, never at a weight that moves the score.
A few markers are language-specific, contributed by that language's dialect (see
below) rather than the shared core:
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
new file mode 100644
index 000000000..029fcc5ca
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/blocking_io_under_lock.py
@@ -0,0 +1,91 @@
+"""Blocking I/O under a lock — an I/O round-trip reached while a lock is held.
+
+Holding a lock across a database / network / filesystem / subprocess call is a
+classic throughput killer: every other thread that needs the lock blocks for the
+full duration of the I/O wait, so the critical section's latency becomes the
+whole system's serialization point. The fix is almost always to do the I/O
+outside the lock and only take the lock to mutate shared state.
+
+Two cases share this detector and the same ``performance`` budget:
+
+ * **same-function** — the sink is lexically inside a block-scoped lock
+ (C# ``lock (x) {}`` / Java ``synchronized (x) {}``); ``PerfHit.path`` empty.
+ * **cross-function** — the lock-holding function calls a helper that, within a
+ few hops, executes the sink; ``PerfHit.path`` carries the resolved
+ ``A -> ... -> sink`` chain (``perf.gated.collect_blocking_io_under_lock``,
+ reusing the sink-agnostic reachability engine with a lock→I/O entry set).
+
+A ``performance`` dimension signal. This detector lifts the pre-collected hits
+into findings — unsupported languages and parse failures yield nothing.
+"""
+
+from __future__ import annotations
+
+from ..complexity import PerfHit
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_KIND = "blocking_io_under_lock"
+
+_BOUNDARY_PHRASING: dict[str, str] = {
+ "db": "a database call",
+ "network": "a network call",
+ "filesystem": "a filesystem call",
+ "subprocess": "a subprocess spawn",
+ "lock": "a lock acquisition",
+}
+
+
+class BlockingIoUnderLockDetector:
+ name = _KIND
+ category = "performance"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for hit in ctx.perf_hits:
+ if hit.kind != _KIND:
+ continue
+ phrasing = _BOUNDARY_PHRASING.get(hit.detail, "an I/O call")
+ if hit.path:
+ out.append(self._cross_function(hit, phrasing))
+ else:
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.MEDIUM,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={"boundary_kind": hit.detail, "cross_function": False},
+ reason=(
+ f"{phrasing} runs while a lock is held; move the I/O "
+ "outside the critical section to avoid serializing "
+ "every thread on the round-trip"
+ ),
+ )
+ )
+ return out
+
+ @staticmethod
+ def _cross_function(hit: PerfHit, phrasing: str) -> BiomarkerResult:
+ names = [seg.rsplit("::", 1)[-1] for seg in hit.path]
+ chain = " -> ".join(names)
+ return BiomarkerResult(
+ biomarker_type=_KIND,
+ severity=Severity.MEDIUM,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={
+ "boundary_kind": hit.detail,
+ "cross_function": True,
+ "path": list(hit.path),
+ },
+ reason=(
+ f"{phrasing} is reached while a lock is held, through "
+ f"{chain}; move the I/O outside the critical section"
+ ),
+ )
+
+
+BIOMARKER = BlockingIoUnderLockDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/hot_path_sync_io.py b/packages/core/src/repowise/core/analysis/health/biomarkers/hot_path_sync_io.py
new file mode 100644
index 000000000..fbc64a24a
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/hot_path_sync_io.py
@@ -0,0 +1,59 @@
+"""Hot-path sync I/O — a blocking I/O call in a hot, request-reachable function.
+
+A synchronous (non-awaited) database / network / filesystem / subprocess
+round-trip blocks its thread for the duration of the call. Outside a loop that is
+usually fine — but in a *hot, central* function (one on many request paths) the
+blocking wait is paid on every request, a latency risk a loop-only detector never
+sees. This generalizes the performance pillar beyond loops using the centrality
+the engine already computes.
+
+The walker emits every loop-depth-0 blocking sink as a candidate; the centrality
+gate (``perf.gated.apply_centrality_gate``) keeps only those in a top-quintile-
+central or churny function. A ``performance`` dimension signal — this detector
+lifts the (already-gated) hits into findings.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_KIND = "hot_path_sync_io"
+
+_BOUNDARY_PHRASING: dict[str, str] = {
+ "db": "a blocking database call",
+ "network": "a blocking network call",
+ "filesystem": "a blocking filesystem call",
+ "subprocess": "a blocking subprocess spawn",
+ "lock": "a blocking lock acquisition",
+}
+
+
+class HotPathSyncIoDetector:
+ name = _KIND
+ category = "performance"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for hit in ctx.perf_hits:
+ if hit.kind != _KIND:
+ continue
+ phrasing = _BOUNDARY_PHRASING.get(hit.detail, "a blocking I/O call")
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.LOW,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={"boundary_kind": hit.detail},
+ reason=(
+ f"{phrasing} runs on a hot, request-reachable path; "
+ "its latency is paid on every call through this function"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = HotPathSyncIoDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_quadratic.py b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_quadratic.py
new file mode 100644
index 000000000..6cd7360c0
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_quadratic.py
@@ -0,0 +1,52 @@
+"""Nested-loop quadratic — an O(n^2) loop shape in a hot, central function.
+
+A data-dependent loop nested inside another is an O(n^2) algorithmic shape. On
+its own that is a LOW-precision signal: triangular bounds, tiny-n loops, and
+two-pass algorithms over small collections are all fine. The backlog deferred
+the bare version for exactly that reason. The unlock is the **centrality gate**:
+the walker emits this as a candidate, and ``perf.gated.apply_centrality_gate``
+drops every hit whose enclosing function is not hot (top-quintile call-graph
+centrality or a churny/hotspot file). What reaches this detector is already
+gated, so a surviving hit is a quadratic shape sitting on a frequently-exercised
+path — worth a look.
+
+A ``performance`` dimension signal. This detector only lifts the (already
+centrality-gated) hits into findings.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_KIND = "nested_loop_quadratic"
+
+
+class NestedLoopQuadraticDetector:
+ name = _KIND
+ category = "performance"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for hit in ctx.perf_hits:
+ if hit.kind != _KIND:
+ continue
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.LOW,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={},
+ reason=(
+ "a loop nested inside another loop (O(n^2)) sits in a "
+ "hot/central function; check the inner bound or use a "
+ "set/map lookup if it is a search"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = NestedLoopQuadraticDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_with_io.py b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_with_io.py
new file mode 100644
index 000000000..1acd875e1
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_with_io.py
@@ -0,0 +1,57 @@
+"""Nested-loop I/O — an execution sink in the inner body of a nested loop.
+
+A database / network / filesystem / subprocess round-trip that runs inside *two*
+levels of data-dependent loop pays O(n·m) round-trips — the quadratic cousin of
+``io_in_loop``. The nesting is the precision lever: a sink two loops deep is
+almost never incidental, so this rides alongside ``io_in_loop`` un-gated (it does
+NOT need the centrality gate the bare O(n^2) marker does).
+
+A ``performance`` dimension signal. This detector lifts the pre-collected,
+loop-depth-scoped hits (``complexity.walker._collect_perf_hits``, emitted only at
+``loop_depth >= 2``) into findings — unsupported languages yield nothing.
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_KIND = "nested_loop_with_io"
+
+_BOUNDARY_PHRASING: dict[str, str] = {
+ "db": "a database call",
+ "network": "a network call",
+ "filesystem": "a filesystem call",
+ "subprocess": "a subprocess spawn",
+ "lock": "a lock acquisition",
+}
+
+
+class NestedLoopWithIoDetector:
+ name = _KIND
+ category = "performance"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for hit in ctx.perf_hits:
+ if hit.kind != _KIND:
+ continue
+ phrasing = _BOUNDARY_PHRASING.get(hit.detail, "an I/O call")
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.MEDIUM,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={"boundary_kind": hit.detail},
+ reason=(
+ f"{phrasing} runs inside a nested loop (O(n·m) round-trips); "
+ "batch the inner query or restructure the loops"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = NestedLoopWithIoDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index b281d52ee..2e209b33a 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -12,6 +12,7 @@ from __future__ import annotations
from collections.abc import Sequence
from .base import Biomarker, BiomarkerResult, FileContext
+from .blocking_io_under_lock import BlockingIoUnderLockDetector
from .blocking_sync_in_async import BlockingSyncInAsyncDetector
from .brain_method import BrainMethodDetector
from .bumpy_road import BumpyRoadDetector
@@ -30,6 +31,7 @@ from .error_handling import ErrorHandlingDetector
from .function_hotspot import FunctionHotspotDetector
from .god_class import GodClassDetector
from .hidden_coupling import HiddenCouplingDetector
+from .hot_path_sync_io import HotPathSyncIoDetector
from .io_in_loop import IoInLoopDetector
from .knowledge_loss import KnowledgeLossDetector
from .large_assertion_block import LargeAssertionBlockDetector
@@ -38,6 +40,8 @@ from .lock_in_loop import LockInLoopDetector
from .low_cohesion import LowCohesionDetector
from .membership_test_against_list_in_loop import MembershipTestAgainstListInLoopDetector
from .nested_complexity import NestedComplexityDetector
+from .nested_loop_quadratic import NestedLoopQuadraticDetector
+from .nested_loop_with_io import NestedLoopWithIoDetector
from .ownership_risk import OwnershipRiskDetector
from .primitive_obsession import PrimitiveObsessionDetector
from .prior_defect import PriorDefectDetector
@@ -82,6 +86,11 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
LockInLoopDetector, # type: ignore[list-item]
SerialAwaitInLoopDetector, # type: ignore[list-item]
MembershipTestAgainstListInLoopDetector, # type: ignore[list-item]
+ # Phase 7b — centrality-gated moat markers.
+ NestedLoopWithIoDetector, # type: ignore[list-item]
+ NestedLoopQuadraticDetector, # type: ignore[list-item]
+ HotPathSyncIoDetector, # type: ignore[list-item]
+ BlockingIoUnderLockDetector, # type: ignore[list-item]
]
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
index 02e7b962c..0697e0b2a 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py
@@ -166,6 +166,22 @@ class PerfHit:
``big_list.includes(x)``) inside a loop where the right operand is a known
list -> O(n·m); a set would make each probe O(1).
+ Phase-7b markers (``func_start``-carrying so the centrality gate can resolve
+ the enclosing function to a graph symbol node):
+
+ - ``nested_loop_with_io`` — an I/O sink in the inner body of a nested loop
+ (``loop_depth >= 2``) -> O(n·m) round-trips. Rides alongside ``io_in_loop``;
+ the nesting itself raises confidence, so it is NOT centrality-gated.
+ - ``nested_loop_quadratic`` — a data-dependent loop nested inside another
+ (O(n^2) shape). Emitted as a *candidate*; the centrality gate keeps it
+ ONLY in a hot/central function (the gate is the precision fix).
+ - ``hot_path_sync_io`` — a blocking (non-awaited) I/O sink at ``loop_depth 0``.
+ Emitted as a *candidate*; survives only in a top-centrality function.
+ - ``blocking_io_under_lock`` — an I/O sink reached while a block-scoped lock
+ (C# ``lock``/Java ``synchronized``) is held. Same-function (sink lexically
+ under the lock) is emitted here; the cross-function case is added by
+ ``perf.gated.collect_blocking_io_under_lock``.
+
The Phase-7a markers above are emitted via the dialect ``loop_call_marker`` /
``loop_stmt_marker`` hooks (and the inline awaited-sink path for
``serial_await_in_loop``), so each is per-language opt-in.
@@ -175,6 +191,10 @@ class PerfHit:
line: int # 1-indexed
function: str | None = None
detail: str = ""
+ # 1-indexed ``def`` line of the enclosing function (0 = module scope). Lets
+ # the centrality gate (Phase 7b) resolve a candidate hit to its graph symbol
+ # node without a separate lookup. 0 for hits where it is irrelevant.
+ func_start: int = 0
# Reachability path for a cross-function hit: the resolved symbol-node
# chain ``A -> B -> ... -> sink`` (PR4). Empty for same-function hits —
# its emptiness is what distinguishes the two cases downstream.
@@ -202,6 +222,11 @@ class PerfFnFacts:
``func_start`` is the 1-indexed line of the enclosing function's ``def``
(0 for module scope, which maps to the synthetic ``::__module__`` node);
the bridge resolves it to a graph symbol node by line containment.
+
+ ``lock_call_targets`` is the Phase-7b analogue of ``loop_call_targets``: the
+ rightmost names of non-sink calls made while a block-scoped lock is held.
+ Each is a candidate helper whose body might reach a sink transitively —
+ the cross-function ``blocking_io_under_lock`` entry points.
"""
function: str | None
@@ -209,6 +234,16 @@ class PerfFnFacts:
# ``(callee_name, call_line)`` pairs for the loop-nested non-sink calls.
loop_call_targets: tuple[tuple[str, int], ...]
bare_sink_kind: str | None
+ # ``(callee_name, call_line)`` pairs for non-sink calls under a held lock.
+ lock_call_targets: tuple[tuple[str, int], ...] = ()
+ # Phase-7b centrality-gated facts the engine turns into hits only for a hot
+ # function. ``nested_loop_line`` is a representative data-dependent
+ # nested-loop site (0 = none -> ``nested_loop_quadratic``);
+ # ``blocking_sink_{kind,line}`` is the first non-awaited loop_depth-0 I/O
+ # sink (None/0 = none -> ``hot_path_sync_io``).
+ nested_loop_line: int = 0
+ blocking_sink_kind: str | None = None
+ blocking_sink_line: int = 0
@dataclass
@@ -986,6 +1021,29 @@ _LOOP_STMT_MARKER_KINDS = frozenset(
}
)
+# Boundary kinds that are *unambiguously blocking* when called synchronously, so
+# a loop_depth-0 occurrence in a hot function is a ``hot_path_sync_io`` candidate.
+# Limited to ``subprocess`` + ``filesystem`` on purpose:
+# * ``db`` — in an async codebase DB access is awaited (non-blocking), and the
+# un-awaited DB calls a static pass sees are almost all result *materializers*
+# (``result.scalars().all()`` / ``.scalar_one()``) on an already-awaited
+# result, not a round-trip (a probe-confirmed FP generator).
+# * ``network`` — async HTTP is awaited too; the walker's ``awaited`` test only
+# inspects the immediate parent, so a wrapped/chained await
+# (``(await client.GetAsync(u)).X``) can read as non-awaited and FP. Every
+# hot-path TP on the OSS corpus was subprocess/fs (0 network), so excluding
+# it costs no measured precision and removes that FP class. (A wrapper-aware
+# ``awaited`` test could re-admit sync ``requests`` — tracked as a follow-up.)
+# subprocess (``subprocess.run`` / ``os.system``) and filesystem (bare ``open``)
+# are synchronous by construction, with no await semantics to misread.
+_HOT_PATH_SINK_KINDS = frozenset({"subprocess", "filesystem"})
+
+# Block node kinds that form the *body* of a lock construct (C# ``lock (x) {…}``
+# / Java ``synchronized (x) {…}``). Only the body runs with the lock held, so
+# ``lock_depth`` is raised for the body child only — a sink in the lock-object
+# expression (``synchronized(repo.find(id)){…}``) runs BEFORE the lock is taken.
+_LOCK_BODY_KINDS = frozenset({"block", "statement_block", "compound_statement"})
+
def _perf_func_name(node: Node) -> str | None:
nm = node.child_by_field_name("name")
@@ -1000,9 +1058,10 @@ def _collect_perf_hits(
"""Whole-tree perf pass → ``(hits, io_boundary_names, fn_facts)``.
Iterative DFS carrying ``(node, loop_depth, in_async, func_name,
- func_start)`` — the proven Phase-0 shape, extended with the enclosing
- function's start line so per-function facts can be keyed to a graph symbol
- node. Loop-body scoping and constant-loop skipping are applied so only
+ func_start, lock_depth)`` — the proven Phase-0 shape, extended with the
+ enclosing function's start line (so per-function facts key to a graph symbol
+ node) and a block-scoped ``lock_depth`` (so an I/O sink under a held lock is
+ flagged). Loop-body scoping and constant-loop skipping are applied so only
genuinely per-iteration calls are flagged. Returns nothing for languages
that opt out of the perf pass (empty ``call_kinds``).
@@ -1023,6 +1082,11 @@ def _collect_perf_hits(
do_loop_call_marker = bool(markers & _LOOP_CALL_MARKER_KINDS)
do_loop_stmt_marker = bool(markers & _LOOP_STMT_MARKER_KINDS)
do_serial_await = "serial_await_in_loop" in markers
+ # Phase 7b markers.
+ do_nested_io = "nested_loop_with_io" in markers
+ do_nested_quadratic = "nested_loop_quadratic" in markers
+ do_hot_path = "hot_path_sync_io" in markers
+ do_lock_io = "blocking_io_under_lock" in markers
# ``list_names`` is the precision gate for the membership marker; compute it
# once per file only when this dialect can emit that marker, then thread it
# to the loop-marker hooks (which ignore it for every other marker).
@@ -1038,20 +1102,32 @@ def _collect_perf_hits(
hits: list[PerfHit] = []
# Per-enclosing-function accumulators keyed by the function's start line
- # (0 = module scope). ``(name, loop_targets{name->min line}, [bare_sink])``.
- fn_acc: dict[int, tuple[str | None, dict[str, int], list[str | None]]] = {}
-
- def _acc(func_start: int, func_name: str | None) -> tuple[dict[str, int], list[str | None]]:
+ # (0 = module scope): ``(name, loop_targets{name->line}, lock_targets{...},
+ # [bare_sink], misc)``. loop/lock targets feed the cross-function
+ # reachability passes; the bare-sink slot makes the function a reachability
+ # target. ``misc`` carries the Phase-7b *centrality-gated* facts the engine
+ # turns into hits only for hot functions (kept out of ``hits`` so the raw
+ # walker output stays the same high-precision same-function set):
+ # misc[0] = nested_loop_line (a data-dependent loop nested in another)
+ # misc[1] = blocking_sink_kind (first non-awaited loop_depth-0 sink kind)
+ # misc[2] = blocking_sink_line
+ fn_acc: dict[
+ int, tuple[str | None, dict[str, int], dict[str, int], list[str | None], list]
+ ] = {}
+
+ def _acc(
+ func_start: int, func_name: str | None
+ ) -> tuple[dict[str, int], dict[str, int], list[str | None], list]:
entry = fn_acc.get(func_start)
if entry is None:
- entry = (func_name, {}, [None])
+ entry = (func_name, {}, {}, [None], [0, None, 0])
fn_acc[func_start] = entry
- return entry[1], entry[2]
+ return entry[1], entry[2], entry[3], entry[4]
- # (node, loop_depth, in_async, func_name, func_start)
- stack: list[tuple[Node, int, bool, str | None, int]] = [(root, 0, False, None, 0)]
+ # (node, loop_depth, in_async, func_name, func_start, lock_depth)
+ stack: list[tuple[Node, int, bool, str | None, int, int]] = [(root, 0, False, None, 0, 0)]
while stack:
- node, loop_depth, in_async, func_name, func_start = stack.pop()
+ node, loop_depth, in_async, func_name, func_start, lock_depth = stack.pop()
t = node.type
is_loop = t in loop_kinds
@@ -1067,6 +1143,15 @@ def _collect_perf_hits(
next_func = _perf_func_name(node) or func_name
next_start = node.start_point[0] + 1
+ # A data-dependent loop nested inside another (``loop_depth`` only counts
+ # non-constant loops) is an O(n^2) shape. Record the site as a fact; the
+ # engine emits ``nested_loop_quadratic`` only when the function is hot
+ # (centrality gate), so the noisy-everywhere shape never ships ungated.
+ if is_loop and loop_depth >= 1 and do_nested_quadratic:
+ misc = _acc(next_start, next_func)[3]
+ if misc[0] == 0:
+ misc[0] = node.start_point[0] + 1
+
if t in call_kinds:
method = dialect.callee_method_name(node) or ""
root_name = dialect.callee_root_name(node) or ""
@@ -1081,24 +1166,67 @@ def _collect_perf_hits(
io_names=io_names,
has_db_import=has_db_import,
)
- if loop_depth >= 1:
- if kind is not None:
- hits.append(PerfHit("io_in_loop", line, next_func, kind))
+ if kind is not None:
+ if loop_depth >= 1:
+ hits.append(PerfHit("io_in_loop", line, next_func, kind, func_start=next_start))
if do_serial_await and awaited:
# An *awaited* sink in a loop body is additionally a
# missed-concurrency candidate (a serial round-trip that
# a ``gather`` / ``Promise.all`` could fan out). Advisory
# co-signal alongside ``io_in_loop``; ``detail`` carries
# the boundary kind for the finding.
- hits.append(PerfHit("serial_await_in_loop", line, next_func, kind))
+ hits.append(
+ PerfHit(
+ "serial_await_in_loop", line, next_func, kind, func_start=next_start
+ )
+ )
+ if do_nested_io and loop_depth >= 2:
+ # A sink in the inner body of a NESTED loop -> O(n·m)
+ # round-trips. Nesting raises confidence, so it ships
+ # un-gated alongside ``io_in_loop``.
+ hits.append(
+ PerfHit(
+ "nested_loop_with_io", line, next_func, kind, func_start=next_start
+ )
+ )
else:
+ # A sink at loop_depth 0 makes this function a reachability
+ # target: a loop elsewhere calling into it runs the sink N
+ # times (cross-function N+1).
+ _lt, _kt, sink_slot, misc = _acc(next_start, next_func)
+ if sink_slot[0] is None:
+ sink_slot[0] = kind
+ if (
+ do_hot_path
+ and not awaited
+ and misc[1] is None
+ and kind in _HOT_PATH_SINK_KINDS
+ ):
+ # An inherently-blocking (non-awaited subprocess / fs /
+ # sync-network) sink outside any loop. Noisy everywhere,
+ # so record it as a fact; the engine emits
+ # ``hot_path_sync_io`` only for a hot, request-reachable
+ # function (centrality gate). ``db`` is excluded — see
+ # ``_HOT_PATH_SINK_KINDS``.
+ misc[1] = kind
+ misc[2] = line
+ if do_lock_io and lock_depth >= 1:
+ # A sink reached while a block-scoped lock is held: the
+ # round-trip runs under the lock, serializing every thread.
+ hits.append(
+ PerfHit(
+ "blocking_io_under_lock", line, next_func, kind, func_start=next_start
+ )
+ )
+ else:
+ if loop_depth >= 1:
marker = (
dialect.loop_call_marker(root_name, method, node, list_names)
if do_loop_call_marker
else None
)
if marker is not None:
- hits.append(PerfHit(marker, line, next_func, ""))
+ hits.append(PerfHit(marker, line, next_func, "", func_start=next_start))
elif method:
# A loop-nested call to a non-sink helper: a candidate
# entry for cross-function reachability (PR4). Keep the
@@ -1106,33 +1234,63 @@ def _collect_perf_hits(
targets = _acc(next_start, next_func)[0]
if method not in targets:
targets[method] = line
- elif kind is not None:
- # A sink at loop_depth 0 makes this function a reachability
- # target: a loop elsewhere calling into it runs the sink N times.
- sink_slot = _acc(next_start, next_func)[1]
- if sink_slot[0] is None:
- sink_slot[0] = kind
+ if do_lock_io and lock_depth >= 1 and method:
+ # A non-sink call under a held lock: a candidate entry for the
+ # cross-function ``blocking_io_under_lock`` reachability pass.
+ lock_targets = _acc(next_start, next_func)[1]
+ if method not in lock_targets:
+ lock_targets[method] = line
if do_blocking and in_async and not awaited:
api = dialect.blocking_sync_api(root_name, method)
if api is not None:
- hits.append(PerfHit("blocking_sync_in_async", line, next_func, api))
+ hits.append(
+ PerfHit(
+ "blocking_sync_in_async", line, next_func, api, func_start=next_start
+ )
+ )
else:
if do_blocking and in_async:
# A non-call member read that blocks in async (C# ``task.Result``).
mem = dialect.async_blocking_member(node)
if mem is not None:
hits.append(
- PerfHit("blocking_sync_in_async", node.start_point[0] + 1, next_func, mem)
+ PerfHit(
+ "blocking_sync_in_async",
+ node.start_point[0] + 1,
+ next_func,
+ mem,
+ func_start=next_start,
+ )
)
if loop_depth >= 1:
if do_string_concat and dialect.is_string_concat(node):
hits.append(
- PerfHit("string_concat_in_loop", node.start_point[0] + 1, next_func, "")
+ PerfHit(
+ "string_concat_in_loop",
+ node.start_point[0] + 1,
+ next_func,
+ "",
+ func_start=next_start,
+ )
)
elif do_loop_stmt_marker:
sm = dialect.loop_stmt_marker(node, list_names)
if sm is not None:
- hits.append(PerfHit(sm, node.start_point[0] + 1, next_func, ""))
+ hits.append(
+ PerfHit(
+ sm,
+ node.start_point[0] + 1,
+ next_func,
+ "",
+ func_start=next_start,
+ )
+ )
+
+ # A block-scoped lock (``lock``/``synchronized``) opens a held region.
+ # Only its BLOCK body runs with the lock held — a sink in the lock-object
+ # expression (``synchronized(repo.find(id)){…}``) runs before the lock is
+ # taken — so ``lock_depth`` is raised per-child, for the body block only.
+ entering_lock = do_lock_io and dialect.is_lock_scope(node)
if is_loop:
# Only the loop BODY runs per-iteration; the ``for x in <iterable>``
@@ -1143,13 +1301,18 @@ def _collect_perf_hits(
# with ``==`` (identity by tree + byte range), never ``is``.
for c in node.children:
cd = loop_depth + 1 if c == body else loop_depth
- stack.append((c, cd, next_async, next_func, next_start))
+ stack.append((c, cd, next_async, next_func, next_start, lock_depth))
else:
for c in node.children:
- stack.append((c, loop_depth + 1, next_async, next_func, next_start))
+ stack.append((c, loop_depth + 1, next_async, next_func, next_start, lock_depth))
+ elif entering_lock:
+ # Raise lock_depth for the body block only (not the lock-object expr).
+ for c in node.children:
+ cl = lock_depth + 1 if c.type in _LOCK_BODY_KINDS else lock_depth
+ stack.append((c, loop_depth, next_async, next_func, next_start, cl))
else:
for c in node.children:
- stack.append((c, loop_depth, next_async, next_func, next_start))
+ stack.append((c, loop_depth, next_async, next_func, next_start, lock_depth))
# Dedup chained sinks: ``result.scalars().all()`` parses as two call nodes
# on one line (the ``.scalars()`` sink and the ``.all()`` materializer) —
@@ -1168,11 +1331,15 @@ def _collect_perf_hits(
PerfFnFacts(
function=name,
func_start=start,
- loop_call_targets=tuple(sorted(targets.items())),
+ loop_call_targets=tuple(sorted(loop_targets.items())),
bare_sink_kind=sink[0],
+ lock_call_targets=tuple(sorted(lock_targets.items())),
+ nested_loop_line=misc[0],
+ blocking_sink_kind=misc[1],
+ blocking_sink_line=misc[2],
)
- for start, (name, targets, sink) in fn_acc.items()
- if targets or sink[0] is not None
+ for start, (name, loop_targets, lock_targets, sink, misc) in fn_acc.items()
+ if (loop_targets or lock_targets or sink[0] is not None or misc[0] or misc[1] is not None)
]
fn_facts.sort(key=lambda f: f.func_start)
return deduped, io_names, fn_facts
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 6e65a7955..cd4fb7049 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -37,7 +37,13 @@ from .complexity import FileComplexity, FunctionComplexity, walk_file
from .coverage import is_test_file as _coverage_is_test_file
from .duplication import DuplicationReport, detect_clones
from .models import HealthFileMetricData, HealthFindingData, HealthReport
-from .perf import collect_crossfn_io_in_loop
+from .perf import (
+ CallGraphIndex,
+ PerfRanker,
+ collect_blocking_io_under_lock,
+ collect_centrality_gated,
+ collect_crossfn_io_in_loop,
+)
from .scoring import attach_impacts, compute_kpis, score_file
log = structlog.get_logger(__name__)
@@ -560,25 +566,45 @@ class HealthAnalyzer:
# ------------------------------------------------------------------
def _apply_crossfn_perf(self, walked: list[tuple[Any, FileComplexity]]) -> None:
- """Splice cross-function ``io_in_loop`` hits into the walked files.
-
- Runs the bounded reachability pass once over the resolved ``calls``
- graph and appends the cross-function hits onto the matching file's
- ``perf_hits`` in place, so the ``io_in_loop`` biomarker handles
- same-function and cross-function hits through one path. Failure-isolated
- and a no-op without a graph — never blocks the rest of the report.
+ """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):
+
+ 1. cross-function ``io_in_loop`` / N+1 (PR4);
+ 2. cross-function ``blocking_io_under_lock`` (Phase 7b) — the lock→I/O
+ reachability case;
+ 3. the centrality-gated ``nested_loop_quadratic`` / ``hot_path_sync_io``
+ markers (Phase 7b), generated from the walker's per-function facts
+ ONLY for a hot function, via the :class:`PerfRanker`.
+
+ Each is appended onto the matching file's ``perf_hits`` in place so the
+ biomarkers handle every case through one path. Failure-isolated and never
+ blocks the report. The cross-function passes are a no-op without a graph;
+ the centrality-gated pass ALWAYS runs — when no graph/git signal is
+ available nothing is hot, so it emits nothing (precision-first: we never
+ ship a centrality-gated marker we cannot establish centrality for).
"""
- if self.graph is None:
- return
try:
- crossfn = collect_crossfn_io_in_loop(walked, self.graph)
+ index = CallGraphIndex(self.graph) if self.graph is not None else None
+ by_file: dict[str, list] = {}
+ if self.graph is not None and index is not None:
+ for src in (
+ collect_crossfn_io_in_loop(walked, self.graph, index=index),
+ collect_blocking_io_under_lock(walked, self.graph, index=index),
+ ):
+ for path, hits in src.items():
+ by_file.setdefault(path, []).extend(hits)
+ ranker = PerfRanker(index, self.git_meta_map)
+ for path, hits in collect_centrality_gated(walked, ranker).items():
+ by_file.setdefault(path, []).extend(hits)
+ for _pf, fcx in walked:
+ extra = by_file.get(_pf.file_info.path)
+ if extra:
+ fcx.perf_hits = [*fcx.perf_hits, *extra]
except Exception as exc:
log.debug("health_crossfn_perf_failed", error=str(exc))
return
- for _pf, fcx in walked:
- extra = crossfn.get(_pf.file_info.path)
- if extra:
- fcx.perf_hits = [*fcx.perf_hits, *extra]
def _function_blame_rows(self, walked: list[tuple[Any, FileComplexity]]) -> list[dict]:
"""Build the per-function blame rollup from the walked files + the
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 d390863a8..08282a034 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/__init__.py
@@ -8,20 +8,30 @@ This package holds:
lexicon + loop / string / async predicates + the per-language marker list)
that the complexity walker drives the perf pass off;
* the sink-agnostic bounded reachability engine (:mod:`.reachability`,
- Primitive 3) and the cross-function N+1 bridge (:mod:`.crossfn`) built on it.
+ Primitive 3) and the cross-function N+1 bridge (:mod:`.crossfn`) built on it;
+* the shared call-graph index (:mod:`.callgraph`) + the severity ranker
+ (:mod:`.ranking`, Primitive 2) used as a centrality precision gate, and the
+ centrality-gated Phase-7b markers (:mod:`.gated`).
"""
from __future__ import annotations
+from .callgraph import CallGraphIndex
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 .ranking import PerfRanker
from .reachability import ReachInfo, path_to_sink, reachable_to_sink
__all__ = [
"PERF_DIALECTS",
"BasePerfDialect",
+ "CallGraphIndex",
+ "PerfRanker",
"ReachInfo",
+ "collect_blocking_io_under_lock",
+ "collect_centrality_gated",
"collect_crossfn_io_in_loop",
"collect_io_names",
"path_to_sink",
diff --git a/packages/core/src/repowise/core/analysis/health/perf/callgraph.py b/packages/core/src/repowise/core/analysis/health/perf/callgraph.py
new file mode 100644
index 000000000..96c7029f6
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/callgraph.py
@@ -0,0 +1,91 @@
+"""Shared one-pass index of the resolved ``calls`` graph.
+
+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.
+"""
+
+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()
+ }
+
+ def resolve_function(self, path: str, func_start: int) -> str | None:
+ """Symbol-node id for the function defined at ``func_start`` in ``path``.
+
+ ``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
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 23f2c74b4..c222ed6c0 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
@@ -48,6 +48,7 @@ from __future__ import annotations
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
+from .callgraph import CallGraphIndex
from .reachability import path_to_sink, reachable_to_sink
if TYPE_CHECKING:
@@ -61,86 +62,23 @@ if TYPE_CHECKING:
CROSSFN_KIND = "io_in_loop"
-def _module_node_id(path: str) -> str:
- return f"{path}::__module__"
-
-
-class _CallGraphIndex:
- """One-pass index of the dependency graph for the cross-function pass.
-
- Holds only what the pass needs: 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", "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)
-
- def resolve_function(self, path: str, func_start: int) -> str | None:
- """Symbol-node id for the function defined at ``func_start`` in ``path``.
-
- ``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
-
-
def collect_crossfn_io_in_loop(
walked: Iterable[tuple[Any, FileComplexity]],
graph: Any,
*,
+ index: CallGraphIndex | None = None,
max_depth: int = 3,
) -> dict[str, list[PerfHit]]:
"""Cross-function ``io_in_loop`` hits, keyed by the loop-owning file path.
``walked`` is the engine's ``(parsed_file, FileComplexity)`` list; ``graph``
is the resolved dependency graph (file + symbol nodes with ``calls``
- edges), or ``None``. Each returned :class:`PerfHit` carries the sink's
- boundary kind in ``detail`` and the ``A -> ... -> sink`` symbol path in
- ``path`` (non-empty ``path`` is what marks a hit as cross-function).
+ edges), or ``None``. ``index`` is an optional pre-built
+ :class:`CallGraphIndex` (the engine builds one and shares it across the
+ graph passes); when omitted it is built from ``graph``. Each returned
+ :class:`PerfHit` carries the sink's boundary kind in ``detail`` and the
+ ``A -> ... -> sink`` symbol path in ``path`` (non-empty ``path`` is what
+ marks a hit as cross-function).
"""
walked_list = list(walked)
if graph is None or not walked_list:
@@ -159,7 +97,8 @@ def collect_crossfn_io_in_loop(
if not (has_sink and has_entry):
return {}
- index = _CallGraphIndex(graph)
+ if index is None:
+ index = CallGraphIndex(graph)
if not index.forward:
return {} # no resolved call edges → nothing cross-function to find
@@ -199,7 +138,7 @@ def collect_crossfn_io_in_loop(
def _hits_for_function(
path: str,
fact: PerfFnFacts,
- index: _CallGraphIndex,
+ index: CallGraphIndex,
reach: dict[str, Any],
sink_kind: dict[str, str],
) -> list[PerfHit]:
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
index b5c31b88a..9f6665d00 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/base.py
@@ -275,6 +275,21 @@ class BasePerfDialect:
"""
return None
+ def is_lock_scope(self, node: Node) -> bool:
+ """True if *node* opens a block-scoped held-lock region.
+
+ The walker tracks a ``lock_depth`` analogous to ``loop_depth`` so the
+ ``blocking_io_under_lock`` marker can fire on an I/O sink reached while a
+ lock is held. Only unambiguous *block* constructs qualify — C#
+ ``lock (x) { ... }`` and Java ``synchronized (x) { ... }`` — where the
+ held region is exactly the node's body. Acquire/release *pairs*
+ (``lock.acquire()`` … ``lock.release()``) are not block-scoped and are
+ deliberately out of scope here (no held-region node to bound), so this
+ defaults to ``False`` and a language that does not override it produces
+ no lock-scope signal. Precision-first by construction.
+ """
+ return False
+
# The registry, populated by ``dialects/__init__.py`` from each language module.
# Keyed by ``LanguageTag``; a missing key ⇒ the perf pass is silent for that
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.py
index 6d1996e21..21d9804db 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/csharp.py
@@ -178,9 +178,19 @@ class CSharpPerfDialect(BasePerfDialect):
"resource_construction_in_loop",
"lock_in_loop",
"serial_await_in_loop",
+ # Phase 7b — centrality-gated / nesting-confidence markers + the
+ # block-scoped lock→I/O case (``lock (x) {}`` is a held region).
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
+ "blocking_io_under_lock",
}
)
+ def is_lock_scope(self, node: Node) -> bool:
+ # ``lock (x) { ... }`` — the body is the held-lock region.
+ return node.type == "lock_statement"
+
# ``invocation_expression`` -> ``member_access_expression`` is the call
# shape; add it so a member call reads as attribute-style.
attribute_callee_kinds = BasePerfDialect.attribute_callee_kinds | frozenset(
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py
index 900d89a94..d77bea120 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/go.py
@@ -106,6 +106,10 @@ class GoPerfDialect(BasePerfDialect):
"regex_compile_in_loop",
"resource_construction_in_loop",
"lock_in_loop",
+ # Phase 7b — centrality-gated / nesting-confidence markers.
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
}
)
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py
index fd14a6812..05fbcf88d 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/java.py
@@ -108,9 +108,19 @@ class JavaPerfDialect(BasePerfDialect):
"regex_compile_in_loop",
"resource_construction_in_loop",
"lock_in_loop",
+ # Phase 7b — centrality-gated / nesting-confidence markers + the
+ # block-scoped lock→I/O case (``synchronized`` is a held region).
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
+ "blocking_io_under_lock",
}
)
+ def is_lock_scope(self, node: Node) -> bool:
+ # ``synchronized (x) { ... }`` — the body is the held-lock region.
+ return node.type == "synchronized_statement"
+
# ``s += "x"`` is an ``assignment_expression`` with the literal directly on
# the ``right`` field (no list wrapper, unlike Go).
string_literal_kinds = frozenset({"string_literal"})
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
index aeecf5cb7..2d4cb8bb8 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/python.py
@@ -104,6 +104,10 @@ class PythonPerfDialect(BasePerfDialect):
"lock_in_loop",
"serial_await_in_loop",
"membership_test_against_list_in_loop",
+ # Phase 7b — centrality-gated / nesting-confidence markers.
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
}
)
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
index 8a87eeaf4..592126a06 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/ts_js.py
@@ -91,6 +91,10 @@ class TsJsPerfDialect(BasePerfDialect):
"resource_construction_in_loop",
"serial_await_in_loop",
"membership_test_against_list_in_loop",
+ # Phase 7b — centrality-gated / nesting-confidence markers.
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
}
)
diff --git a/packages/core/src/repowise/core/analysis/health/perf/gated.py b/packages/core/src/repowise/core/analysis/health/perf/gated.py
new file mode 100644
index 000000000..fce54036d
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/gated.py
@@ -0,0 +1,202 @@
+"""Centrality-gated Phase-7b markers (the differentiator).
+
+Two passes that run after the walker, over the resolved ``calls`` graph, using
+the :class:`~.ranking.PerfRanker` (Primitive 2) and the sink-agnostic
+reachability engine (Primitive 3):
+
+ * :func:`collect_centrality_gated` — turns the walker's per-function *facts*
+ (``PerfFnFacts.nested_loop_line`` / ``blocking_sink_{kind,line}``) into
+ ``nested_loop_quadratic`` and ``hot_path_sync_io`` hits, but ONLY for a
+ function the ranker calls *hot* (top-quintile call-graph centrality or a
+ churny/hotspot file). The shapes are unambiguous but noisy when flagged
+ everywhere; the gate IS the precision fix the backlog deferred the O(n^2)
+ marker for. Keeping the generation here (not in the walker) leaves the raw
+ walker output the same high-precision same-function set it has always been.
+
+ * :func:`collect_blocking_io_under_lock` — the cross-function lock→I/O case: a
+ function holds a lock around a call to a helper that, within a few hops,
+ executes an I/O boundary. Pure moat: it reuses the identical reverse-BFS the
+ cross-function N+1 pass uses, only the *entry set* differs (callees invoked
+ while a lock is held, ``PerfFnFacts.lock_call_targets``, instead of every
+ loop-nested callee).
+
+Both are failure-isolated by their callers.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Any
+
+from .callgraph import CallGraphIndex
+from .reachability import path_to_sink, reachable_to_sink
+
+if TYPE_CHECKING:
+ from ..complexity import FileComplexity, PerfFnFacts, PerfHit
+ from .ranking import PerfRanker
+
+# The boundary-kind detail convention shared with the cross-function N+1 pass.
+LOCK_IO_KIND = "blocking_io_under_lock"
+
+
+def collect_centrality_gated(
+ walked: Iterable[tuple[Any, FileComplexity]], ranker: PerfRanker
+) -> dict[str, list[PerfHit]]:
+ """Centrality-gated ``nested_loop_quadratic`` / ``hot_path_sync_io`` hits.
+
+ Keyed by file path. For every function carrying the corresponding fact, a hit
+ is produced ONLY when ``ranker.is_hot(path, func_start)`` — so a quadratic
+ loop or a blocking sync sink ships only where it sits on a hot, central, or
+ churny path. Pure when neither graph nor git signal is available (nothing is
+ hot ⇒ no hits), which is the precision-first default.
+ """
+ from ..complexity import PerfHit
+
+ out: dict[str, list[PerfHit]] = {}
+ for pf, fcx in walked:
+ if not fcx.perf_fn_facts:
+ continue
+ path = pf.file_info.path
+ file_hits: list[PerfHit] = []
+ for fact in fcx.perf_fn_facts:
+ if fact.nested_loop_line == 0 and fact.blocking_sink_kind is None:
+ continue
+ if not ranker.is_hot(path, fact.func_start):
+ continue
+ if fact.nested_loop_line:
+ file_hits.append(
+ PerfHit(
+ kind="nested_loop_quadratic",
+ line=fact.nested_loop_line,
+ function=fact.function,
+ detail="",
+ func_start=fact.func_start,
+ )
+ )
+ if fact.blocking_sink_kind is not None:
+ file_hits.append(
+ PerfHit(
+ kind="hot_path_sync_io",
+ line=fact.blocking_sink_line,
+ function=fact.function,
+ detail=fact.blocking_sink_kind,
+ func_start=fact.func_start,
+ )
+ )
+ if file_hits:
+ out[path] = file_hits
+ return out
+
+
+def collect_blocking_io_under_lock(
+ walked: Iterable[tuple[Any, FileComplexity]],
+ graph: Any,
+ *,
+ index: CallGraphIndex | None = None,
+ max_depth: int = 3,
+) -> dict[str, list[PerfHit]]:
+ """Cross-function ``blocking_io_under_lock`` hits, keyed by the lock-owning file.
+
+ A function acquires a lock and, while holding it, calls a helper that reaches
+ an I/O boundary within ``max_depth`` hops — the I/O round-trip runs under the
+ lock, serializing every thread on a network/db/fs wait. Mirrors
+ ``crossfn.collect_crossfn_io_in_loop`` exactly: the only difference is the
+ entry set is ``PerfFnFacts.lock_call_targets`` (callees invoked under a held
+ lock) instead of loop-nested callees. The same-function case (an I/O sink
+ lexically inside a ``lock``/``synchronized`` block) is emitted directly by
+ the walker.
+ """
+ from ..complexity import PerfHit
+
+ walked_list = list(walked)
+ if graph is None or not walked_list:
+ return {}
+
+ has_sink = any(
+ fact.bare_sink_kind is not None for _pf, fcx in walked_list for fact in fcx.perf_fn_facts
+ )
+ has_entry = any(
+ fact.lock_call_targets for _pf, fcx in walked_list for fact in fcx.perf_fn_facts
+ )
+ if not (has_sink and has_entry):
+ return {}
+
+ if index is None:
+ index = CallGraphIndex(graph)
+ if not index.forward:
+ return {}
+
+ sink_kind: dict[str, str] = {}
+ for pf, fcx in walked_list:
+ path = pf.file_info.path
+ for fact in fcx.perf_fn_facts:
+ if fact.bare_sink_kind is None:
+ continue
+ sid = index.resolve_function(path, fact.func_start)
+ if sid is not None:
+ sink_kind.setdefault(sid, fact.bare_sink_kind)
+ if not sink_kind:
+ return {}
+
+ reach = reachable_to_sink(
+ sink_kind.keys(),
+ lambda node: index.reverse.get(node, ()),
+ max_depth=max_depth,
+ )
+
+ out: dict[str, list[PerfHit]] = {}
+ for pf, fcx in walked_list:
+ path = pf.file_info.path
+ for fact in fcx.perf_fn_facts:
+ if not fact.lock_call_targets:
+ continue
+ hits = _lock_hits_for_function(path, fact, index, reach, sink_kind, PerfHit)
+ if hits:
+ out.setdefault(path, []).extend(hits)
+ return out
+
+
+def _lock_hits_for_function(
+ path: str,
+ fact: PerfFnFacts,
+ index: CallGraphIndex,
+ reach: dict[str, Any],
+ sink_kind: dict[str, str],
+ perf_hit_cls: type,
+) -> list[PerfHit]:
+ a_sid = index.resolve_function(path, fact.func_start)
+ if a_sid is None:
+ return []
+ 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, ()):
+ info = reach.get(callee)
+ if info is None:
+ continue
+ chain = path_to_sink(callee, reach)
+ if not chain:
+ continue
+ seen.add(target_name)
+ kind = sink_kind.get(info.sink, "")
+ hits.append(
+ perf_hit_cls(
+ kind=LOCK_IO_KIND,
+ line=call_line,
+ function=fact.function,
+ detail=kind,
+ func_start=fact.func_start,
+ path=(a_sid, *chain),
+ )
+ )
+ break
+ return hits
diff --git a/packages/core/src/repowise/core/analysis/health/perf/ranking.py b/packages/core/src/repowise/core/analysis/health/perf/ranking.py
new file mode 100644
index 000000000..02250dc99
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/ranking.py
@@ -0,0 +1,117 @@
+"""Primitive 2 — the severity ranker, reusable as a precision GATE.
+
+The performance pillar already ranks findings by *blast radius*: a hit in a
+widely-called, churny function matters more than the same hit in a cold leaf.
+Phase 7b promotes that ranker from a sort key to a **precision gate**. Some
+patterns are noisy when flagged everywhere (a bare O(n^2) nested loop; a
+blocking I/O call outside any loop) but become high-signal the moment they sit
+in a hot, request-reachable function. The gate fires those markers *only there*.
+
+"Hot" combines two whole-program signals a file-local linter cannot compute:
+
+ * **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
+ or quadratic cost there is paid often. Direct in-degree is a deterministic,
+ ``O(E)`` proxy for request-reachability; transitive fan-in would be stronger
+ but is quadratic to compute per function.
+ * **churn** — the function's *file* is a git hotspot (``is_hotspot``) or sits
+ in the repo's top-quintile of commit volume. Churny code is read and changed
+ often, so a cost there is both more likely to bite and more worth fixing.
+
+Either signal alone makes a function hot (logical OR): a hub utility with no
+churn is still hot by centrality; a frequently-rewritten handler with few static
+callers is still hot by churn. When neither the graph nor git metadata is
+available the gate degrades to "nothing is hot" — the markers behind it simply
+do not fire, never a false positive.
+"""
+
+from __future__ import annotations
+
+from .callgraph import CallGraphIndex
+
+
+def _percentile_threshold(values: list[int], pct: float) -> int:
+ """The ``pct`` percentile of *values* (inclusive-lower), or a high sentinel.
+
+ Mirrors ``engine._percentile_p80``'s convention so the centrality / churn
+ quintiles agree with the rest of the health pipeline. Returns a value larger
+ than any input when *values* is empty, so an empty distribution gates
+ everything out (nothing clears an unreachable bar).
+ """
+ if not values:
+ return 1 << 30
+ ordered = sorted(values)
+ idx = min(len(ordered) - 1, max(0, int(pct * len(ordered))))
+ return ordered[idx]
+
+
+class PerfRanker:
+ """Decides whether a function is *hot* enough for a centrality-gated marker.
+
+ Build once per ``analyze()`` from the shared :class:`CallGraphIndex` and the
+ engine's ``git_meta_map``; call :meth:`is_hot` per candidate hit. Both the
+ centrality threshold (top-quintile caller count) and the churn threshold
+ (top-quintile commit volume) are computed up front from the repo-wide
+ distributions, so the gate adapts to the repo instead of assuming a fixed
+ bar.
+ """
+
+ __slots__ = ("_churn_p80", "_hot_in_degree", "_hotspot_files", "_index", "_meta")
+
+ def __init__(
+ self,
+ index: CallGraphIndex | None,
+ git_meta_map: dict[str, dict] | None,
+ *,
+ centrality_pct: float = 0.8,
+ churn_pct: float = 0.8,
+ ) -> None:
+ self._index = index
+ self._meta = git_meta_map or {}
+
+ # Centrality bar: the top-quintile direct-caller count over functions
+ # that have at least one caller. ``max(2, ...)`` keeps a tiny graph from
+ # calling a function with a single caller "central".
+ in_degrees = [d for d in (index.in_degree.values() if index else ()) if d >= 1]
+ self._hot_in_degree = max(2, _percentile_threshold(in_degrees, centrality_pct))
+
+ # Churn bar + the explicit hotspot set, both off git metadata.
+ commit_counts: list[int] = []
+ hotspot_files: set[str] = set()
+ for path, meta in self._meta.items():
+ if not isinstance(meta, dict):
+ continue
+ if meta.get("is_hotspot"):
+ hotspot_files.add(path)
+ c = meta.get("commit_count_total")
+ if isinstance(c, int) and c > 0:
+ commit_counts.append(c)
+ self._churn_p80 = _percentile_threshold(commit_counts, churn_pct)
+ self._hotspot_files = hotspot_files
+
+ # -- the gate -------------------------------------------------------------
+
+ def is_central(self, path: str, func_start: int) -> bool:
+ """True if the function at ``(path, func_start)`` is top-quintile-called."""
+ if self._index is None:
+ return False
+ sid = self._index.resolve_function(path, func_start)
+ if sid is None:
+ return False
+ return self._index.in_degree.get(sid, 0) >= self._hot_in_degree
+
+ def is_churny(self, path: str) -> bool:
+ """True if ``path`` is a git hotspot or in the top commit-volume quintile."""
+ if path in self._hotspot_files:
+ return True
+ meta = self._meta.get(path)
+ if not isinstance(meta, dict):
+ return False
+ c = meta.get("commit_count_total")
+ return isinstance(c, int) and c >= self._churn_p80
+
+ def is_hot(self, path: str, func_start: int) -> bool:
+ """The OR gate: central OR churny ⇒ worth flagging a noisy-when-ungated
+ marker here. Pure when neither graph nor git metadata is available."""
+ return self.is_central(path, func_start) or self.is_churny(path)
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 0c2239b57..13fc599a9 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -217,6 +217,11 @@ _BIOMARKER_DIMENSIONS: dict[str, set[str]] = {
"lock_in_loop": {"performance"},
"serial_await_in_loop": {"performance"},
"membership_test_against_list_in_loop": {"performance"},
+ # Phase 7b centrality-gated moat markers - performance-only.
+ "nested_loop_with_io": {"performance"},
+ "nested_loop_quadratic": {"performance"},
+ "hot_path_sync_io": {"performance"},
+ "blocking_io_under_lock": {"performance"},
}
# Maintainability per-biomarker weight multipliers. Expert-set by definition -
@@ -292,6 +297,15 @@ _PERFORMANCE_WEIGHT_MULTIPLIER: dict[str, float] = {
"lock_in_loop": 0.5,
"membership_test_against_list_in_loop": 0.5,
"serial_await_in_loop": 0.4,
+ # Phase 7b markers. Ship at advisory weight pending each one's Phase-0 gate
+ # (MARKER_BACKLOG.md / PHASE7B_LABELS.md). nested_loop_with_io rides with
+ # io_in_loop (nesting-confident); blocking_io_under_lock is high-confidence
+ # by construction (a sink under a held lock); the centrality-gated pair are
+ # advisory (the gate is precision, but the algorithmic cost is context-bound).
+ "nested_loop_with_io": 0.5,
+ "blocking_io_under_lock": 0.6,
+ "hot_path_sync_io": 0.5,
+ "nested_loop_quadratic": 0.4,
}
# All perf biomarkers share one ``performance`` category, so the single cap
@@ -304,6 +318,10 @@ _PERFORMANCE_CATEGORY: dict[str, str] = {
"lock_in_loop": "performance",
"serial_await_in_loop": "performance",
"membership_test_against_list_in_loop": "performance",
+ "nested_loop_with_io": "performance",
+ "nested_loop_quadratic": "performance",
+ "hot_path_sync_io": "performance",
+ "blocking_io_under_lock": "performance",
}
# One bounded performance category cap. ~1.0 keeps performance advisory.
@@ -321,6 +339,10 @@ _PERFORMANCE_HOME: frozenset[str] = frozenset(
"lock_in_loop",
"serial_await_in_loop",
"membership_test_against_list_in_loop",
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
+ "blocking_io_under_lock",
}
)
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index f0e9394d6..996f3b1db 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -268,6 +268,30 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
description:
"Testing `x in big_list` (or big_list.includes(x)) inside a loop is O(n·m); a set makes each lookup O(1), turning the loop linear. Only fires when the right operand is provably a list, never a set or dict.",
},
+ nested_loop_with_io: {
+ label: "I/O in nested loop",
+ category: "performance",
+ description:
+ "A database / network / filesystem / subprocess call in the inner body of a nested loop — O(n·m) round-trips, the quadratic cousin of I/O-in-loop. The nesting raises confidence it is real, so it surfaces alongside io_in_loop. Batch the inner query or restructure the loops.",
+ },
+ hot_path_sync_io: {
+ label: "Blocking I/O on a hot path",
+ category: "performance",
+ description:
+ "A blocking subprocess or filesystem call in a hot, request-reachable function (top call-graph centrality or a churny file), even outside a loop. Its latency is paid on every call through the function. Advisory — a latency signal ranked by centrality, not always a defect.",
+ },
+ blocking_io_under_lock: {
+ label: "Blocking I/O under a lock",
+ category: "performance",
+ description:
+ "A database / network / filesystem / subprocess round-trip reached while a lock is held (a C# lock(){} or Java synchronized(){} block, directly or through a call). Every other thread blocks for the full I/O wait. Do the I/O outside the critical section and take the lock only to mutate shared state.",
+ },
+ nested_loop_quadratic: {
+ label: "Quadratic nested loop",
+ category: "performance",
+ description:
+ "A data-dependent loop nested inside another (O(n^2)) in a hot, central function. Advisory / informational — surfaced only where centrality ranking says it is worth a look; check the inner bound or use a set/map lookup if it is a search.",
+ },
};
export function biomarkerInfo(name: string): BiomarkerInfo {
@@ -324,6 +348,10 @@ export const PERFORMANCE_HOME_BIOMARKERS: ReadonlySet<string> = new Set([
"lock_in_loop",
"serial_await_in_loop",
"membership_test_against_list_in_loop",
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
+ "blocking_io_under_lock",
]);
/**
diff --git a/tests/unit/health/test_perf_phase7b.py b/tests/unit/health/test_perf_phase7b.py
new file mode 100644
index 000000000..d26152d9b
--- /dev/null
+++ b/tests/unit/health/test_perf_phase7b.py
@@ -0,0 +1,388 @@
+"""Unit tests for the Phase-7b centrality-gated moat markers.
+
+Four markers built on Primitive 2 (the severity ranker, used as a precision
+gate) and Primitive 3 (the sink-agnostic reachability engine):
+
+ * ``nested_loop_with_io`` — an I/O sink two loops deep (un-gated; nesting is
+ the precision lever). Emitted directly by the walker.
+ * ``blocking_io_under_lock`` — an I/O sink reached while a block-scoped lock is
+ held (same-function via the walker; cross-function via reachability).
+ * ``nested_loop_quadratic`` / ``hot_path_sync_io`` — recorded as per-function
+ facts by the walker and turned into hits by the engine's centrality gate
+ ONLY for a hot (central / churny) function.
+
+Grammar availability is best-effort (a missing grammar degrades to "no hits").
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+import pytest
+
+from repowise.core.analysis.health.biomarkers.base import FileContext
+from repowise.core.analysis.health.biomarkers.blocking_io_under_lock import (
+ BlockingIoUnderLockDetector,
+)
+from repowise.core.analysis.health.biomarkers.hot_path_sync_io import HotPathSyncIoDetector
+from repowise.core.analysis.health.biomarkers.nested_loop_quadratic import (
+ NestedLoopQuadraticDetector,
+)
+from repowise.core.analysis.health.biomarkers.nested_loop_with_io import NestedLoopWithIoDetector
+from repowise.core.analysis.health.biomarkers.registry import detect_all
+from repowise.core.analysis.health.complexity import PerfFnFacts, PerfHit, walk_file
+from repowise.core.analysis.health.perf import (
+ CallGraphIndex,
+ PerfRanker,
+ collect_blocking_io_under_lock,
+ collect_centrality_gated,
+)
+from repowise.core.analysis.health.scoring import dimensions_for, score_file
+
+_NEW_KINDS = [
+ "nested_loop_with_io",
+ "nested_loop_quadratic",
+ "hot_path_sync_io",
+ "blocking_io_under_lock",
+]
+
+
+def _hits(lang: str, src: str):
+ fc = walk_file(f"t.{lang}", lang, src.encode())
+ return sorted((h.kind, h.detail) for h in fc.perf_hits)
+
+
+def _facts(lang: str, src: str) -> dict[str | None, PerfFnFacts]:
+ fc = walk_file(f"t.{lang}", lang, src.encode())
+ return {f.function: f for f in fc.perf_fn_facts}
+
+
+# ---------------------------------------------------------------------------
+# nested_loop_with_io — un-gated, rides alongside io_in_loop (loop_depth >= 2)
+# ---------------------------------------------------------------------------
+
+_NESTED_IO_CASES = [
+ (
+ "python",
+ "def f(session, groups):\n"
+ " for g in groups:\n"
+ " for r in g:\n"
+ " session.execute(r)\n",
+ [("io_in_loop", "db"), ("nested_loop_with_io", "db")],
+ "db execute two loops deep -> io_in_loop + nested_loop_with_io",
+ ),
+ (
+ "python",
+ "def f(session, repos):\n for r in repos:\n session.execute(r)\n",
+ [("io_in_loop", "db")],
+ "a single loop is io_in_loop only (no nesting)",
+ ),
+ (
+ "typescript",
+ "async function f(groups){ for (const g of groups){ "
+ "for (const u of g){ await fetch(u); } } }",
+ [
+ ("io_in_loop", "network"),
+ ("nested_loop_with_io", "network"),
+ ("serial_await_in_loop", "network"),
+ ],
+ "awaited fetch two loops deep -> +nested_loop_with_io",
+ ),
+]
+
+
+ "lang,src,expected,note", _NESTED_IO_CASES, ids=[c[3] for c in _NESTED_IO_CASES]
+)
+def test_nested_loop_with_io_cases(lang, src, expected, note):
+ assert _hits(lang, src) == sorted(expected), note
+
+
+# ---------------------------------------------------------------------------
+# blocking_io_under_lock — same-function (C# lock / Java synchronized blocks)
+# ---------------------------------------------------------------------------
+
+_LOCK_IO_CASES = [
+ (
+ "csharp",
+ "class A{ void M(object gate, AppDbContext ctx){ lock(gate){ ctx.SaveChanges(); } } }",
+ [("blocking_io_under_lock", "db")],
+ "EF SaveChanges() inside lock(){} -> blocking_io_under_lock",
+ ),
+ (
+ "csharp",
+ "class A{ void M(object gate, AppDbContext ctx){"
+ " ctx.SaveChanges(); lock(gate){ Use(); } } }",
+ [],
+ "a sink OUTSIDE the lock block does not fire",
+ ),
+ (
+ "java",
+ "class A{ void m(Object g, javax.persistence.EntityManager em){"
+ " synchronized(g){ em.getResultList(); } } }",
+ [("blocking_io_under_lock", "db")],
+ "JPA getResultList() inside synchronized(){} -> blocking_io_under_lock",
+ ),
+ (
+ "java",
+ "class A{ void m(javax.persistence.EntityManager em){"
+ " synchronized(em.getResultList()){ Use(); } } }",
+ [],
+ "a sink in the lock-OBJECT expression runs before the lock is held",
+ ),
+]
+
+
+ "lang,src,expected,note", _LOCK_IO_CASES, ids=[c[3] for c in _LOCK_IO_CASES]
+)
+def test_blocking_io_under_lock_same_function(lang, src, expected, note):
+ assert _hits(lang, src) == sorted(expected), note
+
+
+# ---------------------------------------------------------------------------
+# The walker records the gated facts (it does NOT emit the gated hits itself)
+# ---------------------------------------------------------------------------
+
+
+def test_walker_records_nested_loop_fact_not_a_hit():
+ src = "def f(xs, ys):\n for x in xs:\n for y in ys:\n use(x, y)\n"
+ fc = walk_file("t.py", "python", src.encode())
+ # No I/O, no nested_loop_with_io hit — but the fact is recorded for the gate.
+ assert all(h.kind != "nested_loop_quadratic" for h in fc.perf_hits)
+ fact = {f.function: f for f in fc.perf_fn_facts}["f"]
+ assert fact.nested_loop_line == 3 # the inner ``for``
+
+
+def test_walker_records_blocking_sink_fact_not_a_hit():
+ src = "import subprocess\ndef handler(args):\n return subprocess.run(args)\n"
+ fc = walk_file("t.py", "python", src.encode())
+ assert all(h.kind != "hot_path_sync_io" for h in fc.perf_hits)
+ fact = {f.function: f for f in fc.perf_fn_facts}["handler"]
+ assert fact.blocking_sink_kind == "subprocess"
+ assert fact.blocking_sink_line == 3
+
+
+def test_awaited_sink_is_not_a_blocking_fact():
+ src = "import httpx\nasync def handler(u):\n return await httpx.get(u)\n"
+ fact = _facts("py", src).get("handler")
+ # An awaited (non-blocking) sink is not a hot_path candidate.
+ assert fact is None or fact.blocking_sink_kind is None
+
+
+def test_db_materializer_is_not_a_blocking_fact():
+ # ``result.scalars().all()`` is a materializer on an already-awaited query,
+ # not a blocking round-trip — db is excluded from hot_path (probe FP fix).
+ src = "def handler(result):\n return result.scalars().all()\n"
+ fact = _facts("py", src).get("handler")
+ assert fact is None or fact.blocking_sink_kind is None
+
+
+# ---------------------------------------------------------------------------
+# The centrality gate — emits the two markers ONLY for a hot function
+# ---------------------------------------------------------------------------
+
+
+class _PF:
+ """Minimal stand-in for a ParsedFile (the gate only reads file_info.path)."""
+
+ class _FI:
+ def __init__(self, path):
+ self.path = path
+
+ def __init__(self, path):
+ self.file_info = _PF._FI(path)
+
+
+def _walked(path: str, src: str):
+ return [(_PF(path), walk_file(path, "python", src.encode()))]
+
+
+_HOT_SRC = (
+ "import subprocess\n"
+ "def hot(xs, ys):\n"
+ " subprocess.run(['git', 'status'])\n" # a blocking loop_depth-0 sink (hot_path)
+ " for x in xs:\n"
+ " for y in ys:\n" # nested loop (quadratic)
+ " use(x, y)\n"
+)
+
+
+def test_centrality_gate_fires_in_a_churny_file():
+ walked = _walked("svc.py", _HOT_SRC)
+ # No graph, but the file is a git hotspot -> churny -> hot.
+ ranker = PerfRanker(None, {"svc.py": {"is_hotspot": True}})
+ out = collect_centrality_gated(walked, ranker)
+ kinds = sorted(h.kind for h in out.get("svc.py", []))
+ assert kinds == ["hot_path_sync_io", "nested_loop_quadratic"]
+ assert out["svc.py"][0].detail or True # hot_path carries the boundary kind
+
+
+def test_centrality_gate_silent_without_any_hot_signal():
+ walked = _walked("cold.py", _HOT_SRC)
+ # No graph, no git metadata -> nothing is hot -> no gated markers ship.
+ ranker = PerfRanker(None, {})
+ assert collect_centrality_gated(walked, ranker) == {}
+
+
+def test_centrality_gate_fires_for_a_central_function():
+ # A symbol with top-quintile caller count is "central" even without churn.
+ g = nx.MultiDiGraph()
+ g.add_node(
+ "svc.py::hot", node_type="symbol", name="hot", file_path="svc.py", start_line=1, end_line=6
+ )
+ callers = []
+ for i in range(4):
+ cid = f"c.py::caller{i}"
+ g.add_node(
+ cid,
+ node_type="symbol",
+ name=f"caller{i}",
+ file_path="c.py",
+ start_line=10 + i,
+ end_line=11 + i,
+ )
+ g.add_edge(cid, "svc.py::hot", edge_type="calls")
+ callers.append(cid)
+ # A cold leaf with a single caller — must NOT be central.
+ g.add_node(
+ "svc.py::cold",
+ node_type="symbol",
+ name="cold",
+ file_path="svc.py",
+ start_line=20,
+ end_line=25,
+ )
+ g.add_edge(callers[0], "svc.py::cold", edge_type="calls")
+
+ index = CallGraphIndex(g)
+ ranker = PerfRanker(index, {})
+ assert ranker.is_central("svc.py", 1) is True
+ assert ranker.is_central("svc.py", 20) is False
+
+
+# ---------------------------------------------------------------------------
+# Cross-function blocking_io_under_lock — reachability with a lock entry set
+# ---------------------------------------------------------------------------
+
+
+def _fake_graph(symbols: dict[str, tuple[str, int, int]], calls: list[tuple[str, str]]):
+ """Build a tiny resolved-calls DiGraph. ``symbols`` maps id -> (path, start, end)."""
+ g = nx.MultiDiGraph()
+ for sid, (path, start, end) in symbols.items():
+ g.add_node(
+ sid,
+ node_type="symbol",
+ name=sid.rsplit("::", 1)[-1],
+ file_path=path,
+ start_line=start,
+ end_line=end,
+ )
+ for src, dst in calls:
+ g.add_edge(src, dst, edge_type="calls")
+ return g
+
+
+def test_crossfn_blocking_io_under_lock():
+ # ``holder`` holds a lock around a call to ``writer``; ``writer`` does the I/O.
+ symbols = {
+ "svc.py::holder": ("svc.py", 1, 5),
+ "svc.py::writer": ("svc.py", 7, 9),
+ }
+ graph = _fake_graph(symbols, [("svc.py::holder", "svc.py::writer")])
+ pf = _PF("svc.py")
+ fcx = walk_file("svc.py", "python", b"def x():\n pass\n") # facts overridden below
+ fcx.perf_fn_facts = [
+ PerfFnFacts(
+ function="holder",
+ func_start=1,
+ loop_call_targets=(),
+ bare_sink_kind=None,
+ lock_call_targets=(("writer", 3),),
+ ),
+ PerfFnFacts(
+ function="writer",
+ func_start=7,
+ loop_call_targets=(),
+ bare_sink_kind="db",
+ ),
+ ]
+ out = collect_blocking_io_under_lock([(pf, fcx)], graph)
+ hits = [h for hs in out.values() for h in hs]
+ assert len(hits) == 1
+ h = hits[0]
+ assert h.kind == "blocking_io_under_lock"
+ assert h.detail == "db"
+ assert h.function == "holder"
+ assert h.path[0].endswith("::holder")
+ assert h.path[-1].endswith("::writer")
+
+
+def test_crossfn_blocking_io_under_lock_no_lock_is_noop():
+ symbols = {"svc.py::a": ("svc.py", 1, 3), "svc.py::b": ("svc.py", 5, 7)}
+ graph = _fake_graph(symbols, [("svc.py::a", "svc.py::b")])
+ pf = _PF("svc.py")
+ fcx = walk_file("svc.py", "python", b"def x():\n pass\n")
+ fcx.perf_fn_facts = [
+ PerfFnFacts(function="a", func_start=1, loop_call_targets=(("b", 2),), bare_sink_kind=None),
+ PerfFnFacts(function="b", func_start=5, loop_call_targets=(), bare_sink_kind="db"),
+ ]
+ # ``a`` calls ``b`` in a loop, not under a lock -> no lock→io hit.
+ assert collect_blocking_io_under_lock([(pf, fcx)], graph) == {}
+
+
+# ---------------------------------------------------------------------------
+# Biomarkers lift hits; scoring keeps every marker performance-only
+# ---------------------------------------------------------------------------
+
+
+def _ctx(perf_hits: list[PerfHit]) -> FileContext:
+ return FileContext(
+ file_path="x.py",
+ language="python",
+ nloc=10,
+ has_test_file=False,
+ module="x",
+ perf_hits=perf_hits,
+ )
+
+
[email protected]("kind", _NEW_KINDS)
+def test_each_marker_is_performance_only(kind):
+ assert dimensions_for(kind) == {"performance"}
+
+
+def test_detectors_only_consume_their_own_kind():
+ ctx = _ctx(
+ [
+ PerfHit("nested_loop_with_io", 1, "f", "db"),
+ PerfHit("nested_loop_quadratic", 2, "f", ""),
+ PerfHit("hot_path_sync_io", 3, "f", "network"),
+ PerfHit("blocking_io_under_lock", 4, "f", "db"),
+ ]
+ )
+ assert len(NestedLoopWithIoDetector().detect(ctx)) == 1
+ assert len(NestedLoopQuadraticDetector().detect(ctx)) == 1
+ assert len(HotPathSyncIoDetector().detect(ctx)) == 1
+ assert len(BlockingIoUnderLockDetector().detect(ctx)) == 1
+
+
+def test_blocking_io_under_lock_renders_cross_function_path():
+ hit = PerfHit(
+ "blocking_io_under_lock", 3, "holder", "db", path=("svc.py::holder", "svc.py::writer")
+ )
+ (finding,) = BlockingIoUnderLockDetector().detect(_ctx([hit]))
+ assert finding.details["cross_function"] is True
+ assert finding.details["path"] == list(hit.path)
+ assert "holder -> writer" in finding.reason
+
+
+def test_new_markers_score_performance_not_defect():
+ ctx = _ctx([PerfHit(k, i + 1, "f", "") for i, k in enumerate(_NEW_KINDS)])
+ results = detect_all(ctx)
+ got = {r.biomarker_type for r in results}
+ assert set(_NEW_KINDS) <= got
+ scores, deductions = score_file(results)
+ assert scores["defect"] == 10.0
+ assert scores["maintainability"] == 10.0
+ assert scores["performance"] < 10.0
+ assert all(d == 0.0 for d in deductions)