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): interprocedural quadratic-loop taint primitive (validated, unsurfaced) (#712)

Raghav Chamadiya08c0aaacbd04
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index 574652f41..73deb85d8 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -185,6 +185,14 @@ class PerfHit:
(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``.
+ - ``interprocedural_quadratic_loop`` — a loop calls a helper that, within a
+ few hops, contains its OWN data-dependent loop: O(n^2)+ pure-CPU cost split
+ across the call boundary (no I/O involved). Cross-function only, produced by
+ ``perf.gated.collect_interprocedural_quadratic``. **Infrastructure only, not
+ surfaced:** the collector validated at ~2% precision (the naive sink
+ over-fires on linear-total "process each element's own children" shapes), so
+ no biomarker consumes this kind and the engine does not run the pass. Kept
+ for a future interprocedural-dataflow-gated detector.
The Phase-7a markers above are emitted via the dialect ``loop_call_marker`` /
``loop_stmt_marker`` hooks (and the inline awaited-sink path for
@@ -239,6 +247,13 @@ class PerfFnFacts:
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.
+
+ ``own_loop_line`` makes the function an ``interprocedural_quadratic_loop``
+ *reachability target*: a representative line of a data-dependent loop the
+ function contains at any depth (0 = none). When a loop in another function
+ calls into this one (directly or within a few hops), the callee's own loop
+ runs once per outer iteration — an O(n^2)+ algorithmic cost with no I/O. It is
+ the pure-CPU analogue of ``bare_sink_kind`` (which targets an I/O sink).
"""
function: str | None
@@ -256,6 +271,10 @@ class PerfFnFacts:
nested_loop_line: int = 0
blocking_sink_kind: str | None = None
blocking_sink_line: int = 0
+ # Cross-function quadratic fact: a representative data-dependent loop line
+ # this function contains (0 = none). Makes the function a reachability target
+ # for the cross-function ``interprocedural_quadratic_loop`` pass.
+ own_loop_line: int = 0
@dataclass
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py
index 3b9830a25..db63303b3 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py
@@ -159,6 +159,9 @@ def _collect_perf_hits(
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
+ # Record every function's own data-dependent loop so a caller looping over
+ # it becomes a cross-function ``interprocedural_quadratic_loop`` target.
+ do_interproc_quad = "interprocedural_quadratic_loop" 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).
@@ -183,6 +186,7 @@ def _collect_perf_hits(
# 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
+ # misc[3] = own_loop_line (first data-dependent loop, any depth)
fn_acc: dict[
int, tuple[str | None, dict[str, int], dict[str, int], list[str | None], list]
] = {}
@@ -192,7 +196,7 @@ def _collect_perf_hits(
) -> 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], [0, None, 0])
+ entry = (func_name, {}, {}, [None], [0, None, 0, 0])
fn_acc[func_start] = entry
return entry[1], entry[2], entry[3], entry[4]
@@ -234,6 +238,15 @@ def _collect_perf_hits(
if misc[0] == 0:
misc[0] = node.start_point[0] + 1
+ # Any data-dependent loop makes the function a cross-function
+ # ``interprocedural_quadratic_loop`` target — a caller looping over it
+ # pays O(n^2)+. Record the first such loop's line (any nesting depth);
+ # the engine emits a hit only when the LOOP-OWNING caller is hot.
+ if is_loop and do_interproc_quad:
+ misc = _acc(next_start, next_func)[3]
+ if misc[3] == 0:
+ misc[3] = node.start_point[0] + 1
+
# A loop whose ITERABLE is itself a slow call (``for _, r in
# df.iterrows()``): the call sits in the loop header (runs once), so the
# body call markers never see it. Fire on the loop node itself, at any
@@ -457,9 +470,17 @@ def _collect_perf_hits(
nested_loop_line=misc[0],
blocking_sink_kind=misc[1],
blocking_sink_line=misc[2],
+ own_loop_line=misc[3],
)
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)
+ if (
+ loop_targets
+ or lock_targets
+ or sink[0] is not None
+ or misc[0]
+ or misc[1] is not None
+ or misc[3]
+ )
]
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 6af9250f3..87db541c5 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -650,15 +650,22 @@ class HealthAnalyzer:
def _apply_crossfn_perf(self, walked: list[tuple[Any, FileComplexity]]) -> None:
"""Run the graph-dependent perf passes over the walked files, in place.
- Four sources of extra ``perf_hits``, all sharing one
+ Three 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
+ 2. cross-function ``blocking_io_under_lock`` — 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`.
+ markers, generated from the walker's per-function facts ONLY for a
+ hot function, via the :class:`PerfRanker`.
+
+ The cross-function ``interprocedural_quadratic_loop`` collector
+ (:func:`perf.gated.collect_interprocedural_quadratic`) is deliberately
+ NOT wired here: it validated at ~2% precision (the naive "reaches a loop"
+ taint over-fires on the linear-total "process each element's own children"
+ shape), so it stays available as reusable infrastructure for a future
+ interprocedural-dataflow-gated version rather than a live finding source.
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
diff --git a/packages/core/src/repowise/core/analysis/health/perf/__init__.py b/packages/core/src/repowise/core/analysis/health/perf/__init__.py
index 2fc06c919..8426fc147 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/__init__.py
@@ -19,7 +19,11 @@ 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 .gated import (
+ collect_blocking_io_under_lock,
+ collect_centrality_gated,
+ collect_interprocedural_quadratic,
+)
from .io_boundaries import collect_io_names
from .promotion import apply_perf_promotions
from .ranking import PerfRanker
@@ -35,6 +39,7 @@ __all__ = [
"collect_blocking_io_under_lock",
"collect_centrality_gated",
"collect_crossfn_io_in_loop",
+ "collect_interprocedural_quadratic",
"collect_io_names",
"path_to_sink",
"reachable_to_sink",
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 9369b2826..c6881c4cd 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
@@ -173,6 +173,9 @@ class CSharpPerfDialect(BasePerfDialect):
markers = frozenset(
{
"io_in_loop",
+ # Record own data-dependent loops so a caller looping over this
+ # function becomes a cross-function quadratic target.
+ "interprocedural_quadratic_loop",
"string_concat_in_loop",
"blocking_sync_in_async",
"resource_construction_in_loop",
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/dart.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/dart.py
index 4ecb21639..5c52dea28 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/dart.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/dart.py
@@ -76,6 +76,9 @@ class DartPerfDialect(BasePerfDialect):
markers = frozenset(
{
"io_in_loop",
+ # Record own data-dependent loops so a caller looping over this
+ # function becomes a cross-function quadratic target.
+ "interprocedural_quadratic_loop",
"serial_await_in_loop",
"string_concat_in_loop",
"resource_construction_in_loop",
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 da639813e..64837aa6a 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
@@ -105,6 +105,9 @@ class GoPerfDialect(BasePerfDialect):
markers = frozenset(
{
"io_in_loop",
+ # Record own data-dependent loops so a caller looping over this
+ # function becomes a cross-function quadratic target.
+ "interprocedural_quadratic_loop",
"string_concat_in_loop",
"defer_in_loop",
"regex_compile_in_loop",
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 05fbcf88d..450416d66 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
@@ -104,6 +104,9 @@ class JavaPerfDialect(BasePerfDialect):
markers = frozenset(
{
"io_in_loop",
+ # Record own data-dependent loops so a caller looping over this
+ # function becomes a cross-function quadratic target.
+ "interprocedural_quadratic_loop",
"string_concat_in_loop",
"regex_compile_in_loop",
"resource_construction_in_loop",
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 a7ceb0101..a0dd0eed9 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
@@ -98,6 +98,9 @@ class PythonPerfDialect(BasePerfDialect):
markers = frozenset(
{
"io_in_loop",
+ # Record own data-dependent loops so a caller looping over this
+ # function becomes a cross-function quadratic target.
+ "interprocedural_quadratic_loop",
"string_concat_in_loop",
"blocking_sync_in_async",
"resource_construction_in_loop",
diff --git a/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.py b/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.py
index 468244a45..a906df513 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/dialects/rust.py
@@ -127,6 +127,9 @@ class RustPerfDialect(BasePerfDialect):
markers = frozenset(
{
"io_in_loop",
+ # Record own data-dependent loops so a caller looping over this
+ # function becomes a cross-function quadratic target.
+ "interprocedural_quadratic_loop",
"blocking_sync_in_async",
"regex_compile_in_loop",
"resource_construction_in_loop",
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 3fbabb7ef..25d5395f4 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
@@ -87,6 +87,9 @@ class TsJsPerfDialect(BasePerfDialect):
markers = frozenset(
{
"io_in_loop",
+ # Record own data-dependent loops so a caller looping over this
+ # function becomes a cross-function quadratic target.
+ "interprocedural_quadratic_loop",
"string_concat_in_loop",
"resource_construction_in_loop",
"serial_await_in_loop",
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..d6994e8ad 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/gated.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/gated.py
@@ -1,6 +1,6 @@
-"""Centrality-gated Phase-7b markers (the differentiator).
+"""Centrality-gated markers (the differentiator).
-Two passes that run after the walker, over the resolved ``calls`` graph, using
+Three 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):
@@ -20,7 +20,27 @@ reachability engine (Primitive 3):
while a lock is held, ``PerfFnFacts.lock_call_targets``, instead of every
loop-nested callee).
-Both are failure-isolated by their callers.
+ * :func:`collect_interprocedural_quadratic` — the cross-function
+ algorithmic-complexity case: a loop in function ``A`` calls a helper ``B``
+ that, within a few hops, contains its OWN data-dependent loop. Each outer
+ iteration pays for ``B``'s inner loop — O(n^2)+ pure-CPU cost with no I/O, the
+ single largest class of real perf bugs (Jin PLDI'12) and invisible to the
+ I/O-centric passes. It reuses the identical reverse-BFS as the N+1 pass; the
+ only differences are the sink set (functions with ``PerfFnFacts.own_loop_line``
+ instead of a bare I/O sink) and a **centrality gate on the loop owner** ``A``.
+
+ **NOT wired into the engine.** Validated at ~2% precision on 4 repos (64
+ hand-labels): the sink "callee contains any data-dependent loop" is satisfied
+ by nearly every collection-processing helper, and the dominant real shape — a
+ helper looping over the current element's OWN sub-data — is linear-total, not
+ quadratic. Telling the two apart needs interprocedural (cross-call)
+ argument-derivation dataflow the intra-procedural ``dataflow`` layer does not
+ provide. This collector + ``PerfFnFacts.own_loop_line`` are kept as validated,
+ tested infrastructure for that future dataflow-gated detector, but the engine
+ does not call this pass, so the marker never reaches a finding. See
+ ``local-stash/performance-pillar/{PROBE_FINDINGS,MARKER_BACKLOG}.md``.
+
+The centrality-gated pair are failure-isolated by their callers.
"""
from __future__ import annotations
@@ -38,6 +58,9 @@ if TYPE_CHECKING:
# The boundary-kind detail convention shared with the cross-function N+1 pass.
LOCK_IO_KIND = "blocking_io_under_lock"
+# The cross-function algorithmic-complexity marker.
+INTERPROC_QUAD_KIND = "interprocedural_quadratic_loop"
+
def collect_centrality_gated(
walked: Iterable[tuple[Any, FileComplexity]], ranker: PerfRanker
@@ -200,3 +223,128 @@ def _lock_hits_for_function(
)
break
return hits
+
+
+def collect_interprocedural_quadratic(
+ walked: Iterable[tuple[Any, FileComplexity]],
+ graph: Any,
+ ranker: PerfRanker,
+ *,
+ index: CallGraphIndex | None = None,
+ max_depth: int = 3,
+) -> dict[str, list[PerfHit]]:
+ """Cross-function ``interprocedural_quadratic_loop`` hits, keyed by the loop-owning file.
+
+ A loop in function ``A`` calls a helper that, within ``max_depth`` hops,
+ contains its own data-dependent loop: the inner loop runs once per outer
+ iteration, an O(n^2)+ algorithmic cost with no I/O. Mirrors
+ :func:`collect_blocking_io_under_lock` exactly, with two differences:
+
+ * the **sink set** is functions carrying a data-dependent loop
+ (``PerfFnFacts.own_loop_line``), not a bare I/O sink;
+ * every candidate is **centrality-gated on the loop owner** ``A`` via the
+ :class:`~.ranking.PerfRanker` — the raw "loop calls a looping helper"
+ shape is common and mostly benign, so a hit survives only where ``A``
+ sits on a hot, central, or churny path. Pure when neither graph nor git
+ signal is available (nothing is hot -> no hits): the precision-first
+ default, exactly as for the same-function quadratic marker.
+ """
+ walked_list = list(walked)
+ if graph is None or not walked_list:
+ return {}
+
+ # Cheap pre-check over the already-computed facts: the case needs BOTH a
+ # function holding a data-dependent loop (a reachability target) and a
+ # function with a loop-nested call (an entry). Skip the graph otherwise.
+ has_sink = any(fact.own_loop_line for _pf, fcx in walked_list for fact in fcx.perf_fn_facts)
+ has_entry = any(
+ fact.loop_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 set: functions that contain a data-dependent loop -------------
+ loop_sinks: set[str] = set()
+ for pf, fcx in walked_list:
+ path = pf.file_info.path
+ for fact in fcx.perf_fn_facts:
+ if not fact.own_loop_line:
+ continue
+ sid = index.resolve_function(path, fact.func_start)
+ if sid is not None:
+ loop_sinks.add(sid)
+ if not loop_sinks:
+ return {}
+
+ reach = reachable_to_sink(
+ loop_sinks,
+ 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:
+ # Gate on the loop owner up front — the precision lever and the
+ # cheapest possible filter.
+ if not fact.loop_call_targets or not ranker.is_hot(path, fact.func_start):
+ continue
+ hits = _quadratic_hits_for_function(path, fact, index, reach)
+ if hits:
+ out.setdefault(path, []).extend(hits)
+ return out
+
+
+def _quadratic_hits_for_function(
+ path: str,
+ fact: PerfFnFacts,
+ index: CallGraphIndex,
+ reach: dict[str, Any],
+) -> list[PerfHit]:
+ from ..complexity import 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.loop_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
+ # Skip the self-loop degenerate case: A's loop calls a helper whose
+ # only reached loop is A itself (recursion resolves back to a_sid).
+ if chain[-1] == a_sid:
+ continue
+ seen.add(target_name)
+ hits.append(
+ PerfHit(
+ kind=INTERPROC_QUAD_KIND,
+ line=call_line,
+ function=fact.function,
+ detail="",
+ func_start=fact.func_start,
+ path=(a_sid, *chain),
+ )
+ )
+ break
+ return hits
diff --git a/tests/unit/health/test_perf_interproc_quadratic.py b/tests/unit/health/test_perf_interproc_quadratic.py
new file mode 100644
index 000000000..1de58e949
--- /dev/null
+++ b/tests/unit/health/test_perf_interproc_quadratic.py
@@ -0,0 +1,219 @@
+"""Unit tests for the cross-function ``interprocedural_quadratic_loop`` machinery.
+
+A loop in function ``A`` calls a helper ``B`` that, within a few call hops, has
+its OWN data-dependent loop. The walker records each function's own loop
+(``PerfFnFacts.own_loop_line``) and ``collect_interprocedural_quadratic`` finds
+the cross-function pairs via the sink-agnostic reachability engine, centrality-
+gated on the loop owner.
+
+This validated at ~2% precision (see ``local-stash/performance-pillar/
+PROBE_FINDINGS.md``) so it is NOT wired into the engine and produces no finding.
+These tests lock the reusable infrastructure (the walker fact + the collector),
+which is kept for a future interprocedural-dataflow-gated detector.
+
+Grammar availability is best-effort (a missing grammar degrades to "no hits").
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.analysis.health.complexity import PerfFnFacts, walk_file
+from repowise.core.analysis.health.perf import (
+ PerfRanker,
+ collect_interprocedural_quadratic,
+)
+
+_KIND = "interprocedural_quadratic_loop"
+
+
+class _PF:
+ """Minimal stand-in for a ParsedFile (the pass 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 _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
+
+
+# ---------------------------------------------------------------------------
+# The walker records each function's own data-dependent loop as a fact.
+# ---------------------------------------------------------------------------
+
+
+def test_walker_records_own_loop_line():
+ src = "def inner(rows):\n for r in rows:\n use(r)\n"
+ fc = walk_file("t.py", "python", src.encode())
+ fact = {f.function: f for f in fc.perf_fn_facts}["inner"]
+ assert fact.own_loop_line == 2 # the ``for`` line
+
+
+def test_walker_skips_constant_loop_for_own_loop():
+ # A loop over a fixed literal / range is not data-dependent -> not a target.
+ src = "def inner():\n for r in range(10):\n use(r)\n"
+ fc = walk_file("t.py", "python", src.encode())
+ fact = {f.function: f for f in fc.perf_fn_facts}.get("inner")
+ assert fact is None or fact.own_loop_line == 0
+
+
+def test_walker_no_loop_no_own_loop_fact():
+ src = "def inner(x):\n return x + 1\n"
+ fc = walk_file("t.py", "python", src.encode())
+ fact = {f.function: f for f in fc.perf_fn_facts}.get("inner")
+ assert fact is None or fact.own_loop_line == 0
+
+
+# ---------------------------------------------------------------------------
+# Cross-function detection, end-to-end over a real walk + a resolved graph.
+# ---------------------------------------------------------------------------
+
+_QUAD_SRC = (
+ "def outer(items):\n"
+ " for it in items:\n"
+ " inner(it)\n" # loop-nested call to a looping helper
+ "def inner(x):\n"
+ " for y in x:\n"
+ " use(y)\n"
+)
+
+
+def _walked_quad(path="svc.py"):
+ pf = _PF(path)
+ fcx = walk_file(path, "python", _QUAD_SRC.encode())
+ # outer defined at line 1, inner at line 4 (1-indexed def lines).
+ graph = _fake_graph(
+ {f"{path}::outer": (path, 1, 3), f"{path}::inner": (path, 4, 6)},
+ [(f"{path}::outer", f"{path}::inner")],
+ )
+ return [(pf, fcx)], graph, pf
+
+
+def test_crossfn_quadratic_fires_in_a_churny_file():
+ walked, graph, _pf = _walked_quad()
+ ranker = PerfRanker(None, {"svc.py": {"is_hotspot": True}}) # churny -> hot
+ out = collect_interprocedural_quadratic(walked, graph, ranker)
+ hits = [h for hs in out.values() for h in hs]
+ assert len(hits) == 1
+ h = hits[0]
+ assert h.kind == _KIND
+ assert h.function == "outer"
+ assert h.path[0].endswith("::outer")
+ assert h.path[-1].endswith("::inner")
+
+
+def test_crossfn_quadratic_silent_without_a_hot_signal():
+ walked, graph, _pf = _walked_quad()
+ # No graph centrality, no git metadata -> nothing is hot -> no hits.
+ ranker = PerfRanker(None, {})
+ assert collect_interprocedural_quadratic(walked, graph, ranker) == {}
+
+
+def test_crossfn_quadratic_fires_for_a_central_loop_owner():
+ walked, _graph, _pf = _walked_quad()
+ # Give ``outer`` top-quintile caller count so it is central without churn.
+ g = _fake_graph(
+ {"svc.py::outer": ("svc.py", 1, 3), "svc.py::inner": ("svc.py", 4, 6)},
+ [("svc.py::outer", "svc.py::inner")],
+ )
+ 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::outer", edge_type="calls")
+ from repowise.core.analysis.health.perf import CallGraphIndex
+
+ index = CallGraphIndex(g)
+ ranker = PerfRanker(index, {})
+ out = collect_interprocedural_quadratic(walked, g, ranker, index=index)
+ hits = [h for hs in out.values() for h in hs]
+ assert len(hits) == 1
+ assert hits[0].function == "outer"
+
+
+def test_crossfn_quadratic_no_hit_when_helper_has_no_loop():
+ # ``inner`` does not loop -> not a reachability target -> no quadratic hit.
+ src = (
+ "def outer(items):\n"
+ " for it in items:\n"
+ " inner(it)\n"
+ "def inner(x):\n"
+ " return x + 1\n"
+ )
+ pf = _PF("svc.py")
+ fcx = walk_file("svc.py", "python", src.encode())
+ graph = _fake_graph(
+ {"svc.py::outer": ("svc.py", 1, 3), "svc.py::inner": ("svc.py", 4, 5)},
+ [("svc.py::outer", "svc.py::inner")],
+ )
+ ranker = PerfRanker(None, {"svc.py": {"is_hotspot": True}})
+ assert collect_interprocedural_quadratic([(pf, fcx)], graph, ranker) == {}
+
+
+def test_crossfn_quadratic_skips_self_recursion():
+ # ``outer`` loops and calls itself: the only reached loop is its own, so the
+ # self-loop degenerate case must not produce a hit.
+ symbols = {"svc.py::outer": ("svc.py", 1, 3)}
+ graph = _fake_graph(symbols, [("svc.py::outer", "svc.py::outer")])
+ pf = _PF("svc.py")
+ fcx = walk_file("svc.py", "python", b"def x():\n pass\n")
+ fcx.perf_fn_facts = [
+ PerfFnFacts(
+ function="outer",
+ func_start=1,
+ loop_call_targets=(("outer", 2),),
+ bare_sink_kind=None,
+ own_loop_line=2,
+ ),
+ ]
+ ranker = PerfRanker(None, {"svc.py": {"is_hotspot": True}})
+ assert collect_interprocedural_quadratic([(pf, fcx)], graph, ranker) == {}
+
+
+def test_crossfn_quadratic_no_graph_is_noop():
+ walked, _graph, _pf = _walked_quad()
+ ranker = PerfRanker(None, {"svc.py": {"is_hotspot": True}})
+ assert collect_interprocedural_quadratic(walked, None, ranker) == {}
+
+
+def test_collector_emits_its_own_kind():
+ walked, graph, _pf = _walked_quad()
+ ranker = PerfRanker(None, {"svc.py": {"is_hotspot": True}})
+ out = collect_interprocedural_quadratic(walked, graph, ranker)
+ hits = [h for hs in out.values() for h in hs]
+ assert hits and all(h.kind == _KIND for h in hits)
+
+
+def test_marker_is_not_registered_as_a_biomarker():
+ # Deliberately unwired: no biomarker consumes the kind and it is absent from
+ # the scoring tables, so it can never reach a finding or move any dimension.
+ from repowise.core.analysis.health.biomarkers.registry import registered_biomarkers
+ from repowise.core.analysis.health.scoring import dimensions_for
+
+ assert _KIND not in {b.name for b in registered_biomarkers()}
+ # Unlisted -> defaults to the historical single {"defect"}; never emitted.
+ assert dimensions_for(_KIND) == {"defect"}