Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

refactor(perf): give each opportunity rule one owner, and pin what identity means (#1974)

Raghav Chamadiya53521b223121
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 b47a540d1..1c94f5ab0 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/__init__.py
@@ -7,11 +7,19 @@ This package holds:
* the per-language perf :mod:`.dialects` (callee extraction + execution-sink
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;
+* the sink-agnostic bounded reachability engine (:mod:`.reachability`) 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`).
+ (:mod:`.ranking`) used as a centrality precision gate, and the
+ centrality-gated markers (:mod:`.gated`);
+* the causal read model that folds raw findings into ranked opportunities:
+ :mod:`.opportunities` is its public face, over :mod:`.facts` (typed evidence
+ read off a row), :mod:`.causal` (grouping and the versioned identity kernel),
+ :mod:`.actionability` (whether the evidence supports naming a change), and
+ :mod:`.opportunity_rank` (the ordering policy).
+
+Nothing here touches persistence or transport. Stored rows arrive through the
+same attribute adapter analyzer dataclasses do.
"""
from __future__ import annotations
diff --git a/packages/core/src/repowise/core/analysis/health/perf/actionability.py b/packages/core/src/repowise/core/analysis/health/perf/actionability.py
new file mode 100644
index 000000000..d87c4ba89
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/actionability.py
@@ -0,0 +1,123 @@
+"""Whether a group's evidence supports naming one safe change.
+
+Proven repetition is not proof that removing it is valid. Every gate returns
+``None`` rather than a weaker plan when it cannot prove its precondition,
+because a wrong plan costs more than a missing one.
+
+The confidence here is evidence confidence: how reliably the call path was
+resolved, not whether the change is safe. That is :attr:`PerformanceFix.safety`.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Literal
+
+FixSafety = Literal["proven", "advisory"]
+OpportunityConfidence = Literal["high", "medium", "low"]
+FixStrategy = Literal[
+ "parallelize_independent_awaits",
+ "replace_membership_collection",
+ "buffer_string_accumulation",
+ "hoist_loop_invariant_resource",
+ "batch_or_prefetch_io",
+ "shrink_lock_scope",
+]
+
+
+@dataclass(frozen=True, slots=True)
+class PerformanceFix:
+ strategy: FixStrategy
+ safety: FixSafety
+ rationale: str
+
+ def as_dict(self) -> dict[str, str]:
+ return {"strategy": self.strategy, "safety": self.safety, "rationale": self.rationale}
+
+
+def provenance_confidence(provenance: str) -> OpportunityConfidence:
+ """Product confidence label owned beside the provenance ranking policy."""
+ if provenance in {"call-site", "direct"}:
+ return "high"
+ if provenance == "reliable-edge":
+ return "medium"
+ return "low"
+
+
+def fix_for(
+ marker: str,
+ markers: tuple[str, ...],
+ boundary: str | None,
+ details: list[dict[str, Any]],
+ *,
+ cross_function: bool,
+ shared_suffix: tuple[str, ...],
+) -> PerformanceFix | None:
+ """The one strategy this group's evidence supports, or nothing.
+
+ Gate order is load-bearing: marker-specific proofs run before the generic
+ batching fallback, so a group that qualifies for a proven transformation is
+ never downgraded to an advisory one.
+ """
+ if marker == "serial_await_in_loop" and all(d.get("dataflow_verified") for d in details):
+ return PerformanceFix(
+ "parallelize_independent_awaits",
+ "proven",
+ "Dataflow proves that every observed loop carries no cross-iteration dependence.",
+ )
+ if marker == "membership_test_against_list_in_loop":
+ return PerformanceFix(
+ "replace_membership_collection",
+ "advisory",
+ "The collection is proven list-backed; element hashability and ordering/identity use still require validation.",
+ )
+ if marker == "string_concat_in_loop":
+ return PerformanceFix(
+ "buffer_string_accumulation",
+ "advisory",
+ "Repeated string accumulation is proven; intermediate accumulator observations still require validation.",
+ )
+ if set(markers) <= {"io_in_loop", "nested_loop_with_io"} and boundary in {
+ "db",
+ "network",
+ }:
+ if cross_function and len(shared_suffix) < 2:
+ # A generic sink shared by otherwise unrelated callers is evidence
+ # of repeated cost, not proof that editing it is one coherent
+ # intervention. Stay visible without claiming a batch plan.
+ return None
+ return PerformanceFix(
+ "batch_or_prefetch_io",
+ "advisory",
+ "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ )
+ if marker == "blocking_io_under_lock":
+ path_starts = {
+ path[0] for detail in details if (path := detail.get("path")) and isinstance(path, list)
+ }
+ if cross_function and len(path_starts) != 1:
+ return None
+ return PerformanceFix(
+ "shrink_lock_scope",
+ "advisory",
+ "I/O under the lock is proven, but shared-state ordering must be validated before moving it.",
+ )
+ if marker == "resource_construction_in_loop" and all(
+ d.get("resource_invariant") is True for d in details
+ ):
+ return PerformanceFix(
+ "hoist_loop_invariant_resource",
+ "proven",
+ "Dataflow proves construction arguments and lifetime are loop invariant.",
+ )
+ return None
+
+
+__all__ = [
+ "FixSafety",
+ "FixStrategy",
+ "OpportunityConfidence",
+ "PerformanceFix",
+ "fix_for",
+ "provenance_confidence",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/perf/causal.py b/packages/core/src/repowise/core/analysis/health/perf/causal.py
new file mode 100644
index 000000000..097731f75
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/causal.py
@@ -0,0 +1,172 @@
+"""Causal grouping and the versioned identity kernel.
+
+:func:`causal_key` decides what makes two observations the same cause, and its
+output is what gets hashed into the ``opportunity_id``. Grouping and identity
+are deliberately the same computation: an id that could disagree with its own
+group would be a join key nobody could trust.
+
+That id is persisted into every raw finding and every performance plan, and
+readers join on exact string equality, so the kernel's inputs are a contract.
+Adding a fact must not change them; changing them means bumping
+:data:`PERFORMANCE_MODEL_VERSION`.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from collections import defaultdict
+from typing import Any, Literal
+
+from repowise.core.test_paths import is_test_related_path
+
+from .facts import ObservationFacts, detail_map, is_performance, observation_facts
+
+PERFORMANCE_MODEL_VERSION = 1
+"""Version of the identity, grouping, actionability, and ranking semantics.
+
+Version 1 predates this constant, so it is deliberately not an input to
+:func:`stable_id`: embedding it would rewrite every persisted ``opportunity_id``
+and orphan every stored plan link for no semantic change. A later version may
+embed it, and must bump ``HEALTH_ANALYZER_VERSION`` with it.
+"""
+
+ExecutionContext = Literal["production", "tooling", "test"]
+
+CausalKey = tuple[Any, ...]
+
+_TOOLING_PARTS = frozenset(
+ {".github", "benchmarks", "build", "devtools", "scripts", "tooling", "tools"}
+)
+
+
+def execution_context(file_path: str) -> ExecutionContext:
+ """Where this code runs. An identity input, so it is classified once."""
+ if is_test_related_path(file_path):
+ return "test"
+ parts = {part.lower() for part in file_path.replace("\\", "/").split("/")}
+ if parts & _TOOLING_PARTS or "/cli/" in f"/{file_path.lower().replace(chr(92), '/')}/":
+ return "tooling"
+ return "production"
+
+
+def cost_shape(marker: str) -> str:
+ """Compatibility family for observations that may share one intervention."""
+ if marker in {"io_in_loop", "nested_loop_with_io"}:
+ return "repeated_io"
+ return marker
+
+
+def causal_key(facts: ObservationFacts) -> CausalKey:
+ """The v1 identity kernel.
+
+ The two branches are deliberately asymmetric. A cross-function cause is
+ named by its terminal sink, so a new caller adds evidence without renaming
+ the cause; a same-function one has no shared sink and is named by its own
+ location.
+
+ Everything outside these tuples is display or derived data and stays out:
+ prose, line ends, storage ids, rank factors, confidence, reachability, and
+ provenance.
+ """
+ context = execution_context(facts.file_path)
+ if facts.cross_function and facts.path:
+ return (
+ "cross-function",
+ context,
+ cost_shape(facts.marker),
+ facts.boundary_kind,
+ facts.path[-1],
+ )
+ return (
+ "local",
+ context,
+ facts.marker,
+ facts.boundary_kind,
+ facts.file_path,
+ facts.function_name,
+ facts.line_start,
+ )
+
+
+def stable_id(key: CausalKey) -> str:
+ payload = json.dumps(key, separators=(",", ":"), ensure_ascii=True)
+ return "perf_" + hashlib.sha256(payload.encode("utf-8")).hexdigest()[:20]
+
+
+def key_context(key: CausalKey) -> ExecutionContext:
+ """Both kernel branches carry the execution context in the same slot."""
+ return key[1]
+
+
+def key_boundary(key: CausalKey) -> str | None:
+ """Both kernel branches carry the boundary kind in the same slot."""
+ return key[3]
+
+
+def key_is_cross_function(key: CausalKey) -> bool:
+ return key[0] == "cross-function"
+
+
+def opportunity_id_for_finding(row: Any) -> str:
+ return stable_id(causal_key(observation_facts(row)))
+
+
+def link_performance_findings(findings: list[Any]) -> None:
+ """Attach the causal id to analyzer findings before they are persisted.
+
+ Runs before opportunities are built, so a finding carries the id its
+ opportunity will publish. Mutates in place: the caller persists these same
+ objects.
+ """
+ for finding in findings:
+ if not is_performance(finding):
+ continue
+ details = detail_map(finding)
+ details["opportunity_id"] = opportunity_id_for_finding(finding)
+
+
+def group_observations(rows: list[Any]) -> dict[CausalKey, list[ObservationFacts]]:
+ """Fold raw rows into causal groups, each in deterministic evidence order."""
+ groups: dict[CausalKey, list[ObservationFacts]] = defaultdict(list)
+ for row in rows:
+ if is_performance(row):
+ facts = observation_facts(row)
+ groups[causal_key(facts)].append(facts)
+ for members in groups.values():
+ members.sort(key=lambda facts: facts.sort_key)
+ return groups
+
+
+def shared_path_suffix(paths: list[tuple[str, ...]]) -> tuple[str, ...]:
+ """The longest call path every observation in a group ends with.
+
+ Its length is the evidence that one edit could address all of them: a
+ suffix of one node is a shared destination, not a shared cause.
+ """
+ if not paths:
+ return ()
+ common: list[str] = []
+ for nodes in zip(*(reversed(path) for path in paths), strict=False):
+ if len(set(nodes)) != 1:
+ break
+ common.append(nodes[0])
+ return tuple(reversed(common))
+
+
+__all__ = [
+ "PERFORMANCE_MODEL_VERSION",
+ "CausalKey",
+ "ExecutionContext",
+ "causal_key",
+ "cost_shape",
+ "execution_context",
+ "group_observations",
+ "key_boundary",
+ "key_context",
+ "key_is_cross_function",
+ "link_performance_findings",
+ "opportunity_id_for_finding",
+ "shared_path_suffix",
+ "stable_id",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/perf/crossfn.py b/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
index 8660076ff..63b63d8e8 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/crossfn.py
@@ -15,7 +15,7 @@ This module is the bridge between three things that already exist:
(non-loop) sink;
* the resolved symbol-level ``calls`` graph the engine already has (file +
symbol nodes, ``calls`` edges between ``path::name`` symbol ids);
- * the sink-agnostic :mod:`.reachability` walk (Primitive 3).
+ * the sink-agnostic :mod:`.reachability` walk.
It runs **once per analyze()** and is ``O(V + E)`` bounded by ``max_depth``:
one pass to index symbol nodes, one pass to extract ``calls`` adjacency, one
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 cf7abbbf9..e1873b583 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
@@ -237,7 +237,7 @@ class BasePerfDialect:
The precision lever for the nested-loop markers: only when the OUTER
loop multiplies over a collection is an inner I/O sink genuinely O(n*m).
A pagination ``while`` cursor wrapping an inner ``for ... of chunk`` is
- ``io_in_loop``, not a nested round-trip explosion (Phase-7c TS corpus).
+ ``io_in_loop``, not a nested round-trip explosion.
Default ``True`` — a language that does not distinguish keeps today's
behavior byte-for-byte; TS/JS overrides this to exclude ``while`` /
C-style ``for`` cursors.
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..6d8477524 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,7 +178,7 @@ class CSharpPerfDialect(BasePerfDialect):
"resource_construction_in_loop",
"lock_in_loop",
"serial_await_in_loop",
- # Phase 7b — centrality-gated / nesting-confidence markers + the
+ # 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",
@@ -261,8 +261,8 @@ class CSharpPerfDialect(BasePerfDialect):
return None
# ``.Result`` collides hard with the ubiquitous Result-pattern
# (Ardalis.Result / FluentResults / custom ``Result<T>`` DTOs), which is
- # NOT a ``Task`` and does not block. Two precision-first guards (Phase-7c
- # C# corpus: 10/12 FPs were ``Ardalis.Result.ResultStatus.X``, 1 a write):
+ # NOT a ``Task`` and does not block. Two precision-first guards (on a
+ # C# corpus, 10/12 FPs were ``Ardalis.Result.ResultStatus.X``, 1 a write):
# NOTE: py-tree-sitter returns fresh Node wrappers per call, so compare
# by byte span (``_same_span``), never identity.
parent = node.parent
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 d619615e1..c015aa72a 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
@@ -47,7 +47,7 @@ GO_SQL_METHODS: frozenset[str] = frozenset(
# ``Scan`` is deliberately EXCLUDED: ``*sql.Rows.Scan`` (decoding an
# already-fetched cursor row inside ``for rows.Next()``) is far more common than
# GORM's ``db.Scan`` finisher and is NOT a round-trip — it FP'd ``io_in_loop``
-# on every cursor-read loop (Phase-7c syft corpus). Dropping it costs ~0
+# on every cursor-read loop, measured across a Go corpus. Dropping it costs ~0
# measured recall (no corpus GORM-``Scan``-in-loop) and removes the FP class.
GO_GORM_METHODS: frozenset[str] = frozenset(
{
@@ -110,11 +110,11 @@ class GoPerfDialect(BasePerfDialect):
"regex_compile_in_loop",
"resource_construction_in_loop",
"lock_in_loop",
- # Phase 7b — centrality-gated / nesting-confidence markers.
+ # Centrality-gated / nesting-confidence markers.
"nested_loop_with_io",
"nested_loop_quadratic",
"hot_path_sync_io",
- # Phase 7d — Go-specific spawn explosion.
+ # Go-specific spawn explosion.
"goroutine_in_unbounded_loop",
}
)
@@ -192,7 +192,7 @@ class GoPerfDialect(BasePerfDialect):
# Only a *string-literal* pattern is unambiguously hoistable: a
# dynamic argument (``regexp.MustCompile(pat)`` / a concatenation with
# a per-iteration variable) may legitimately vary each iteration and
- # cannot be lifted out of the loop. Phase-7c Go corpus: the 10
+ # cannot be lifted out of the loop. Measured on a Go corpus: the 10
# dynamic-arg cases were all UNSURE; gating on a literal removes them.
return "regex_compile_in_loop"
if (root, method) in GO_RESOURCE_CTORS:
@@ -375,7 +375,7 @@ class GoPerfDialect(BasePerfDialect):
def _nearest_for_is_range(node: Node) -> bool:
"""True if the nearest enclosing ``for`` loop ranges over a COLLECTION.
- Phase-7d gate: a single-variable ``for i := range n`` (Go 1.22
+ Gate: a single-variable ``for i := range n`` (Go 1.22
range-over-int, or a count constant) is a bounded count loop, NOT a
per-element fan-out — both 0%-precision FPs were ``for i := range
<const>`` in tests. The two-variable ``for k, v := range coll`` form is
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..712bd4ab1 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,7 +108,7 @@ class JavaPerfDialect(BasePerfDialect):
"regex_compile_in_loop",
"resource_construction_in_loop",
"lock_in_loop",
- # Phase 7b — centrality-gated / nesting-confidence markers + the
+ # Centrality-gated / nesting-confidence markers + the
# block-scoped lock→I/O case (``synchronized`` is a held region).
"nested_loop_with_io",
"nested_loop_quadratic",
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 02b9ad34b..ab98d10fe 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
@@ -168,11 +168,11 @@ class PythonPerfDialect(BasePerfDialect):
"lock_in_loop",
"serial_await_in_loop",
"membership_test_against_list_in_loop",
- # Phase 7b — centrality-gated / nesting-confidence markers.
+ # Centrality-gated / nesting-confidence markers.
"nested_loop_with_io",
"nested_loop_quadratic",
"hot_path_sync_io",
- # Phase 7d — Python-specific quadratic anti-patterns.
+ # Python-specific quadratic anti-patterns.
"list_insert_zero_in_loop",
"pd_concat_in_loop",
# Header-call marker: the slow iterable IS the loop driver.
@@ -213,7 +213,7 @@ class PythonPerfDialect(BasePerfDialect):
# yield, never an I/O round-trip — but ``await asyncio.sleep(...)`` would
# otherwise hit the awaited-network arm below when ``asyncio`` is
# import-classified as network, FP-ing ``io_in_loop`` / ``serial_await``
- # on every backoff/poll loop (Phase-7c headroom corpus). No legitimate
+ # on every backoff/poll loop, measured across a Python corpus. No legitimate
# execution sink is named ``sleep``, so excluding it costs no recall.
if method == "sleep":
return None
@@ -327,7 +327,7 @@ class PythonPerfDialect(BasePerfDialect):
``buf = base[:N]; ... buf += part`` inside a loop builds a fresh, bounded
string per iteration (not the O(n^2) cross-iteration accumulation the
- marker targets), so it is a false positive. Phase-7c headroom corpus:
+ marker targets), so it is a false positive. Measured on a Python corpus:
the reset-per-iteration shape was the dominant FP class (Py 77.8%). When
the same name is plainly re-assigned inside an enclosing loop body, the
``+=`` cannot accumulate across iterations, so do not flag it.
@@ -403,7 +403,7 @@ class PythonPerfDialect(BasePerfDialect):
# the front-insertion anti-pattern) AND to a list that is not re-created
# each iteration (a fresh ``buf = [...]; buf.insert(0, x)`` is bounded,
# not O(n^2) — the same reset-per-iteration FP class as string_concat;
- # Phase-7d headroom corpus).
+ # measured on a Python corpus).
# ``collections.deque.insert(0, x)`` is O(1) front-insertion by design (it
# is the deque's own ``appendleft`` machinery), so exclude a receiver
# provably constructed via ``deque()`` / ``collections.deque(...)``.
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..a36769977 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
@@ -19,8 +19,8 @@ Flagship: a ``sqlx`` query or a ``std::fs`` / ``reqwest`` round-trip inside a
Rust has no compile-optimization hazard around ``String`` building — ``push_str``
/ ``+=`` on a ``String`` are amortized O(1) (the buffer grows geometrically), so
-``string_concat_in_loop`` is deliberately NOT in :attr:`markers` (it would be a
-guaranteed-FP marker — the language-scope rule in ``MARKER_BACKLOG.md``).
+``string_concat_in_loop`` is deliberately NOT in :attr:`markers`: it would be a
+guaranteed false positive, which is why markers are scoped per language.
The per-grammar seam: Rust spells free calls (``foo()``), method calls
(``x.fetch_all()`` -> ``call_expression`` over a ``field_expression``) and
@@ -131,7 +131,7 @@ class RustPerfDialect(BasePerfDialect):
"regex_compile_in_loop",
"resource_construction_in_loop",
"serial_await_in_loop",
- # Phase 7b — centrality-gated / nesting-confidence markers (parity).
+ # Centrality-gated / nesting-confidence markers (parity).
"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 6f8964535..c86cf6280 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,11 +91,11 @@ class TsJsPerfDialect(BasePerfDialect):
"resource_construction_in_loop",
"serial_await_in_loop",
"membership_test_against_list_in_loop",
- # Phase 7b — centrality-gated / nesting-confidence markers.
+ # Centrality-gated / nesting-confidence markers.
"nested_loop_with_io",
"nested_loop_quadratic",
"hot_path_sync_io",
- # Phase 7d — JS/TS-specific anti-patterns.
+ # JS/TS-specific anti-patterns.
"json_parse_in_loop",
"array_spread_in_reduce",
}
@@ -181,7 +181,7 @@ class TsJsPerfDialect(BasePerfDialect):
if method == "includes" and root in list_names:
return "membership_test_against_list_in_loop"
# ``JSON.parse(JSON.stringify(x))`` deep-clone in a loop is the canonical
- # waste (use ``structuredClone``). Phase-7d gate: a BARE ``JSON.parse`` /
+ # waste (use ``structuredClone``). Gate: a BARE ``JSON.parse`` /
# ``JSON.stringify`` per iteration was 0% precision (30/30 were
# format-conversion loops serializing a DISTINCT payload each pass —
# necessary work, not waste), so the marker is restricted to the
diff --git a/packages/core/src/repowise/core/analysis/health/perf/facts.py b/packages/core/src/repowise/core/analysis/health/perf/facts.py
new file mode 100644
index 000000000..63e769525
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/facts.py
@@ -0,0 +1,143 @@
+"""Typed, language-neutral facts read off one raw performance finding.
+
+Everything downstream works on :class:`ObservationFacts`, never on a row, so
+grouping, actionability, and ranking stay free of the shape a finding arrives
+in: analyzer dataclass, ORM row, or plain dict all reduce here.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from typing import Any
+
+
+def field(row: Any, name: str, default: Any = None) -> Any:
+ """Read one attribute from a dataclass, an ORM row, or a dict."""
+ if isinstance(row, dict):
+ return row.get(name, default)
+ return getattr(row, name, default)
+
+
+def detail_map(row: Any) -> dict[str, Any]:
+ """The finding's open ``details`` payload, whether stored or in memory."""
+ value = field(row, "details", None)
+ if isinstance(value, dict):
+ return value
+ raw = field(row, "details_json", None)
+ if isinstance(raw, str):
+ try:
+ loaded = json.loads(raw)
+ return loaded if isinstance(loaded, dict) else {}
+ except (TypeError, ValueError):
+ return {}
+ return {}
+
+
+def is_performance(row: Any) -> bool:
+ return field(row, "dimension", None) == "performance"
+
+
+@dataclass(frozen=True, slots=True)
+class ObservationFacts:
+ """One detector-supported cost shape at one location.
+
+ ``details`` stays verbatim: the actionability gates read marker-specific
+ proof keys off it, and closing it into typed fields would drop the keys a
+ new marker adds.
+ """
+
+ finding_id: str
+ file_path: str
+ function_name: Any
+ line_start: Any
+ line_end: Any
+ reason: str
+ raw_marker: Any
+ boundary_kind: str | None
+ path: tuple[str, ...]
+ has_path: bool
+ cross_function: bool
+ resolution_basis: Any
+ reliable_entry_reachability: Any
+ details: dict[str, Any]
+
+ @property
+ def marker(self) -> str:
+ """The identity and ranking view of the biomarker type."""
+ return str(self.raw_marker)
+
+ @property
+ def evidence_marker(self) -> str:
+ """The evidence-row view: a falsy marker renders empty, not ``"None"``."""
+ return str(self.raw_marker or "")
+
+ @property
+ def provenance(self) -> str:
+ return str(self.resolution_basis)
+
+ @property
+ def site(self) -> tuple[str, Any, Any]:
+ return (self.file_path, self.line_start, self.function_name)
+
+ @property
+ def sort_key(self) -> tuple[str, Any, str]:
+ """Deterministic within-group evidence order."""
+ return (self.file_path, self.line_start or 0, str(self.function_name))
+
+
+def observation_facts(row: Any) -> ObservationFacts:
+ details = detail_map(row)
+ raw_path = details.get("path", ())
+ return ObservationFacts(
+ finding_id=str(field(row, "id", "") or ""),
+ file_path=str(field(row, "file_path", "")),
+ function_name=field(row, "function_name", None),
+ line_start=field(row, "line_start", None),
+ line_end=field(row, "line_end", None),
+ reason=str(field(row, "reason", "") or ""),
+ raw_marker=field(row, "biomarker_type", ""),
+ boundary_kind=details.get("boundary_kind") or None,
+ path=tuple(str(node) for node in raw_path if isinstance(node, str)),
+ # Whether a path was offered, which is not whether any of it survived
+ # the string filter above. Both drive real branches.
+ has_path=bool(raw_path),
+ cross_function=bool(details.get("cross_function")),
+ resolution_basis=details.get("resolution_basis", "direct"),
+ reliable_entry_reachability=details.get("reliable_entry_reachability"),
+ details=details,
+ )
+
+
+def performance_facts(rows: list[Any]) -> list[ObservationFacts]:
+ return [observation_facts(row) for row in rows if is_performance(row)]
+
+
+def evidence_row(facts: ObservationFacts) -> dict[str, Any]:
+ """One public evidence entry.
+
+ ``finding_id`` is the storage row id, not a content hash: empty before
+ persistence, a fresh UUID after. It points within one index only.
+ """
+ return {
+ "finding_id": facts.finding_id,
+ "file_path": facts.file_path,
+ "biomarker_type": facts.evidence_marker,
+ "function_name": facts.function_name,
+ "line_start": facts.line_start,
+ "line_end": facts.line_end,
+ "reason": facts.reason,
+ "path": list(facts.details.get("path", ())),
+ "provenance": facts.resolution_basis,
+ }
+
+
+__all__ = [
+ "ObservationFacts",
+ "detail_map",
+ "evidence_row",
+ "field",
+ "is_performance",
+ "observation_facts",
+ "performance_facts",
+]
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 5e2203fd5..7bdb73374 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/gated.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/gated.py
@@ -1,17 +1,16 @@
-"""Centrality-gated Phase-7b markers (the differentiator).
+"""Centrality-gated markers.
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):
+the :class:`~.ranking.PerfRanker` and the sink-agnostic reachability engine:
* :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.
+ everywhere; the gate is what makes the O(n^2) marker precise enough to
+ emit. 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,
diff --git a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
index 2bd1672f2..feb68875e 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py
@@ -7,8 +7,8 @@ ordinary computation?* That decomposes into two pieces:
1. **Dependency classification** (this module) — which imported names in a file
originate from an I/O library, and of what kind. Reuses the shared
:func:`...ingestion.external_systems.io_kind.classify_io_kind` table
- (Primitive 1) rather than a perf-private list, so the same maintained
- classification powers C4 typing, the perf pass, and a future security layer.
+ rather than a perf-private list, so the same maintained classification
+ powers C4 typing, the perf pass, and a future security layer.
:func:`collect_io_names` walks a file's import nodes and binds each imported
identifier to its ``io_kind``. This step is **language-agnostic** — an import
statement is a quoted module source (TS) or a dotted path (Python/Java/...);
diff --git a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
index ffdbb36d7..93355f689 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
@@ -5,58 +5,43 @@ them once into bounded, ranked opportunities so repeated caller paths to one
sink lead an agent to one intervention. It is deliberately persistence-
agnostic: analyzer dataclasses, ORM rows, and lightweight SQL rows are accepted
through the same attribute adapter.
+
+This file is the public face of that model. The rules behind it live in four
+modules with one owner each: :mod:`.facts` reads a row, :mod:`.causal` decides
+what shares a cause and what that cause is called, :mod:`.actionability`
+decides whether the evidence supports naming a change, and
+:mod:`.opportunity_rank` decides the order. The orchestration below holds no
+policy of its own.
"""
from __future__ import annotations
-import hashlib
-import json
-from collections import defaultdict
from dataclasses import dataclass
-from math import log2
-from typing import Any, Literal
-
-from repowise.core.test_paths import is_test_related_path
-
-ExecutionContext = Literal["production", "tooling", "test"]
-FixSafety = Literal["proven", "advisory"]
-OpportunityConfidence = Literal["high", "medium", "low"]
-FixStrategy = Literal[
- "parallelize_independent_awaits",
- "replace_membership_collection",
- "buffer_string_accumulation",
- "hoist_loop_invariant_resource",
- "batch_or_prefetch_io",
- "shrink_lock_scope",
-]
-
-_TOOLING_PARTS = frozenset(
- {".github", "benchmarks", "build", "devtools", "scripts", "tooling", "tools"}
+from typing import Any
+
+from .actionability import (
+ FixSafety,
+ FixStrategy,
+ OpportunityConfidence,
+ PerformanceFix,
+ fix_for,
+ provenance_confidence,
)
-_BOUNDARY_POINTS = {"subprocess": 5, "network": 4, "db": 4, "lock": 3, "filesystem": 2}
-_MULTIPLIER_POINTS = {
- "nested_loop_with_io": 6,
- "nested_loop_quadratic": 6,
- "blocking_io_under_lock": 5,
- "io_in_loop": 4,
- "serial_await_in_loop": 4,
- "resource_construction_in_loop": 4,
- "membership_test_against_list_in_loop": 3,
- "string_concat_in_loop": 3,
- "lock_in_loop": 2,
-}
-_CONTEXT_POINTS = {"production": 3, "tooling": 2, "test": 1}
-_PROVENANCE_POINTS = {"call-site": 3, "direct": 3, "reliable-edge": 2, "name-fallback": 0}
-
-
-@dataclass(frozen=True, slots=True)
-class PerformanceFix:
- strategy: FixStrategy
- safety: FixSafety
- rationale: str
-
- def as_dict(self) -> dict[str, str]:
- return {"strategy": self.strategy, "safety": self.safety, "rationale": self.rationale}
+from .causal import (
+ PERFORMANCE_MODEL_VERSION,
+ ExecutionContext,
+ execution_context,
+ group_observations,
+ key_boundary,
+ key_context,
+ key_is_cross_function,
+ link_performance_findings,
+ opportunity_id_for_finding,
+ shared_path_suffix,
+ stable_id,
+)
+from .facts import evidence_row
+from .opportunity_rank import dominant_marker, rank_factors, rank_sort_key, weakest_provenance
@dataclass(frozen=True, slots=True)
@@ -105,241 +90,43 @@ class PerformanceOpportunity:
}
-def _attr(row: Any, name: str, default: Any = None) -> Any:
- if isinstance(row, dict):
- return row.get(name, default)
- return getattr(row, name, default)
-
-
-def _details(row: Any) -> dict[str, Any]:
- value = _attr(row, "details", None)
- if isinstance(value, dict):
- return value
- raw = _attr(row, "details_json", None)
- if isinstance(raw, str):
- try:
- loaded = json.loads(raw)
- return loaded if isinstance(loaded, dict) else {}
- except (TypeError, ValueError):
- return {}
- return {}
-
-
-def execution_context(file_path: str) -> ExecutionContext:
- if is_test_related_path(file_path):
- return "test"
- parts = {part.lower() for part in file_path.replace("\\", "/").split("/")}
- if parts & _TOOLING_PARTS or "/cli/" in f"/{file_path.lower().replace(chr(92), '/')}/":
- return "tooling"
- return "production"
-
-
-def _stable_id(key: tuple[Any, ...]) -> str:
- payload = json.dumps(key, separators=(",", ":"), ensure_ascii=True)
- return "perf_" + hashlib.sha256(payload.encode("utf-8")).hexdigest()[:20]
-
-
-def _cost_shape(marker: str) -> str:
- """Compatibility family for observations that may share one intervention."""
- if marker in {"io_in_loop", "nested_loop_with_io"}:
- return "repeated_io"
- return marker
-
-
-def _causal_key(row: Any) -> tuple[Any, ...]:
- details = _details(row)
- marker = str(_attr(row, "biomarker_type", ""))
- file_path = str(_attr(row, "file_path", ""))
- context = execution_context(file_path)
- path = tuple(str(node) for node in details.get("path", ()) if isinstance(node, str))
- boundary = details.get("boundary_kind") or None
- if details.get("cross_function") and path:
- # Membership is immutable under caller churn: a new caller changes the
- # evidence and common suffix, never the identity of the shared cause.
- return ("cross-function", context, _cost_shape(marker), boundary, path[-1])
- return (
- "local",
- context,
- marker,
- boundary,
- file_path,
- _attr(row, "function_name", None),
- _attr(row, "line_start", None),
- )
-
-
-def opportunity_id_for_finding(row: Any) -> str:
- return _stable_id(_causal_key(row))
-
-
-def link_performance_findings(findings: list[Any]) -> None:
- """Attach the causal id to analyzer findings before they are persisted."""
- for finding in findings:
- if _attr(finding, "dimension", None) != "performance":
- continue
- details = _details(finding)
- details["opportunity_id"] = opportunity_id_for_finding(finding)
-
-
-def _shared_suffix(paths: list[tuple[str, ...]]) -> tuple[str, ...]:
- if not paths:
- return ()
- common: list[str] = []
- for nodes in zip(*(reversed(path) for path in paths), strict=False):
- if len(set(nodes)) != 1:
- break
- common.append(nodes[0])
- return tuple(reversed(common))
-
-
-def _evidence(row: Any, details: dict[str, Any]) -> dict[str, Any]:
- return {
- "finding_id": str(_attr(row, "id", "") or ""),
- "file_path": str(_attr(row, "file_path", "")),
- "biomarker_type": str(_attr(row, "biomarker_type", "") or ""),
- "function_name": _attr(row, "function_name", None),
- "line_start": _attr(row, "line_start", None),
- "line_end": _attr(row, "line_end", None),
- "reason": str(_attr(row, "reason", "") or ""),
- "path": list(details.get("path", ())),
- "provenance": details.get("resolution_basis", "direct"),
- }
-
-
-def provenance_confidence(provenance: str) -> OpportunityConfidence:
- """Product confidence label owned beside the provenance ranking policy."""
- if provenance in {"call-site", "direct"}:
- return "high"
- if provenance == "reliable-edge":
- return "medium"
- return "low"
-
-
-def _fix_for(
- marker: str,
- markers: tuple[str, ...],
- boundary: str | None,
- details: list[dict[str, Any]],
- *,
- cross_function: bool,
- shared_suffix: tuple[str, ...],
-) -> PerformanceFix | None:
- if marker == "serial_await_in_loop" and all(d.get("dataflow_verified") for d in details):
- return PerformanceFix(
- "parallelize_independent_awaits",
- "proven",
- "Dataflow proves that every observed loop carries no cross-iteration dependence.",
- )
- if marker == "membership_test_against_list_in_loop":
- return PerformanceFix(
- "replace_membership_collection",
- "advisory",
- "The collection is proven list-backed; element hashability and ordering/identity use still require validation.",
- )
- if marker == "string_concat_in_loop":
- return PerformanceFix(
- "buffer_string_accumulation",
- "advisory",
- "Repeated string accumulation is proven; intermediate accumulator observations still require validation.",
- )
- if set(markers) <= {"io_in_loop", "nested_loop_with_io"} and boundary in {
- "db",
- "network",
- }:
- if cross_function and len(shared_suffix) < 2:
- # A generic terminal resource/API shared by otherwise unrelated
- # callers (for example ``get_session``) is evidence of repeated
- # cost, but not proof that editing that sink is one coherent
- # intervention. Keep the opportunity visible without claiming a
- # batch plan.
- return None
- return PerformanceFix(
- "batch_or_prefetch_io",
- "advisory",
- "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
- )
- if marker == "blocking_io_under_lock":
- path_starts = {
- path[0] for detail in details if (path := detail.get("path")) and isinstance(path, list)
- }
- if cross_function and len(path_starts) != 1:
- return None
- return PerformanceFix(
- "shrink_lock_scope",
- "advisory",
- "I/O under the lock is proven, but shared-state ordering must be validated before moving it.",
- )
- if marker == "resource_construction_in_loop" and all(
- d.get("resource_invariant") is True for d in details
- ):
- return PerformanceFix(
- "hoist_loop_invariant_resource",
- "proven",
- "Dataflow proves construction arguments and lifetime are loop invariant.",
- )
- return None
+def _reachability(values: set[Any]) -> bool | None:
+ """One reachable caller makes the group reachable; unknown outranks False."""
+ if True in values:
+ return True
+ return False if values == {False} else None
def build_performance_opportunities(
findings: list[Any], *, evidence_limit: int = 8
) -> list[PerformanceOpportunity]:
"""Group and rank performance rows in one deterministic pass."""
- groups: dict[tuple[Any, ...], list[Any]] = defaultdict(list)
- for row in findings:
- if _attr(row, "dimension", None) == "performance":
- groups[_causal_key(row)].append(row)
-
- opportunities: list[PerformanceOpportunity] = []
cap = max(0, evidence_limit)
- for key, rows in groups.items():
- rows.sort(
- key=lambda row: (
- str(_attr(row, "file_path", "")),
- _attr(row, "line_start", None) or 0,
- str(_attr(row, "function_name", "")),
- )
- )
- detail_rows = [_details(row) for row in rows]
- paths = [
- tuple(str(node) for node in details.get("path", ()) if isinstance(node, str))
- for details in detail_rows
- if details.get("path")
- ]
- suffix = _shared_suffix(paths)
- markers = tuple(sorted({str(_attr(row, "biomarker_type", "")) for row in rows}))
- marker = min(markers, key=lambda value: (-_MULTIPLIER_POINTS.get(value, 1), value))
- boundary = detail_rows[0].get("boundary_kind") or None
- context = execution_context(str(_attr(rows[0], "file_path", "")))
- sites = {
- (
- str(_attr(row, "file_path", "")),
- _attr(row, "line_start", None),
- _attr(row, "function_name", None),
- )
- for row in rows
- }
- files = {site[0] for site in sites}
- reach_values = {d.get("reliable_entry_reachability") for d in detail_rows}
- reachable: bool | None = (
- True if True in reach_values else (False if reach_values == {False} else None)
- )
- provenances = {str(d.get("resolution_basis", "direct")) for d in detail_rows}
- provenance = min(provenances, key=lambda value: (_PROVENANCE_POINTS.get(value, 0), value))
- factors = {
- "multiplier_shape": _MULTIPLIER_POINTS.get(marker, 1),
- "boundary_kind": _BOUNDARY_POINTS.get(boundary or "", 0),
- "execution_context": _CONTEXT_POINTS[context],
- "entry_reachability": 3 if reachable is True else 0,
- "affected_call_sites": min(8, int(log2(len(sites) + 1) * 2)),
- "provenance": _PROVENANCE_POINTS.get(provenance, 0),
- }
- evidence = tuple(
- _evidence(row, details)
- for row, details in zip(rows[:cap], detail_rows[:cap], strict=True)
+ opportunities: list[PerformanceOpportunity] = []
+ for key, members in group_observations(findings).items():
+ # Context and boundary are kernel inputs, so the group already agrees on
+ # them by construction. Reading them off the key keeps one owner for the
+ # classification instead of reclassifying a representative row.
+ context = key_context(key)
+ boundary = key_boundary(key)
+ paths = [facts.path for facts in members if facts.has_path]
+ suffix = shared_path_suffix(paths)
+ markers = tuple(sorted({facts.marker for facts in members}))
+ marker = dominant_marker(markers)
+ sites = {facts.site for facts in members}
+ provenance = weakest_provenance({facts.provenance for facts in members})
+ reachable = _reachability({facts.reliable_entry_reachability for facts in members})
+ factors = rank_factors(
+ marker=marker,
+ boundary=boundary,
+ context=context,
+ reachable=reachable,
+ site_count=len(sites),
+ provenance=provenance,
)
opportunities.append(
PerformanceOpportunity(
- opportunity_id=_stable_id(key),
+ opportunity_id=stable_id(key),
biomarker_type=marker,
biomarker_types=markers,
boundary_kind=boundary,
@@ -348,36 +135,31 @@ def build_performance_opportunities(
shared_path_suffix=suffix,
intervention_symbol=suffix[0] if suffix else None,
affected_call_sites_total=len(sites),
- affected_files_total=len(files),
- observations_total=len(rows),
- evidence=evidence,
- evidence_truncated=len(rows) > cap,
+ affected_files_total=len({site[0] for site in sites}),
+ observations_total=len(members),
+ evidence=tuple(evidence_row(facts) for facts in members[:cap]),
+ evidence_truncated=len(members) > cap,
reliable_entry_reachability=reachable,
provenance=provenance,
confidence=provenance_confidence(provenance),
rank_score=sum(factors.values()),
rank_factors=factors,
- fix=_fix_for(
+ fix=fix_for(
marker,
markers,
boundary,
- detail_rows,
- cross_function=key[0] == "cross-function",
+ [facts.details for facts in members],
+ cross_function=key_is_cross_function(key),
shared_suffix=suffix,
),
)
)
- opportunities.sort(
- key=lambda item: (
- -item.rank_score,
- -item.affected_call_sites_total,
- item.opportunity_id,
- )
- )
+ opportunities.sort(key=rank_sort_key)
return opportunities
__all__ = [
+ "PERFORMANCE_MODEL_VERSION",
"FixSafety",
"FixStrategy",
"PerformanceFix",
diff --git a/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py b/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py
new file mode 100644
index 000000000..d28a5ed89
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py
@@ -0,0 +1,82 @@
+"""Ordering policy: the weight tables and the total order over opportunities.
+
+Nothing here is a score in the health sense. No value produced by this module
+is blended into ``performance_score`` or any other dimension; it is an ordering
+key whose weights are frozen policy, not fitted parameters.
+"""
+
+from __future__ import annotations
+
+from math import log2
+from typing import Any
+
+BOUNDARY_POINTS = {"subprocess": 5, "network": 4, "db": 4, "lock": 3, "filesystem": 2}
+MULTIPLIER_POINTS = {
+ "nested_loop_with_io": 6,
+ "nested_loop_quadratic": 6,
+ "blocking_io_under_lock": 5,
+ "io_in_loop": 4,
+ "serial_await_in_loop": 4,
+ "resource_construction_in_loop": 4,
+ "membership_test_against_list_in_loop": 3,
+ "string_concat_in_loop": 3,
+ "lock_in_loop": 2,
+}
+CONTEXT_POINTS = {"production": 3, "tooling": 2, "test": 1}
+PROVENANCE_POINTS = {"call-site": 3, "direct": 3, "reliable-edge": 2, "name-fallback": 0}
+
+
+def dominant_marker(markers: tuple[str, ...]) -> str:
+ """The strongest cost shape in a group, ties broken by name."""
+ return min(markers, key=lambda value: (-MULTIPLIER_POINTS.get(value, 1), value))
+
+
+def weakest_provenance(provenances: set[str]) -> str:
+ """The least reliable resolution in a group, ties broken by name.
+
+ A group is only as trustworthy as its worst edge, so this is a ``min`` on
+ points where :func:`dominant_marker` is a ``min`` on negated points. They
+ read alike and mean the opposite; that is intentional.
+ """
+ return min(provenances, key=lambda value: (PROVENANCE_POINTS.get(value, 0), value))
+
+
+def rank_factors(
+ *,
+ marker: str,
+ boundary: str | None,
+ context: str,
+ reachable: bool | None,
+ site_count: int,
+ provenance: str,
+) -> dict[str, int]:
+ """The additive rank terms, published verbatim on every opportunity.
+
+ Call-site count is logarithmic and capped: leverage matters, but sixty
+ callers is not fifteen times the lead four callers is.
+ """
+ return {
+ "multiplier_shape": MULTIPLIER_POINTS.get(marker, 1),
+ "boundary_kind": BOUNDARY_POINTS.get(boundary or "", 0),
+ "execution_context": CONTEXT_POINTS[context],
+ "entry_reachability": 3 if reachable is True else 0,
+ "affected_call_sites": min(8, int(log2(site_count + 1) * 2)),
+ "provenance": PROVENANCE_POINTS.get(provenance, 0),
+ }
+
+
+def rank_sort_key(item: Any) -> tuple[int, int, str]:
+ """A total order: rank, then leverage, then id so ties never float."""
+ return (-item.rank_score, -item.affected_call_sites_total, item.opportunity_id)
+
+
+__all__ = [
+ "BOUNDARY_POINTS",
+ "CONTEXT_POINTS",
+ "MULTIPLIER_POINTS",
+ "PROVENANCE_POINTS",
+ "dominant_marker",
+ "rank_factors",
+ "rank_sort_key",
+ "weakest_provenance",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/perf/ranking.py b/packages/core/src/repowise/core/analysis/health/perf/ranking.py
index bca8fb28b..65b8bf27c 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/ranking.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/ranking.py
@@ -1,8 +1,8 @@
-"""Primitive 2 — the severity ranker, reusable as a precision GATE.
+"""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
+The ranker is also used as a **precision gate**, not only a sort key. 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*.
diff --git a/tests/fixtures/perf_corpus/README.md b/tests/fixtures/perf_corpus/README.md
new file mode 100644
index 000000000..286647d96
--- /dev/null
+++ b/tests/fixtures/perf_corpus/README.md
@@ -0,0 +1,43 @@
+# Performance opportunity corpus
+
+A small, checked-in, hand-authored corpus that pins the current behaviour of
+`repowise.core.analysis.health.perf`. It is a characterization corpus, not a
+precision corpus: every expectation records what the analyzer does today, so a
+semantic change shows up as an explicit golden diff rather than a silent one.
+
+## Files
+
+| File | Role |
+|---|---|
+| `manifest.json` | Which workload archetypes and languages this corpus covers, and which are honestly **uncovered**. |
+| `observations.json` | The input observations (one raw performance finding each), grouped into named cases. |
+| `golden_opportunities.json` | The exact serialized `PerformanceOpportunity` list the corpus produces, in emitted order. |
+| `golden_plans.json` | The exact `performance_fix` plan payloads the corpus produces. |
+
+## Runner
+
+```
+uv run pytest tests/unit/health/test_perf_corpus_golden.py -v
+```
+
+Or, with the worktree interpreter directly:
+
+```
+.venv/Scripts/python -m pytest tests/unit/health/test_perf_corpus_golden.py -v
+```
+
+Regenerate the goldens **only** when a change to the semantics is intended and
+reviewed:
+
+```
+REPOWISE_REWRITE_PERF_GOLDEN=1 uv run pytest tests/unit/health/test_perf_corpus_golden.py
+```
+
+## Rules
+
+- No session downloads or clones a repository to run this. Every input is
+ checked in here.
+- Archetypes with no fixture are listed as `uncovered` in `manifest.json` with
+ the reason. They are never faked with a synthetic case that would imply
+ coverage the product does not have.
+- Large probe artifacts stay outside the tracked tree.
diff --git a/tests/fixtures/perf_corpus/golden_opportunities.json b/tests/fixtures/perf_corpus/golden_opportunities.json
new file mode 100644
index 000000000..cca7d6b89
--- /dev/null
+++ b/tests/fixtures/perf_corpus/golden_opportunities.json
@@ -0,0 +1,1002 @@
+{
+ "opportunities": [
+ {
+ "affected_call_sites_total": 2,
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/entry.py",
+ "finding_id": "reachability_states-25",
+ "function_name": "a",
+ "line_end": 252,
+ "line_start": 250,
+ "path": [
+ "src/app/entry.py::a",
+ "src/app/db.py::reach_sink"
+ ],
+ "provenance": "call-site",
+ "reason": "reachability_states: io_in_loop at src/app/entry.py:250 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/entry.py",
+ "finding_id": "reachability_states-26",
+ "function_name": "b",
+ "line_end": 257,
+ "line_start": 255,
+ "path": [
+ "src/app/entry.py::b",
+ "src/app/db.py::reach_sink"
+ ],
+ "provenance": "call-site",
+ "reason": "reachability_states: io_in_loop at src/app/entry.py:255 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": null,
+ "intervention_symbol": "src/app/db.py::reach_sink",
+ "observations_total": 2,
+ "opportunity_id": "perf_81d11a5a80af2c45ad13",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 4,
+ "entry_reachability": 3,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 20,
+ "reliable_entry_reachability": true,
+ "shared_path_suffix": [
+ "src/app/db.py::reach_sink"
+ ],
+ "terminal_sink": "src/app/db.py::reach_sink"
+ },
+ {
+ "affected_call_sites_total": 2,
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/api.py",
+ "finding_id": "specific_shared_helper-03",
+ "function_name": "list_users",
+ "line_end": 32,
+ "line_start": 30,
+ "path": [
+ "src/app/api.py::list_users",
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
+ ],
+ "provenance": "call-site",
+ "reason": "specific_shared_helper: io_in_loop at src/app/api.py:30 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/api.py",
+ "finding_id": "specific_shared_helper-04",
+ "function_name": "list_orders",
+ "line_end": 33,
+ "line_start": 31,
+ "path": [
+ "src/app/api.py::list_orders",
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
+ ],
+ "provenance": "call-site",
+ "reason": "specific_shared_helper: io_in_loop at src/app/api.py:31 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "intervention_symbol": "src/app/repo.py::fetch_page",
+ "observations_total": 2,
+ "opportunity_id": "perf_9de801a6e25fb309d266",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 4,
+ "entry_reachability": 3,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 20,
+ "reliable_entry_reachability": true,
+ "shared_path_suffix": [
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
+ ],
+ "terminal_sink": "src/app/db.py::execute"
+ },
+ {
+ "affected_call_sites_total": 2,
+ "affected_files_total": 1,
+ "biomarker_type": "nested_loop_with_io",
+ "biomarker_types": [
+ "io_in_loop",
+ "nested_loop_with_io"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/reindex.py",
+ "finding_id": "cost_shape_merge-21",
+ "function_name": "one",
+ "line_end": 212,
+ "line_start": 210,
+ "path": [
+ "src/app/reindex.py::one",
+ "src/app/db.py::upsert"
+ ],
+ "provenance": "call-site",
+ "reason": "cost_shape_merge: io_in_loop at src/app/reindex.py:210 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "nested_loop_with_io",
+ "file_path": "src/app/reindex.py",
+ "finding_id": "cost_shape_merge-22",
+ "function_name": "many",
+ "line_end": 217,
+ "line_start": 215,
+ "path": [
+ "src/app/reindex.py::many",
+ "src/app/db.py::upsert"
+ ],
+ "provenance": "call-site",
+ "reason": "cost_shape_merge: nested_loop_with_io at src/app/reindex.py:215 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": null,
+ "intervention_symbol": "src/app/db.py::upsert",
+ "observations_total": 2,
+ "opportunity_id": "perf_f5c50464496a3100a1b8",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 6,
+ "provenance": 3
+ },
+ "rank_score": 19,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "src/app/db.py::upsert"
+ ],
+ "terminal_sink": "src/app/db.py::upsert"
+ },
+ {
+ "affected_call_sites_total": 4,
+ "affected_files_total": 4,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/billing.py",
+ "finding_id": "generic_infra_sink-01",
+ "function_name": "handle",
+ "line_end": 13,
+ "line_start": 11,
+ "path": [
+ "src/app/billing.py::handle",
+ "src/app/db.py::get_session"
+ ],
+ "provenance": "call-site",
+ "reason": "generic_infra_sink: io_in_loop at src/app/billing.py:11 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/job.py",
+ "finding_id": "context_split-18",
+ "function_name": "run",
+ "line_end": 202,
+ "line_start": 200,
+ "path": [
+ "src/app/job.py::run",
+ "src/app/db.py::get_session"
+ ],
+ "provenance": "call-site",
+ "reason": "context_split: io_in_loop at src/app/job.py:200 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/orders.py",
+ "finding_id": "generic_infra_sink-00",
+ "function_name": "handle",
+ "line_end": 12,
+ "line_start": 10,
+ "path": [
+ "src/app/orders.py::handle",
+ "src/app/db.py::get_session"
+ ],
+ "provenance": "call-site",
+ "reason": "generic_infra_sink: io_in_loop at src/app/orders.py:10 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/reports.py",
+ "finding_id": "generic_infra_sink-02",
+ "function_name": "handle",
+ "line_end": 14,
+ "line_start": 12,
+ "path": [
+ "src/app/reports.py::handle",
+ "src/app/db.py::get_session"
+ ],
+ "provenance": "call-site",
+ "reason": "generic_infra_sink: io_in_loop at src/app/reports.py:12 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": null,
+ "intervention_symbol": "src/app/db.py::get_session",
+ "observations_total": 4,
+ "opportunity_id": "perf_e358397251b660183fdd",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 4,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 18,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "src/app/db.py::get_session"
+ ],
+ "terminal_sink": "src/app/db.py::get_session"
+ },
+ {
+ "affected_call_sites_total": 2,
+ "affected_files_total": 1,
+ "biomarker_type": "blocking_io_under_lock",
+ "biomarker_types": [
+ "blocking_io_under_lock"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "blocking_io_under_lock",
+ "file_path": "src/app/pool.py",
+ "finding_id": "distinct_lock_owners-13",
+ "function_name": "reaper",
+ "line_end": 132,
+ "line_start": 130,
+ "path": [
+ "src/app/pool.py::reaper",
+ "src/app/store.py::flush"
+ ],
+ "provenance": "call-site",
+ "reason": "distinct_lock_owners: blocking_io_under_lock at src/app/pool.py:130 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "blocking_io_under_lock",
+ "file_path": "src/app/pool.py",
+ "finding_id": "distinct_lock_owners-12",
+ "function_name": "writer",
+ "line_end": 132,
+ "line_start": 130,
+ "path": [
+ "src/app/pool.py::writer",
+ "src/app/store.py::flush"
+ ],
+ "provenance": "call-site",
+ "reason": "distinct_lock_owners: blocking_io_under_lock at src/app/pool.py:130 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": null,
+ "intervention_symbol": "src/app/store.py::flush",
+ "observations_total": 2,
+ "opportunity_id": "perf_c4ee441bf83047cd1cd8",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 5,
+ "provenance": 3
+ },
+ "rank_score": 18,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "src/app/store.py::flush"
+ ],
+ "terminal_sink": "src/app/store.py::flush"
+ },
+ {
+ "affected_call_sites_total": 2,
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/sync.py",
+ "finding_id": "same_file_db_helper-07",
+ "function_name": "sync_one",
+ "line_end": 72,
+ "line_start": 70,
+ "path": [
+ "src/app/sync.py::sync_one",
+ "src/app/sync.py::_load",
+ "src/app/db.py::query"
+ ],
+ "provenance": "call-site",
+ "reason": "same_file_db_helper: io_in_loop at src/app/sync.py:70 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/sync.py",
+ "finding_id": "same_file_db_helper-08",
+ "function_name": "sync_all",
+ "line_end": 73,
+ "line_start": 71,
+ "path": [
+ "src/app/sync.py::sync_all",
+ "src/app/sync.py::_load",
+ "src/app/db.py::query"
+ ],
+ "provenance": "call-site",
+ "reason": "same_file_db_helper: io_in_loop at src/app/sync.py:71 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "intervention_symbol": "src/app/sync.py::_load",
+ "observations_total": 2,
+ "opportunity_id": "perf_353153d5e9b5c681a057",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 17,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "src/app/sync.py::_load",
+ "src/app/db.py::query"
+ ],
+ "terminal_sink": "src/app/db.py::query"
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "blocking_io_under_lock",
+ "biomarker_types": [
+ "blocking_io_under_lock"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "blocking_io_under_lock",
+ "file_path": "src/app/cache.py",
+ "finding_id": "single_lock_owner-11",
+ "function_name": "refresh",
+ "line_end": 112,
+ "line_start": 110,
+ "path": [
+ "src/app/cache.py::refresh",
+ "src/app/db.py::write"
+ ],
+ "provenance": "call-site",
+ "reason": "single_lock_owner: blocking_io_under_lock at src/app/cache.py:110 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "I/O under the lock is proven, but shared-state ordering must be validated before moving it.",
+ "safety": "advisory",
+ "strategy": "shrink_lock_scope"
+ },
+ "intervention_symbol": "src/app/cache.py::refresh",
+ "observations_total": 1,
+ "opportunity_id": "perf_7e351bac743b6db777e7",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 5,
+ "provenance": 3
+ },
+ "rank_score": 17,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "src/app/cache.py::refresh",
+ "src/app/db.py::write"
+ ],
+ "terminal_sink": "src/app/db.py::write"
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "serial_await_in_loop",
+ "biomarker_types": [
+ "serial_await_in_loop"
+ ],
+ "boundary_kind": "network",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "serial_await_in_loop",
+ "file_path": "src/app/fanout.py",
+ "finding_id": "async_serial_awaits-09",
+ "function_name": "gather_all",
+ "line_end": 92,
+ "line_start": 90,
+ "path": [],
+ "provenance": "direct",
+ "reason": "async_serial_awaits: serial_await_in_loop at src/app/fanout.py:90 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "Dataflow proves that every observed loop carries no cross-iteration dependence.",
+ "safety": "proven",
+ "strategy": "parallelize_independent_awaits"
+ },
+ "intervention_symbol": null,
+ "observations_total": 1,
+ "opportunity_id": "perf_182b2a7c053167959285",
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 16,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [],
+ "terminal_sink": null
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "resource_construction_in_loop",
+ "biomarker_types": [
+ "resource_construction_in_loop"
+ ],
+ "boundary_kind": "network",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "resource_construction_in_loop",
+ "file_path": "src/app/clients.py",
+ "finding_id": "resource_construction-17",
+ "function_name": "each_varying",
+ "line_end": 182,
+ "line_start": 180,
+ "path": [],
+ "provenance": "direct",
+ "reason": "resource_construction: resource_construction_in_loop at src/app/clients.py:180 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": null,
+ "intervention_symbol": null,
+ "observations_total": 1,
+ "opportunity_id": "perf_266b6dd67d9b9e93e201",
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 16,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [],
+ "terminal_sink": null
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "resource_construction_in_loop",
+ "biomarker_types": [
+ "resource_construction_in_loop"
+ ],
+ "boundary_kind": "network",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "resource_construction_in_loop",
+ "file_path": "src/app/clients.py",
+ "finding_id": "resource_construction-16",
+ "function_name": "each",
+ "line_end": 172,
+ "line_start": 170,
+ "path": [],
+ "provenance": "direct",
+ "reason": "resource_construction: resource_construction_in_loop at src/app/clients.py:170 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "Dataflow proves construction arguments and lifetime are loop invariant.",
+ "safety": "proven",
+ "strategy": "hoist_loop_invariant_resource"
+ },
+ "intervention_symbol": null,
+ "observations_total": 1,
+ "opportunity_id": "perf_386a99aa2876c0dd31bd",
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 16,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [],
+ "terminal_sink": null
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "serial_await_in_loop",
+ "biomarker_types": [
+ "serial_await_in_loop"
+ ],
+ "boundary_kind": "network",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "serial_await_in_loop",
+ "file_path": "src/app/fanout.py",
+ "finding_id": "async_serial_awaits-10",
+ "function_name": "gather_seq",
+ "line_end": 97,
+ "line_start": 95,
+ "path": [],
+ "provenance": "direct",
+ "reason": "async_serial_awaits: serial_await_in_loop at src/app/fanout.py:95 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": null,
+ "intervention_symbol": null,
+ "observations_total": 1,
+ "opportunity_id": "perf_64fbd03504c61c115894",
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 16,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [],
+ "terminal_sink": null
+ },
+ {
+ "affected_call_sites_total": 2,
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "filesystem",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/walker.py",
+ "finding_id": "filesystem_fan_out-05",
+ "function_name": "scan",
+ "line_end": 52,
+ "line_start": 50,
+ "path": [
+ "src/app/walker.py::scan",
+ "src/app/fsio.py::read_text"
+ ],
+ "provenance": "call-site",
+ "reason": "filesystem_fan_out: io_in_loop at src/app/walker.py:50 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/walker.py",
+ "finding_id": "filesystem_fan_out-06",
+ "function_name": "index",
+ "line_end": 53,
+ "line_start": 51,
+ "path": [
+ "src/app/walker.py::index",
+ "src/app/fsio.py::read_text"
+ ],
+ "provenance": "call-site",
+ "reason": "filesystem_fan_out: io_in_loop at src/app/walker.py:51 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": null,
+ "intervention_symbol": "src/app/fsio.py::read_text",
+ "observations_total": 2,
+ "opportunity_id": "perf_833888def208e12ceb5d",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 2,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 15,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "src/app/fsio.py::read_text"
+ ],
+ "terminal_sink": "src/app/fsio.py::read_text"
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "confidence": "medium",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/edge.py",
+ "finding_id": "provenance_mix-23",
+ "function_name": "run",
+ "line_end": 232,
+ "line_start": 230,
+ "path": [
+ "src/app/edge.py::run",
+ "src/app/db.py::reliable_sink"
+ ],
+ "provenance": "reliable-edge",
+ "reason": "provenance_mix: io_in_loop at src/app/edge.py:230 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "intervention_symbol": "src/app/edge.py::run",
+ "observations_total": 1,
+ "opportunity_id": "perf_688cbe7795e13b1910b2",
+ "provenance": "reliable-edge",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 2
+ },
+ "rank_score": 15,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "src/app/edge.py::run",
+ "src/app/db.py::reliable_sink"
+ ],
+ "terminal_sink": "src/app/db.py::reliable_sink"
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "scripts/backfill.py",
+ "finding_id": "context_split-19",
+ "function_name": "run",
+ "line_end": 202,
+ "line_start": 200,
+ "path": [
+ "scripts/backfill.py::run",
+ "src/app/db.py::get_session"
+ ],
+ "provenance": "call-site",
+ "reason": "context_split: io_in_loop at scripts/backfill.py:200 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "tooling",
+ "fix": {
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "intervention_symbol": "scripts/backfill.py::run",
+ "observations_total": 1,
+ "opportunity_id": "perf_a50b5b7b58559225e3c6",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 2,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 15,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "scripts/backfill.py::run",
+ "src/app/db.py::get_session"
+ ],
+ "terminal_sink": "src/app/db.py::get_session"
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "tests/test_job.py",
+ "finding_id": "context_split-20",
+ "function_name": "run",
+ "line_end": 202,
+ "line_start": 200,
+ "path": [
+ "tests/test_job.py::run",
+ "src/app/db.py::get_session"
+ ],
+ "provenance": "call-site",
+ "reason": "context_split: io_in_loop at tests/test_job.py:200 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "test",
+ "fix": {
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "intervention_symbol": "tests/test_job.py::run",
+ "observations_total": 1,
+ "opportunity_id": "perf_63ace13595c0f6bf553b",
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 1,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 14,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "tests/test_job.py::run",
+ "src/app/db.py::get_session"
+ ],
+ "terminal_sink": "src/app/db.py::get_session"
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "confidence": "low",
+ "evidence": [
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/guess.py",
+ "finding_id": "provenance_mix-24",
+ "function_name": "run",
+ "line_end": 242,
+ "line_start": 240,
+ "path": [
+ "src/app/guess.py::run",
+ "src/app/db.py::guessed_sink"
+ ],
+ "provenance": "name-fallback",
+ "reason": "provenance_mix: io_in_loop at src/app/guess.py:240 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "intervention_symbol": "src/app/guess.py::run",
+ "observations_total": 1,
+ "opportunity_id": "perf_cdc672bf096aac79f951",
+ "provenance": "name-fallback",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 0
+ },
+ "rank_score": 13,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [
+ "src/app/guess.py::run",
+ "src/app/db.py::guessed_sink"
+ ],
+ "terminal_sink": "src/app/db.py::guessed_sink"
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "membership_test_against_list_in_loop",
+ "biomarker_types": [
+ "membership_test_against_list_in_loop"
+ ],
+ "boundary_kind": null,
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "membership_test_against_list_in_loop",
+ "file_path": "src/app/filters.py",
+ "finding_id": "membership_scan-14",
+ "function_name": "select",
+ "line_end": 152,
+ "line_start": 150,
+ "path": [],
+ "provenance": "direct",
+ "reason": "membership_scan: membership_test_against_list_in_loop at src/app/filters.py:150 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "The collection is proven list-backed; element hashability and ordering/identity use still require validation.",
+ "safety": "advisory",
+ "strategy": "replace_membership_collection"
+ },
+ "intervention_symbol": null,
+ "observations_total": 1,
+ "opportunity_id": "perf_6b8f8be1ab10062f0a19",
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 0,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 3,
+ "provenance": 3
+ },
+ "rank_score": 11,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [],
+ "terminal_sink": null
+ },
+ {
+ "affected_call_sites_total": 1,
+ "affected_files_total": 1,
+ "biomarker_type": "string_concat_in_loop",
+ "biomarker_types": [
+ "string_concat_in_loop"
+ ],
+ "boundary_kind": null,
+ "confidence": "high",
+ "evidence": [
+ {
+ "biomarker_type": "string_concat_in_loop",
+ "file_path": "src/app/render.py",
+ "finding_id": "string_accumulation-15",
+ "function_name": "to_csv",
+ "line_end": 162,
+ "line_start": 160,
+ "path": [],
+ "provenance": "direct",
+ "reason": "string_accumulation: string_concat_in_loop at src/app/render.py:160 repeats work per iteration."
+ }
+ ],
+ "evidence_truncated": false,
+ "execution_context": "production",
+ "fix": {
+ "rationale": "Repeated string accumulation is proven; intermediate accumulator observations still require validation.",
+ "safety": "advisory",
+ "strategy": "buffer_string_accumulation"
+ },
+ "intervention_symbol": null,
+ "observations_total": 1,
+ "opportunity_id": "perf_e82f5ad0e9c24fe3d1a1",
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 0,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 3,
+ "provenance": 3
+ },
+ "rank_score": 11,
+ "reliable_entry_reachability": null,
+ "shared_path_suffix": [],
+ "terminal_sink": null
+ }
+ ]
+}
diff --git a/tests/fixtures/perf_corpus/golden_plans.json b/tests/fixtures/perf_corpus/golden_plans.json
new file mode 100644
index 000000000..e5825dbc5
--- /dev/null
+++ b/tests/fixtures/perf_corpus/golden_plans.json
@@ -0,0 +1,690 @@
+{
+ "plans": [
+ {
+ "blast_radius": {
+ "call_sites": 2,
+ "file_count": 1,
+ "files": [
+ "src/app/api.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "execution_context": "production",
+ "observations_total": 2,
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 4,
+ "entry_reachability": 3,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 20,
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "reliable_entry_reachability": true
+ },
+ "file_path": "src/app/repo.py",
+ "impact_delta": 0.0,
+ "line_end": null,
+ "line_start": null,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/api.py",
+ "function_name": "list_users",
+ "line_end": 32,
+ "line_start": 30
+ },
+ {
+ "file_path": "src/app/api.py",
+ "function_name": "list_orders",
+ "line_end": 33,
+ "line_start": 31
+ }
+ ],
+ "affected_locations_total": 2,
+ "evidence_truncated": false,
+ "intervention_symbol": "src/app/repo.py::fetch_page",
+ "opportunity_id": "perf_9de801a6e25fb309d266",
+ "paths": [
+ [
+ "src/app/api.py::list_users",
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
+ ],
+ [
+ "src/app/api.py::list_orders",
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
+ ]
+ ],
+ "paths_total": 2,
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "io_in_loop",
+ "target_symbol": "src/app/repo.py::fetch_page"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 2,
+ "file_count": 1,
+ "files": [
+ "src/app/sync.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "execution_context": "production",
+ "observations_total": 2,
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 17,
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/sync.py",
+ "impact_delta": 0.0,
+ "line_end": 72,
+ "line_start": 70,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/sync.py",
+ "function_name": "sync_one",
+ "line_end": 72,
+ "line_start": 70
+ },
+ {
+ "file_path": "src/app/sync.py",
+ "function_name": "sync_all",
+ "line_end": 73,
+ "line_start": 71
+ }
+ ],
+ "affected_locations_total": 2,
+ "evidence_truncated": false,
+ "intervention_symbol": "src/app/sync.py::_load",
+ "opportunity_id": "perf_353153d5e9b5c681a057",
+ "paths": [
+ [
+ "src/app/sync.py::sync_one",
+ "src/app/sync.py::_load",
+ "src/app/db.py::query"
+ ],
+ [
+ "src/app/sync.py::sync_all",
+ "src/app/sync.py::_load",
+ "src/app/db.py::query"
+ ]
+ ],
+ "paths_total": 2,
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "io_in_loop",
+ "target_symbol": "src/app/sync.py::_load"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "src/app/cache.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "blocking_io_under_lock",
+ "biomarker_types": [
+ "blocking_io_under_lock"
+ ],
+ "boundary_kind": "db",
+ "execution_context": "production",
+ "observations_total": 1,
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 5,
+ "provenance": 3
+ },
+ "rank_score": 17,
+ "rationale": "I/O under the lock is proven, but shared-state ordering must be validated before moving it.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/cache.py",
+ "impact_delta": 0.0,
+ "line_end": 112,
+ "line_start": 110,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/cache.py",
+ "function_name": "refresh",
+ "line_end": 112,
+ "line_start": 110
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": "src/app/cache.py::refresh",
+ "opportunity_id": "perf_7e351bac743b6db777e7",
+ "paths": [
+ [
+ "src/app/cache.py::refresh",
+ "src/app/db.py::write"
+ ]
+ ],
+ "paths_total": 1,
+ "safety": "advisory",
+ "strategy": "shrink_lock_scope"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "blocking_io_under_lock",
+ "target_symbol": "src/app/cache.py::refresh"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "src/app/fanout.py"
+ ]
+ },
+ "confidence": "high",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "serial_await_in_loop",
+ "biomarker_types": [
+ "serial_await_in_loop"
+ ],
+ "boundary_kind": "network",
+ "execution_context": "production",
+ "observations_total": 1,
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 16,
+ "rationale": "Dataflow proves that every observed loop carries no cross-iteration dependence.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/fanout.py",
+ "impact_delta": 0.0,
+ "line_end": 92,
+ "line_start": 90,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/fanout.py",
+ "function_name": "gather_all",
+ "line_end": 92,
+ "line_start": 90
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": null,
+ "opportunity_id": "perf_182b2a7c053167959285",
+ "paths": [],
+ "paths_total": 1,
+ "safety": "proven",
+ "strategy": "parallelize_independent_awaits"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "serial_await_in_loop",
+ "target_symbol": "gather_all"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "src/app/clients.py"
+ ]
+ },
+ "confidence": "high",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "resource_construction_in_loop",
+ "biomarker_types": [
+ "resource_construction_in_loop"
+ ],
+ "boundary_kind": "network",
+ "execution_context": "production",
+ "observations_total": 1,
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 16,
+ "rationale": "Dataflow proves construction arguments and lifetime are loop invariant.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/clients.py",
+ "impact_delta": 0.0,
+ "line_end": 172,
+ "line_start": 170,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/clients.py",
+ "function_name": "each",
+ "line_end": 172,
+ "line_start": 170
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": null,
+ "opportunity_id": "perf_386a99aa2876c0dd31bd",
+ "paths": [],
+ "paths_total": 1,
+ "safety": "proven",
+ "strategy": "hoist_loop_invariant_resource"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "resource_construction_in_loop",
+ "target_symbol": "each"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "src/app/edge.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "execution_context": "production",
+ "observations_total": 1,
+ "provenance": "reliable-edge",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 2
+ },
+ "rank_score": 15,
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/edge.py",
+ "impact_delta": 0.0,
+ "line_end": 232,
+ "line_start": 230,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/edge.py",
+ "function_name": "run",
+ "line_end": 232,
+ "line_start": 230
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": "src/app/edge.py::run",
+ "opportunity_id": "perf_688cbe7795e13b1910b2",
+ "paths": [
+ [
+ "src/app/edge.py::run",
+ "src/app/db.py::reliable_sink"
+ ]
+ ],
+ "paths_total": 1,
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "io_in_loop",
+ "target_symbol": "src/app/edge.py::run"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "scripts/backfill.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "execution_context": "tooling",
+ "observations_total": 1,
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 2,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 15,
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "scripts/backfill.py",
+ "impact_delta": 0.0,
+ "line_end": 202,
+ "line_start": 200,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "scripts/backfill.py",
+ "function_name": "run",
+ "line_end": 202,
+ "line_start": 200
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": "scripts/backfill.py::run",
+ "opportunity_id": "perf_a50b5b7b58559225e3c6",
+ "paths": [
+ [
+ "scripts/backfill.py::run",
+ "src/app/db.py::get_session"
+ ]
+ ],
+ "paths_total": 1,
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "io_in_loop",
+ "target_symbol": "scripts/backfill.py::run"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "tests/test_job.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "execution_context": "test",
+ "observations_total": 1,
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 1,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 14,
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "tests/test_job.py",
+ "impact_delta": 0.0,
+ "line_end": 202,
+ "line_start": 200,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "tests/test_job.py",
+ "function_name": "run",
+ "line_end": 202,
+ "line_start": 200
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": "tests/test_job.py::run",
+ "opportunity_id": "perf_63ace13595c0f6bf553b",
+ "paths": [
+ [
+ "tests/test_job.py::run",
+ "src/app/db.py::get_session"
+ ]
+ ],
+ "paths_total": 1,
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "io_in_loop",
+ "target_symbol": "tests/test_job.py::run"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "src/app/guess.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "io_in_loop",
+ "biomarker_types": [
+ "io_in_loop"
+ ],
+ "boundary_kind": "db",
+ "execution_context": "production",
+ "observations_total": 1,
+ "provenance": "name-fallback",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 4,
+ "provenance": 0
+ },
+ "rank_score": 13,
+ "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/guess.py",
+ "impact_delta": 0.0,
+ "line_end": 242,
+ "line_start": 240,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/guess.py",
+ "function_name": "run",
+ "line_end": 242,
+ "line_start": 240
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": "src/app/guess.py::run",
+ "opportunity_id": "perf_cdc672bf096aac79f951",
+ "paths": [
+ [
+ "src/app/guess.py::run",
+ "src/app/db.py::guessed_sink"
+ ]
+ ],
+ "paths_total": 1,
+ "safety": "advisory",
+ "strategy": "batch_or_prefetch_io"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "io_in_loop",
+ "target_symbol": "src/app/guess.py::run"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "src/app/filters.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "membership_test_against_list_in_loop",
+ "biomarker_types": [
+ "membership_test_against_list_in_loop"
+ ],
+ "boundary_kind": null,
+ "execution_context": "production",
+ "observations_total": 1,
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 0,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 3,
+ "provenance": 3
+ },
+ "rank_score": 11,
+ "rationale": "The collection is proven list-backed; element hashability and ordering/identity use still require validation.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/filters.py",
+ "impact_delta": 0.0,
+ "line_end": 152,
+ "line_start": 150,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/filters.py",
+ "function_name": "select",
+ "line_end": 152,
+ "line_start": 150
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": null,
+ "opportunity_id": "perf_6b8f8be1ab10062f0a19",
+ "paths": [],
+ "paths_total": 1,
+ "safety": "advisory",
+ "strategy": "replace_membership_collection"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "membership_test_against_list_in_loop",
+ "target_symbol": "select"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "src/app/render.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "string_concat_in_loop",
+ "biomarker_types": [
+ "string_concat_in_loop"
+ ],
+ "boundary_kind": null,
+ "execution_context": "production",
+ "observations_total": 1,
+ "provenance": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 0,
+ "entry_reachability": 0,
+ "execution_context": 3,
+ "multiplier_shape": 3,
+ "provenance": 3
+ },
+ "rank_score": 11,
+ "rationale": "Repeated string accumulation is proven; intermediate accumulator observations still require validation.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/render.py",
+ "impact_delta": 0.0,
+ "line_end": 162,
+ "line_start": 160,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/render.py",
+ "function_name": "to_csv",
+ "line_end": 162,
+ "line_start": 160
+ }
+ ],
+ "affected_locations_total": 1,
+ "evidence_truncated": false,
+ "intervention_symbol": null,
+ "opportunity_id": "perf_e82f5ad0e9c24fe3d1a1",
+ "paths": [],
+ "paths_total": 1,
+ "safety": "advisory",
+ "strategy": "buffer_string_accumulation"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "string_concat_in_loop",
+ "target_symbol": "to_csv"
+ }
+ ]
+}
diff --git a/tests/fixtures/perf_corpus/manifest.json b/tests/fixtures/perf_corpus/manifest.json
new file mode 100644
index 000000000..67cdd6484
--- /dev/null
+++ b/tests/fixtures/perf_corpus/manifest.json
@@ -0,0 +1,62 @@
+{
+ "corpus_version": 1,
+ "performance_model_version": 1,
+ "purpose": "characterization of current grouping, identity, actionability and ranking",
+ "runner": "uv run pytest tests/unit/health/test_perf_corpus_golden.py -v",
+ "rewrite_env": "REPOWISE_REWRITE_PERF_GOLDEN=1",
+ "downloads_repositories": false,
+ "cases_are_hand_authored": true,
+ "covered": [
+ {
+ "archetype": "cli_build_indexing_tool",
+ "language": "python",
+ "cases": ["generic_infra_sink", "specific_shared_helper", "filesystem_fan_out"],
+ "note": "Over-represented on purpose; it is one archetype row, not the tuning target."
+ },
+ {
+ "archetype": "orm_database_heavy",
+ "language": "python",
+ "cases": ["generic_infra_sink", "same_file_db_helper", "async_serial_awaits"],
+ "note": "Database boundary through a shared session/query helper."
+ },
+ {
+ "archetype": "concurrent_server_worker",
+ "language": "python",
+ "cases": ["single_lock_owner", "distinct_lock_owners"],
+ "note": "Only the lock-scope shape is expressible today."
+ },
+ {
+ "archetype": "general_library",
+ "language": "python",
+ "cases": ["membership_scan", "string_accumulation", "resource_construction"],
+ "note": "Local, same-function cost shapes with no call path."
+ }
+ ],
+ "uncovered": [
+ {
+ "archetype": "web_api_service",
+ "reason": "No request-scoped entrypoint or route-context fact exists yet; a fixture would imply exposure evidence the analyzer cannot produce.",
+ "prerequisite": "typed entrypoint context"
+ },
+ {
+ "archetype": "data_pipeline_dataframe",
+ "reason": "No collection cardinality or dataframe-operation model; the only expressible marker is generic io_in_loop, which the CLI archetype already covers.",
+ "prerequisite": "cardinality and multiplicity propagation"
+ },
+ {
+ "archetype": "mobile_application",
+ "reason": "No Kotlin/Swift/Dart fixture is exercised through the opportunity layer in this repository; the dialects emit observations but no labelled archetype case exists.",
+ "prerequisite": "per-language corpus rows"
+ },
+ {
+ "archetype": "systems_native",
+ "reason": "C/C++/Rust observations reach the same generic markers; no distinct native cost shape is modelled.",
+ "prerequisite": "per-language corpus rows"
+ }
+ ],
+ "languages_covered": ["python"],
+ "languages_uncovered": [
+ "typescript", "java", "kotlin", "go", "rust", "csharp", "ruby", "scala", "dart", "cpp"
+ ],
+ "languages_uncovered_reason": "The opportunity layer is language-neutral: it consumes biomarker findings, not source. Per-language recall lives in tests/unit/health/test_perf_dialects.py. Adding language rows here would duplicate that suite without adding grouping evidence."
+}
diff --git a/tests/fixtures/perf_corpus/observations.json b/tests/fixtures/perf_corpus/observations.json
new file mode 100644
index 000000000..daeb89c00
--- /dev/null
+++ b/tests/fixtures/perf_corpus/observations.json
@@ -0,0 +1,482 @@
+{
+ "observations": [
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "generic_infra_sink",
+ "extra": {},
+ "file_path": "src/app/orders.py",
+ "finding_ref": "generic_infra_sink-00",
+ "function_name": "handle",
+ "line_end": 12,
+ "line_start": 10,
+ "path": [
+ "src/app/orders.py::handle",
+ "src/app/db.py::get_session"
+ ],
+ "reason": "generic_infra_sink: io_in_loop at src/app/orders.py:10 repeats work per iteration.",
+ "reliable_entry_reachability": false,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "generic_infra_sink",
+ "extra": {},
+ "file_path": "src/app/billing.py",
+ "finding_ref": "generic_infra_sink-01",
+ "function_name": "handle",
+ "line_end": 13,
+ "line_start": 11,
+ "path": [
+ "src/app/billing.py::handle",
+ "src/app/db.py::get_session"
+ ],
+ "reason": "generic_infra_sink: io_in_loop at src/app/billing.py:11 repeats work per iteration.",
+ "reliable_entry_reachability": false,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "generic_infra_sink",
+ "extra": {},
+ "file_path": "src/app/reports.py",
+ "finding_ref": "generic_infra_sink-02",
+ "function_name": "handle",
+ "line_end": 14,
+ "line_start": 12,
+ "path": [
+ "src/app/reports.py::handle",
+ "src/app/db.py::get_session"
+ ],
+ "reason": "generic_infra_sink: io_in_loop at src/app/reports.py:12 repeats work per iteration.",
+ "reliable_entry_reachability": false,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "specific_shared_helper",
+ "extra": {},
+ "file_path": "src/app/api.py",
+ "finding_ref": "specific_shared_helper-03",
+ "function_name": "list_users",
+ "line_end": 32,
+ "line_start": 30,
+ "path": [
+ "src/app/api.py::list_users",
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
+ ],
+ "reason": "specific_shared_helper: io_in_loop at src/app/api.py:30 repeats work per iteration.",
+ "reliable_entry_reachability": true,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "specific_shared_helper",
+ "extra": {},
+ "file_path": "src/app/api.py",
+ "finding_ref": "specific_shared_helper-04",
+ "function_name": "list_orders",
+ "line_end": 33,
+ "line_start": 31,
+ "path": [
+ "src/app/api.py::list_orders",
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
+ ],
+ "reason": "specific_shared_helper: io_in_loop at src/app/api.py:31 repeats work per iteration.",
+ "reliable_entry_reachability": true,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "filesystem",
+ "case": "filesystem_fan_out",
+ "extra": {},
+ "file_path": "src/app/walker.py",
+ "finding_ref": "filesystem_fan_out-05",
+ "function_name": "scan",
+ "line_end": 52,
+ "line_start": 50,
+ "path": [
+ "src/app/walker.py::scan",
+ "src/app/fsio.py::read_text"
+ ],
+ "reason": "filesystem_fan_out: io_in_loop at src/app/walker.py:50 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "filesystem",
+ "case": "filesystem_fan_out",
+ "extra": {},
+ "file_path": "src/app/walker.py",
+ "finding_ref": "filesystem_fan_out-06",
+ "function_name": "index",
+ "line_end": 53,
+ "line_start": 51,
+ "path": [
+ "src/app/walker.py::index",
+ "src/app/fsio.py::read_text"
+ ],
+ "reason": "filesystem_fan_out: io_in_loop at src/app/walker.py:51 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "same_file_db_helper",
+ "extra": {},
+ "file_path": "src/app/sync.py",
+ "finding_ref": "same_file_db_helper-07",
+ "function_name": "sync_one",
+ "line_end": 72,
+ "line_start": 70,
+ "path": [
+ "src/app/sync.py::sync_one",
+ "src/app/sync.py::_load",
+ "src/app/db.py::query"
+ ],
+ "reason": "same_file_db_helper: io_in_loop at src/app/sync.py:70 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "same_file_db_helper",
+ "extra": {},
+ "file_path": "src/app/sync.py",
+ "finding_ref": "same_file_db_helper-08",
+ "function_name": "sync_all",
+ "line_end": 73,
+ "line_start": 71,
+ "path": [
+ "src/app/sync.py::sync_all",
+ "src/app/sync.py::_load",
+ "src/app/db.py::query"
+ ],
+ "reason": "same_file_db_helper: io_in_loop at src/app/sync.py:71 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "serial_await_in_loop",
+ "boundary_kind": "network",
+ "case": "async_serial_awaits",
+ "extra": {
+ "dataflow_verified": true
+ },
+ "file_path": "src/app/fanout.py",
+ "finding_ref": "async_serial_awaits-09",
+ "function_name": "gather_all",
+ "line_end": 92,
+ "line_start": 90,
+ "path": [],
+ "reason": "async_serial_awaits: serial_await_in_loop at src/app/fanout.py:90 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "direct"
+ },
+ {
+ "biomarker_type": "serial_await_in_loop",
+ "boundary_kind": "network",
+ "case": "async_serial_awaits",
+ "extra": {},
+ "file_path": "src/app/fanout.py",
+ "finding_ref": "async_serial_awaits-10",
+ "function_name": "gather_seq",
+ "line_end": 97,
+ "line_start": 95,
+ "path": [],
+ "reason": "async_serial_awaits: serial_await_in_loop at src/app/fanout.py:95 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "direct"
+ },
+ {
+ "biomarker_type": "blocking_io_under_lock",
+ "boundary_kind": "db",
+ "case": "single_lock_owner",
+ "extra": {},
+ "file_path": "src/app/cache.py",
+ "finding_ref": "single_lock_owner-11",
+ "function_name": "refresh",
+ "line_end": 112,
+ "line_start": 110,
+ "path": [
+ "src/app/cache.py::refresh",
+ "src/app/db.py::write"
+ ],
+ "reason": "single_lock_owner: blocking_io_under_lock at src/app/cache.py:110 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "blocking_io_under_lock",
+ "boundary_kind": "db",
+ "case": "distinct_lock_owners",
+ "extra": {},
+ "file_path": "src/app/pool.py",
+ "finding_ref": "distinct_lock_owners-12",
+ "function_name": "writer",
+ "line_end": 132,
+ "line_start": 130,
+ "path": [
+ "src/app/pool.py::writer",
+ "src/app/store.py::flush"
+ ],
+ "reason": "distinct_lock_owners: blocking_io_under_lock at src/app/pool.py:130 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "blocking_io_under_lock",
+ "boundary_kind": "db",
+ "case": "distinct_lock_owners",
+ "extra": {},
+ "file_path": "src/app/pool.py",
+ "finding_ref": "distinct_lock_owners-13",
+ "function_name": "reaper",
+ "line_end": 132,
+ "line_start": 130,
+ "path": [
+ "src/app/pool.py::reaper",
+ "src/app/store.py::flush"
+ ],
+ "reason": "distinct_lock_owners: blocking_io_under_lock at src/app/pool.py:130 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "membership_test_against_list_in_loop",
+ "boundary_kind": null,
+ "case": "membership_scan",
+ "extra": {},
+ "file_path": "src/app/filters.py",
+ "finding_ref": "membership_scan-14",
+ "function_name": "select",
+ "line_end": 152,
+ "line_start": 150,
+ "path": [],
+ "reason": "membership_scan: membership_test_against_list_in_loop at src/app/filters.py:150 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "direct"
+ },
+ {
+ "biomarker_type": "string_concat_in_loop",
+ "boundary_kind": null,
+ "case": "string_accumulation",
+ "extra": {},
+ "file_path": "src/app/render.py",
+ "finding_ref": "string_accumulation-15",
+ "function_name": "to_csv",
+ "line_end": 162,
+ "line_start": 160,
+ "path": [],
+ "reason": "string_accumulation: string_concat_in_loop at src/app/render.py:160 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "direct"
+ },
+ {
+ "biomarker_type": "resource_construction_in_loop",
+ "boundary_kind": "network",
+ "case": "resource_construction",
+ "extra": {
+ "resource_invariant": true
+ },
+ "file_path": "src/app/clients.py",
+ "finding_ref": "resource_construction-16",
+ "function_name": "each",
+ "line_end": 172,
+ "line_start": 170,
+ "path": [],
+ "reason": "resource_construction: resource_construction_in_loop at src/app/clients.py:170 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "direct"
+ },
+ {
+ "biomarker_type": "resource_construction_in_loop",
+ "boundary_kind": "network",
+ "case": "resource_construction",
+ "extra": {
+ "resource_invariant": false
+ },
+ "file_path": "src/app/clients.py",
+ "finding_ref": "resource_construction-17",
+ "function_name": "each_varying",
+ "line_end": 182,
+ "line_start": 180,
+ "path": [],
+ "reason": "resource_construction: resource_construction_in_loop at src/app/clients.py:180 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "direct"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "context_split",
+ "extra": {},
+ "file_path": "src/app/job.py",
+ "finding_ref": "context_split-18",
+ "function_name": "run",
+ "line_end": 202,
+ "line_start": 200,
+ "path": [
+ "src/app/job.py::run",
+ "src/app/db.py::get_session"
+ ],
+ "reason": "context_split: io_in_loop at src/app/job.py:200 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "context_split",
+ "extra": {},
+ "file_path": "scripts/backfill.py",
+ "finding_ref": "context_split-19",
+ "function_name": "run",
+ "line_end": 202,
+ "line_start": 200,
+ "path": [
+ "scripts/backfill.py::run",
+ "src/app/db.py::get_session"
+ ],
+ "reason": "context_split: io_in_loop at scripts/backfill.py:200 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "context_split",
+ "extra": {},
+ "file_path": "tests/test_job.py",
+ "finding_ref": "context_split-20",
+ "function_name": "run",
+ "line_end": 202,
+ "line_start": 200,
+ "path": [
+ "tests/test_job.py::run",
+ "src/app/db.py::get_session"
+ ],
+ "reason": "context_split: io_in_loop at tests/test_job.py:200 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "cost_shape_merge",
+ "extra": {},
+ "file_path": "src/app/reindex.py",
+ "finding_ref": "cost_shape_merge-21",
+ "function_name": "one",
+ "line_end": 212,
+ "line_start": 210,
+ "path": [
+ "src/app/reindex.py::one",
+ "src/app/db.py::upsert"
+ ],
+ "reason": "cost_shape_merge: io_in_loop at src/app/reindex.py:210 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "nested_loop_with_io",
+ "boundary_kind": "db",
+ "case": "cost_shape_merge",
+ "extra": {},
+ "file_path": "src/app/reindex.py",
+ "finding_ref": "cost_shape_merge-22",
+ "function_name": "many",
+ "line_end": 217,
+ "line_start": 215,
+ "path": [
+ "src/app/reindex.py::many",
+ "src/app/db.py::upsert"
+ ],
+ "reason": "cost_shape_merge: nested_loop_with_io at src/app/reindex.py:215 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "provenance_mix",
+ "extra": {},
+ "file_path": "src/app/edge.py",
+ "finding_ref": "provenance_mix-23",
+ "function_name": "run",
+ "line_end": 232,
+ "line_start": 230,
+ "path": [
+ "src/app/edge.py::run",
+ "src/app/db.py::reliable_sink"
+ ],
+ "reason": "provenance_mix: io_in_loop at src/app/edge.py:230 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "reliable-edge"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "provenance_mix",
+ "extra": {},
+ "file_path": "src/app/guess.py",
+ "finding_ref": "provenance_mix-24",
+ "function_name": "run",
+ "line_end": 242,
+ "line_start": 240,
+ "path": [
+ "src/app/guess.py::run",
+ "src/app/db.py::guessed_sink"
+ ],
+ "reason": "provenance_mix: io_in_loop at src/app/guess.py:240 repeats work per iteration.",
+ "reliable_entry_reachability": null,
+ "resolution_basis": "name-fallback"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "reachability_states",
+ "extra": {},
+ "file_path": "src/app/entry.py",
+ "finding_ref": "reachability_states-25",
+ "function_name": "a",
+ "line_end": 252,
+ "line_start": 250,
+ "path": [
+ "src/app/entry.py::a",
+ "src/app/db.py::reach_sink"
+ ],
+ "reason": "reachability_states: io_in_loop at src/app/entry.py:250 repeats work per iteration.",
+ "reliable_entry_reachability": true,
+ "resolution_basis": "call-site"
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "boundary_kind": "db",
+ "case": "reachability_states",
+ "extra": {},
+ "file_path": "src/app/entry.py",
+ "finding_ref": "reachability_states-26",
+ "function_name": "b",
+ "line_end": 257,
+ "line_start": 255,
+ "path": [
+ "src/app/entry.py::b",
+ "src/app/db.py::reach_sink"
+ ],
+ "reason": "reachability_states: io_in_loop at src/app/entry.py:255 repeats work per iteration.",
+ "reliable_entry_reachability": false,
+ "resolution_basis": "call-site"
+ }
+ ]
+}
diff --git a/tests/unit/health/perf_corpus_fixture.py b/tests/unit/health/perf_corpus_fixture.py
new file mode 100644
index 000000000..552d40dfd
--- /dev/null
+++ b/tests/unit/health/perf_corpus_fixture.py
@@ -0,0 +1,72 @@
+"""Loader for the checked-in performance opportunity corpus.
+
+The corpus lives in ``tests/fixtures/perf_corpus`` so a characterization run
+needs no repository download, no index, and no network. See that directory's
+README for the runner and the regeneration switch.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+from typing import Any
+
+CORPUS_DIR = Path(__file__).resolve().parents[2] / "fixtures" / "perf_corpus"
+REWRITE_ENV = "REPOWISE_REWRITE_PERF_GOLDEN"
+
+
+def rewrite_requested() -> bool:
+ return os.environ.get(REWRITE_ENV, "") not in {"", "0", "false", "False"}
+
+
+def _read(name: str) -> Any:
+ return json.loads((CORPUS_DIR / name).read_text(encoding="utf-8"))
+
+
+def observation_rows() -> list[dict[str, Any]]:
+ """Expand the compact corpus records into raw performance finding rows.
+
+ Rows are plain dicts on purpose: ``build_performance_opportunities`` accepts
+ analyzer dataclasses, ORM rows, and dicts through one attribute adapter, and
+ the dict form is the one that keeps the corpus readable in review.
+ """
+ rows: list[dict[str, Any]] = []
+ for record in _read("observations.json")["observations"]:
+ rows.append(
+ {
+ "id": record["finding_ref"],
+ "dimension": "performance",
+ "biomarker_type": record["biomarker_type"],
+ "file_path": record["file_path"],
+ "function_name": record["function_name"],
+ "line_start": record["line_start"],
+ "line_end": record["line_end"],
+ "reason": record["reason"],
+ "details": {
+ "boundary_kind": record["boundary_kind"],
+ "cross_function": bool(record["path"]),
+ "path": list(record["path"]),
+ "resolution_basis": record["resolution_basis"],
+ "reliable_entry_reachability": record["reliable_entry_reachability"],
+ **record["extra"],
+ },
+ }
+ )
+ return rows
+
+
+def rows_for(case: str) -> list[dict[str, Any]]:
+ records = _read("observations.json")["observations"]
+ keep = {record["finding_ref"] for record in records if record["case"] == case}
+ return [row for row in observation_rows() if row["id"] in keep]
+
+
+def load_golden(name: str) -> Any:
+ return _read(name)
+
+
+def write_golden(name: str, payload: Any) -> None:
+ with (CORPUS_DIR / name).open("w", encoding="utf-8", newline="\n") as handle:
+ json.dump(payload, handle, indent=2, sort_keys=True)
+ handle.write("\n")
diff --git a/tests/unit/health/test_perf_corpus_golden.py b/tests/unit/health/test_perf_corpus_golden.py
new file mode 100644
index 000000000..cf93abfee
--- /dev/null
+++ b/tests/unit/health/test_perf_corpus_golden.py
@@ -0,0 +1,173 @@
+"""Golden characterization of the performance opportunity read model.
+
+Asserts the exact serialized output of the engine over a checked-in corpus, so
+a change to grouping, actionability, or ranking shows up as a reviewable golden
+diff rather than a silent count move. Nothing here claims the current grouping
+is correct; several cases pin behaviour that should improve.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.perf.opportunities import (
+ build_performance_opportunities,
+ link_performance_findings,
+)
+from repowise.core.analysis.health.refactoring.performance_fix import (
+ performance_fix_suggestions,
+)
+
+from .perf_corpus_fixture import (
+ load_golden,
+ observation_rows,
+ rewrite_requested,
+ rows_for,
+ write_golden,
+)
+
+EVIDENCE_LIMIT = 8
+
+
+def _opportunities():
+ return build_performance_opportunities(observation_rows(), evidence_limit=EVIDENCE_LIMIT)
+
+
+def _plan_payloads(opportunities):
+ return [
+ {
+ "refactoring_type": plan.refactoring_type,
+ "file_path": plan.file_path,
+ "target_symbol": plan.target_symbol,
+ "line_start": plan.line_start,
+ "line_end": plan.line_end,
+ "plan": plan.plan,
+ "evidence": plan.evidence,
+ "impact_delta": plan.impact_delta,
+ "blast_radius": plan.blast_radius,
+ "confidence": plan.confidence,
+ "source_biomarker": plan.source_biomarker,
+ }
+ for plan in performance_fix_suggestions(opportunities)
+ ]
+
+
+def test_opportunity_payloads_and_order_match_the_golden() -> None:
+ """Identity, membership, ordering, confidence, and evidence in one artifact."""
+ payload = [item.as_dict() for item in _opportunities()]
+ if rewrite_requested():
+ write_golden("golden_opportunities.json", {"opportunities": payload})
+ pytest.skip("golden rewritten")
+ assert payload == load_golden("golden_opportunities.json")["opportunities"]
+
+
+def test_performance_plan_payloads_match_the_golden() -> None:
+ """Exact plan linkage: every plan names the opportunity id it addresses."""
+ payload = _plan_payloads(_opportunities())
+ if rewrite_requested():
+ write_golden("golden_plans.json", {"plans": payload})
+ pytest.skip("golden rewritten")
+ assert payload == load_golden("golden_plans.json")["plans"]
+
+
+def test_every_plan_names_an_opportunity_that_the_corpus_still_produces() -> None:
+ """The only accepted plan join is exact ``opportunity_id`` equality."""
+ opportunities = _opportunities()
+ ids = {item.opportunity_id for item in opportunities}
+ plans = performance_fix_suggestions(opportunities)
+ assert plans, "the corpus must exercise the plan path"
+ assert {plan.plan["opportunity_id"] for plan in plans} <= ids
+
+
+def test_grouping_is_independent_of_input_order() -> None:
+ rows = observation_rows()
+ forward = [item.as_dict() for item in build_performance_opportunities(rows)]
+ reverse = [item.as_dict() for item in build_performance_opportunities(list(reversed(rows)))]
+ assert forward == reverse
+
+
+def test_a_subset_of_the_corpus_reproduces_the_same_identities() -> None:
+ """Opportunity identity does not depend on which other rows were analyzed.
+
+ This is the invariant the incremental path relies on: a partial run sees a
+ subset of observations and must still stamp the ids a full run would.
+ """
+ whole = {item.opportunity_id: item.execution_context for item in _opportunities()}
+ for case in ("generic_infra_sink", "specific_shared_helper", "context_split"):
+ subset = build_performance_opportunities(rows_for(case), evidence_limit=EVIDENCE_LIMIT)
+ assert subset, case
+ for item in subset:
+ assert item.opportunity_id in whole, case
+ assert whole[item.opportunity_id] == item.execution_context, case
+
+
+def test_linking_stamps_the_id_the_builder_derives() -> None:
+ rows = observation_rows()
+ link_performance_findings(rows)
+ opportunities = _opportunities()
+ by_id = {item.opportunity_id: item for item in opportunities}
+ stamped = {row["details"]["opportunity_id"] for row in rows}
+ assert stamped == set(by_id)
+ for item in opportunities:
+ members = [row for row in rows if row["details"]["opportunity_id"] == item.opportunity_id]
+ assert len(members) == item.observations_total
+
+
+ ("case", "expected_groups", "expected_strategies"),
+ [
+ # A generic infrastructure sink merges unrelated callers into one group
+ # and refuses to claim a plan.
+ ("generic_infra_sink", 1, {None}),
+ # A specific shared helper keeps a coherent suffix and does get a plan.
+ ("specific_shared_helper", 1, {"batch_or_prefetch_io"}),
+ # Filesystem repetition is real but has no batch API to point at.
+ ("filesystem_fan_out", 1, {None}),
+ ("same_file_db_helper", 1, {"batch_or_prefetch_io"}),
+ ("async_serial_awaits", 2, {"parallelize_independent_awaits", None}),
+ ("single_lock_owner", 1, {"shrink_lock_scope"}),
+ ("distinct_lock_owners", 1, {None}),
+ ("membership_scan", 1, {"replace_membership_collection"}),
+ ("string_accumulation", 1, {"buffer_string_accumulation"}),
+ ("resource_construction", 2, {"hoist_loop_invariant_resource", None}),
+ # Execution context is an identity input: one shape, three contexts.
+ # Each context holds a single caller, so its shared suffix is the whole
+ # path and a plan is offered, while ``generic_infra_sink`` above, with
+ # three callers on the same sink, gets none: plan availability falls
+ # as caller count rises, which is backwards.
+ ("context_split", 3, {"batch_or_prefetch_io"}),
+ # io_in_loop and nested_loop_with_io share one cross-function identity,
+ # and two callers shorten the suffix to the sink alone, so no plan.
+ ("cost_shape_merge", 1, {None}),
+ ("provenance_mix", 2, {"batch_or_prefetch_io"}),
+ ("reachability_states", 1, {None}),
+ ],
+)
+def test_case_membership_and_actionability(case, expected_groups, expected_strategies) -> None:
+ opportunities = build_performance_opportunities(rows_for(case), evidence_limit=EVIDENCE_LIMIT)
+ assert len(opportunities) == expected_groups
+ assert {
+ item.fix.strategy if item.fix else None for item in opportunities
+ } == expected_strategies
+
+
+def test_confidence_facets_available_today_are_provenance_only() -> None:
+ """Evidence confidence and actionability are not yet separable.
+
+ ``confidence`` is derived from call-graph provenance alone; a plan's own
+ confidence comes from ``fix.safety`` in the refactoring layer. This records
+ that the two facets are still collapsed into one label.
+ """
+ by_case = {
+ "provenance_mix": {"medium", "low"},
+ "generic_infra_sink": {"high"},
+ }
+ for case, expected in by_case.items():
+ items = build_performance_opportunities(rows_for(case))
+ assert {item.confidence for item in items} == expected
+
+
+def test_reachability_aggregates_any_true_over_all_false() -> None:
+ item = build_performance_opportunities(rows_for("reachability_states"))[0]
+ assert item.reliable_entry_reachability is True
+ assert item.observations_total == 2
diff --git a/tests/unit/health/test_perf_identity_contract.py b/tests/unit/health/test_perf_identity_contract.py
new file mode 100644
index 000000000..8e00b018a
--- /dev/null
+++ b/tests/unit/health/test_perf_identity_contract.py
@@ -0,0 +1,227 @@
+"""Versioned identity kernels for performance findings, opportunities, and plans.
+
+An opportunity id is a persisted join key: it is stamped into every raw
+finding's ``details_json`` at analyze time and into every performance plan's
+``plan_json`` at generation time, and both REST and MCP join on exact string
+equality. So the *inputs* to that hash are a contract, not an implementation
+detail. This suite pins them, and pins which fields are deliberately outside the
+kernel so that adding a fact or editing prose cannot churn identity by accident.
+
+A change to the kernel increments ``PERFORMANCE_MODEL_VERSION`` and moves these
+pinned strings in one reviewable diff.
+"""
+
+from __future__ import annotations
+
+import copy
+
+import pytest
+
+from repowise.core.analysis.health.perf.opportunities import (
+ PERFORMANCE_MODEL_VERSION,
+ build_performance_opportunities,
+ link_performance_findings,
+ opportunity_id_for_finding,
+)
+from repowise.core.analysis.health.refactoring.performance_fix import (
+ performance_fix_suggestions,
+)
+
+# The v1 kernel, pinned. A change to either string is a model-version change.
+CROSS_FUNCTION_ID = "perf_e358397251b660183fdd"
+LOCAL_ID = "perf_f13beed790fd3cb29ac1"
+
+
+def _row(**overrides):
+ row = {
+ "id": "storage-uuid-not-a-content-hash",
+ "dimension": "performance",
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/a.py",
+ "function_name": "run",
+ "line_start": 10,
+ "line_end": 12,
+ "reason": "Database work repeats for every loop iteration.",
+ "details": {
+ "boundary_kind": "db",
+ "cross_function": True,
+ "path": ["src/app/a.py::run", "src/app/db.py::get_session"],
+ "resolution_basis": "call-site",
+ },
+ }
+ details = overrides.pop("details", None)
+ row.update(overrides)
+ if details is not None:
+ row["details"] = {**row["details"], **details}
+ return row
+
+
+def _local_row(**overrides):
+ return _row(
+ details={"cross_function": False, "path": [], "resolution_basis": "direct"}, **overrides
+ )
+
+
+def test_the_model_version_is_pinned_and_is_not_itself_a_kernel_input() -> None:
+ """v1 ids predate the constant, so the constant stays out of the payload.
+
+ Embedding the version in the hash would rewrite every persisted
+ ``opportunity_id`` and orphan every stored plan link for no semantic
+ change. A later version may embed it; version 1 must not.
+ """
+ assert PERFORMANCE_MODEL_VERSION == 1
+ assert opportunity_id_for_finding(_row()) == CROSS_FUNCTION_ID
+ assert opportunity_id_for_finding(_local_row()) == LOCAL_ID
+
+
+ ("field", "value"),
+ [
+ ("reason", "Completely different prose about the same loop."),
+ ("line_end", 999),
+ ("id", "a-different-storage-uuid"),
+ ("severity", "high"),
+ ("health_impact", -3.5),
+ ],
+)
+def test_display_only_fields_are_outside_the_opportunity_kernel(field, value) -> None:
+ assert opportunity_id_for_finding(_row(**{field: value})) == CROSS_FUNCTION_ID
+ assert opportunity_id_for_finding(_local_row(**{field: value})) == LOCAL_ID
+
+
+ ("field", "value"),
+ [
+ ("rank_score", 99),
+ ("rank_factors", {"boundary_kind": 9}),
+ ("confidence", "low"),
+ ("dataflow_verified", True),
+ ("resource_invariant", True),
+ ("reliable_entry_reachability", True),
+ ("resolution_basis", "name-fallback"),
+ ],
+)
+def test_derived_and_ranking_details_are_outside_the_opportunity_kernel(field, value) -> None:
+ """Adding an evidence or ranking fact must never move identity.
+
+ ``resolution_basis`` is the sharp one: it feeds confidence and ranking but
+ is deliberately not an identity input, so a call-graph confidence upgrade
+ does not renumber opportunities.
+ """
+ assert opportunity_id_for_finding(_row(details={field: value})) == CROSS_FUNCTION_ID
+
+
+ ("mutate", "reason"),
+ [
+ ({"file_path": "tests/test_a.py"}, "execution context"),
+ ({"details": {"boundary_kind": "filesystem"}}, "boundary"),
+ ({"details": {"path": ["src/app/a.py::run", "src/app/db.py::other"]}}, "terminal sink"),
+ ({"biomarker_type": "membership_test_against_list_in_loop"}, "cost shape"),
+ ],
+)
+def test_cross_function_kernel_inputs_each_move_the_identity(mutate, reason) -> None:
+ assert opportunity_id_for_finding(_row(**copy.deepcopy(mutate))) != CROSS_FUNCTION_ID, reason
+
+
+def test_a_new_caller_never_changes_the_cross_function_identity() -> None:
+ """The shared cause is the identity; callers are evidence.
+
+ ``file_path``, ``function_name``, and ``line_start`` are kernel inputs for a
+ same-function observation and deliberately are not for a cross-function one.
+ """
+ original = _row()
+ other_caller = _row(file_path="src/app/b.py", function_name="other", line_start=77)
+ other_caller["details"]["path"] = ["src/app/b.py::other", "src/app/db.py::get_session"]
+ assert opportunity_id_for_finding(other_caller) == CROSS_FUNCTION_ID
+ assert len(build_performance_opportunities([original, other_caller])) == 1
+
+
+ "mutate",
+ [
+ {"file_path": "src/app/b.py"},
+ {"function_name": "other"},
+ {"line_start": 11},
+ {"biomarker_type": "nested_loop_with_io"},
+ ],
+)
+def test_local_kernel_inputs_each_move_the_identity(mutate) -> None:
+ assert opportunity_id_for_finding(_local_row(**mutate)) != LOCAL_ID
+
+
+def test_the_cost_shape_merge_applies_to_cross_function_identity_only() -> None:
+ """``io_in_loop`` and ``nested_loop_with_io`` share one cross-function cause.
+
+ The local kernel keeps the literal marker. The asymmetry is deliberate and
+ load-bearing: a split that unified the two branches would regroup the whole
+ repository.
+ """
+ nested = _row(biomarker_type="nested_loop_with_io")
+ assert opportunity_id_for_finding(nested) == CROSS_FUNCTION_ID
+ assert opportunity_id_for_finding(_local_row(biomarker_type="nested_loop_with_io")) != LOCAL_ID
+
+
[email protected]("path", [[], [5], [None]])
+def test_a_cross_function_flag_without_a_usable_path_falls_back_to_the_local_kernel(path) -> None:
+ """The flag alone does not make an observation cross-function.
+
+ Only path nodes that survive the string filter can name a terminal sink, so
+ a truthy ``cross_function`` with nothing usable in ``path`` is keyed by its
+ own location. The corpus derives the flag from the path and cannot reach
+ this branch, so it is pinned here.
+ """
+ row = _row(details={"path": path})
+ assert opportunity_id_for_finding(row) == LOCAL_ID
+
+
+def _shared_helper_rows():
+ rows = [_row(), _row(function_name="also", line_start=40)]
+ for row in rows:
+ row["details"]["path"] = [
+ "src/app/a.py::" + str(row["function_name"]),
+ "src/app/repo.py::fetch",
+ "src/app/db.py::execute",
+ ]
+ return rows
+
+
+def test_the_plan_kernel_is_the_opportunity_id_in_plan_json() -> None:
+ """One plan addresses exactly one opportunity, joined on the id string."""
+ opportunity = build_performance_opportunities(_shared_helper_rows())[0]
+ plan = performance_fix_suggestions([opportunity])[0]
+ assert plan.plan["opportunity_id"] == opportunity.opportunity_id
+
+
+def test_the_plan_id_is_absent_from_plan_evidence_today() -> None:
+ """Characterization of a live linkage hazard, not an endorsement.
+
+ ``performance_fix`` writes ``opportunity_id`` into ``plan`` only. The REST
+ route reads ``plan_json`` and links correctly; ``tool_health`` reads
+ ``suggestion.evidence`` and therefore never links, so
+ ``recommendation_lede.performance_plan_id`` is always ``None`` on a real
+ index. Pinned here so the divergence stays visible until it is fixed.
+ """
+ plan = performance_fix_suggestions(build_performance_opportunities(_shared_helper_rows()))[0]
+ assert "opportunity_id" in plan.plan
+ assert "opportunity_id" not in plan.evidence
+
+
+def test_a_performance_finding_has_no_content_derived_public_reference() -> None:
+ """The only stable public key on a performance finding is its group id.
+
+ ``evidence[].finding_id`` is the storage row id: empty in memory, a random
+ UUID once persisted. Nothing joins on it across a reindex, so it is not
+ an identity.
+ """
+ in_memory = _row()
+ del in_memory["id"]
+ opportunity = build_performance_opportunities([in_memory])[0]
+ assert opportunity.evidence[0]["finding_id"] == ""
+
+ persisted = _row(id="8f14e45fceea167a5a36dedd4bea2543")
+ assert build_performance_opportunities([persisted])[0].evidence[0]["finding_id"] == (
+ "8f14e45fceea167a5a36dedd4bea2543"
+ )
+ link_performance_findings([persisted])
+ assert persisted["details"]["opportunity_id"] == CROSS_FUNCTION_ID