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.

fix(health): name performance work in Fix first and Do next only when its cost is confirmed (#4227)

Raghav Chamadiya09b21703a475
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 69e962c4b..73f1d671a 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -701,7 +701,8 @@ reason. These reasons and the performance default queue's are decided in one pla
|---|---|
| `test`, `tooling`, `generated`, `vendored`, `docs_example` | Path-role classification. Tooling includes build files by type wherever they sit (Gradle, CMake, Makefiles, Bazel, MSBuild props/targets, root `setup.py`, `noxfile.py`, crate-root `build.rs`, bundler configs). Docs means a root `docs/` or `docs_src/` tree, or one beside a docs-site config; a product's own `app/docs/` route is production |
| `unknown`, `expected`, `no_strategy`, `no_plan` | Performance causes with no classified context, expected repetition, no supported strategy, or no stored safe plan |
-| `below_min_worth` | A refactoring recovering under `MIN_WORTH` (0.5) or with no steps; a loop-built string that is bounded or not in production |
+| `below_min_worth` | A refactoring recovering under `MIN_WORTH` (0.5) or with no steps |
+| `unmeasured_cost`, `cold_role`, `background_unproven`, `unconfirmed_cost` | Performance causes the default queue drops, and queued causes `perf_confident_verdict` does not confirm: growth only a registry or cold-path loop shows, or no known role and no entry point reaching it |
| `history_only` | Only git-history findings |
| `deprecated` | Deprecated functions |
| `gated_off` | Functions a same-file constant-false flag switches off (`complexity/gating.py`): the body opens with `if not FLAG: return` or is one `if FLAG:` block. For performance this is the opportunity state `expected` with reason `gated_off`, and the default queue counts it under `gated_off`. `totals.dormant` counts the distinct functions |
@@ -777,7 +778,10 @@ The default queue holds production `plan_ready` and `advisory` with
`cost_proof = proven`, ranked by `rank_score`; actionability only breaks ties.
Excluded reasons are counted in `default_queue`. A cause whose loop size nothing
measured is stored as `cost_proof = unproven`: it never leads, and the `proof`
-filter and facet expose it.
+filter and facet expose it. Fix first, Do next and the queue's lead take only the
+queued `plan_ready` causes `queue.eligibility.perf_confident_verdict` confirms
+(facet `growth_source = loop`); advisory causes measured 0 true of 14 on three
+repositories, so they stay in the queue.
**Plans.** Proven means the transformation, not the runtime: parallelizing awaits
against a DB or network client is advisory with a `bounded_concurrency`
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.md
index 9ab91ec20..0dba20fca 100644
--- a/docs/layers/PERFORMANCE.md
+++ b/docs/layers/PERFORMANCE.md
@@ -126,7 +126,11 @@ like an example tree (`com/example/...`) is judged as production when the index
read it as production.
Performance work also appears in [Fix first](CODE_HEALTH.md#fix-first), where it
-competes with other kinds of work.
+competes with other kinds of work. Fix first, Do next and the queue's lead name only
+a `plan_ready` default-queue cause whose growth a loop outside a registry and a cold path shows
+(facet `growth_source = loop`) and, when no role is known, that an entry point reaches.
+Every other cause stays in the Performance view and is counted in Fix first as
+`unconfirmed_cost`.
## Reading it
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 70a3c874e..43f9ea14b 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -427,7 +427,7 @@ Performance findings carry `health_impact: 0`; the pillar never blends into the
A bare `get_health()` ranks performance work inside `fix_first` as `perf_fix` items. `get_health(opportunity_id="perf...")` adds `plan_steps`, `validation` and `siblings`; `only=["performance_evidence"]` with `cursor` pages the evidence. Ids are stable within a performance model version; an id from an older model resolves to `model_state.state: "stale_model"` with `refresh_required`. `lifecycle_status` is `open` or `resolved`. Evidence rows carry a public `finding_id`.
-The `performance_opportunities` list holds causes whose cost is measured (`cost_proof` `proven`). A cause whose loop size nothing measured is `unproven`: it never sets `may_lead`, and every list leaves it out. `performance_summary.default_queue.excluded.unmeasured_cost` counts the ones the default queue drops, `performance_summary.proof` counts both values, and the `proof` facet counts them under the current filters. REST lists them with `proof=unproven` on `/api/repos/{id}/health/performance-opportunities`.
+The `performance_opportunities` list holds causes whose cost is measured (`cost_proof` `proven`). A cause whose loop size nothing measured is `unproven`: it never sets `may_lead`, and every list leaves it out. `performance_summary.default_queue.excluded.unmeasured_cost` counts the ones the default queue drops, `performance_summary.proof` counts both values, and the `proof` facet counts them under the current filters. REST lists them with `proof=unproven` on `/api/repos/{id}/health/performance-opportunities`. The `growth_source` facet names the member loop that shows the cost grows (`loop`, `registry`, `cold_path`, `none`, `n/a`); `fix_first`, Do next and `performance_summary.lead` take only `plan_ready` causes with `loop` (or a per-call cause an entry point reaches), and `fix_first.totals.excluded.unconfirmed_cost` counts the rest.
### Coverage
diff --git a/packages/core/src/repowise/core/analysis/actions/build.py b/packages/core/src/repowise/core/analysis/actions/build.py
index d0da80979..a59ddd11f 100644
--- a/packages/core/src/repowise/core/analysis/actions/build.py
+++ b/packages/core/src/repowise/core/analysis/actions/build.py
@@ -33,7 +33,8 @@ Row shapes (the field names are the SQL columns):
One mapping of the Fix-first builder's own inputs (``metrics``,
``findings``, ``refactoring``, ``performance``, ``plans``); shapes in
``repowise.core.analysis.health.fix_first.build``. The recent findings
- also read ``performance`` rows' ``queue_eligible`` and ``cost_proof``.
+ also read ``performance`` rows' ``queue_eligible`` and the fields
+ ``perf_confident_verdict`` reads.
``security``
``file_path``, ``kind``, ``line_number``, ``snippet``, ``severity``,
``commit_sha`` (empty for the working tree).
@@ -68,6 +69,7 @@ from repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDS
from repowise.core.analysis.finding_registry import excluded_types, is_served
from repowise.core.analysis.health.fix_first import build_fix_first
from repowise.core.analysis.health.models import primary_finding, split_by_origin
+from repowise.core.analysis.health.queue.eligibility import perf_confident_verdict
from repowise.core.analysis.health.rows import field
from repowise.core.analysis.health.scoring import HISTORY_CATEGORY, biomarker_category
from repowise.core.author_identity import author_identity_key
@@ -335,14 +337,13 @@ def _recent_candidates(
def proven_performance(rows: Rows) -> frozenset[tuple[str, str]]:
- """``(file, marker)`` of each open performance cause in the default queue
- whose cost is proven to grow: the bar a performance regression clears."""
+ """``(file, marker)`` of each open performance cause stored in the default
+ queue that is sure enough to be told to do (``perf_confident_verdict``):
+ the bar a performance regression clears."""
return frozenset(
(field(r, "file_path"), field(r, "biomarker_type"))
for r in rows
- if _open(r)
- and field(r, "queue_eligible") is True
- and (field(r, "cost_proof") or "proven") == "proven"
+ if _open(r) and field(r, "queue_eligible") is True and perf_confident_verdict(r).eligible
)
diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/model.py b/packages/core/src/repowise/core/analysis/health/fix_first/model.py
index 78d997efc..e9e06bf40 100644
--- a/packages/core/src/repowise/core/analysis/health/fix_first/model.py
+++ b/packages/core/src/repowise/core/analysis/health/fix_first/model.py
@@ -40,9 +40,11 @@ FIX_FACT_BASES: tuple[str, ...] = get_args(FixFactBasis)
# The reasons Fix first's ladders produce, from the one vocabulary in
# ``queue.eligibility.Reason``. ``unknown``, ``gated_off``, ``cold_path``,
-# ``expected`` and ``no_strategy`` come from the performance ladder; ``gated_off``
-# also keeps out any other unit in a function a constant-false flag switches
-# off. ``unreachable``: an open dead-code finding covers the target.
+# ``expected`` and ``no_strategy`` come from the performance ladder, with the
+# queue's ``unmeasured_cost``, ``cold_role``, ``background_unproven`` and
+# ``unconfirmed_cost``; ``gated_off`` also keeps out any other unit in a
+# function a constant-false flag switches off. ``unreachable``: an open
+# dead-code finding covers the target.
# ``terminal_flow``: a print or prompt flow; ``moderate_quiet``: a function
# under the large-size bar with no churn or bug-fix history.
FixExclusion = Literal[
@@ -68,6 +70,10 @@ FixExclusion = Literal[
"kind_unaudited",
"terminal_flow",
"moderate_quiet",
+ "unmeasured_cost",
+ "cold_role",
+ "background_unproven",
+ "unconfirmed_cost",
]
FIX_EXCLUSIONS: tuple[str, ...] = get_args(FixExclusion)
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 6a18dc201..4bbe4af57 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
@@ -57,6 +57,7 @@ from .opportunity_rank import (
change_risk,
dominant_marker,
exposure,
+ growth_source,
leverage,
loop_magnitude,
may_lead,
@@ -175,6 +176,7 @@ class _Reading:
role: str
sinks: tuple[str, ...]
magnitude: str
+ growth: str
def _read_live(members: list[Any]) -> _Reading:
@@ -190,6 +192,7 @@ def _read_live(members: list[Any]) -> _Reading:
marker = dominant_marker(markers)
sites = {facts.site for facts in live}
role = hottest_role(facts.execution_role for facts in live)
+ owners = [f for f in live if hottest_role((f.execution_role,)) == role]
return _Reading(
live=live,
markers=markers,
@@ -200,9 +203,8 @@ def _read_live(members: list[Any]) -> _Reading:
reachable=_reachability({facts.reliable_entry_reachability for facts in live}),
role=role,
sinks=tuple(sorted({facts.terminal_sink for facts in live if facts.terminal_sink})),
- magnitude=loop_magnitude(
- marker, [f.details for f in live if hottest_role((f.execution_role,)) == role]
- ),
+ magnitude=loop_magnitude(marker, [f.details for f in owners]),
+ growth=growth_source(marker, owners),
)
@@ -214,6 +216,7 @@ def _facets(r: _Reading, confidence: str) -> dict[str, str]:
"leverage": leverage(len(r.sites)),
"change_risk": change_risk(len(r.files)),
"loop_magnitude": r.magnitude,
+ "growth_source": r.growth,
"execution_role": r.role,
}
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
index a4b6b8fc0..ac5d1a7e2 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py
@@ -18,11 +18,12 @@ from __future__ import annotations
from collections.abc import Mapping
from math import log2
-from typing import Any
+from typing import Any, Literal, get_args
from ...execution_roles import COLD_ROLES
from ..rank_common import top_factors, weakest
from ..worth import lead_reason
+from .cold_paths import is_cold_path
BOUNDARY_POINTS = {"subprocess": 5, "network": 4, "db": 4, "lock": 3, "filesystem": 2}
"""What one crossing of each boundary costs, as an order of magnitude.
@@ -195,6 +196,36 @@ def loop_magnitude(marker: str, details: list[dict[str, Any]]) -> str:
return "bounded" if values == {"bounded"} else "unknown"
+GrowthSource = Literal["loop", "registry", "cold_path", "none", "n/a"]
+GROWTH_SOURCES: tuple[str, ...] = get_args(GrowthSource)
+
+
+def growth_source(marker: str, members: list[Any]) -> GrowthSource:
+ """Which member loop shows the group's cost grows, read off the members
+ :func:`loop_magnitude` reads.
+
+ ``loop``: a loop whose read grows, outside a registry and a cold path.
+ ``registry``: only loops over a registry or configuration table grow,
+ which a name says and nothing measures. ``cold_path``: only loops in
+ migration, startup or recovery code grow (:mod:`.cold_paths`).
+ """
+ if amplification(marker) not in {"per_iteration", "quadratic"}:
+ return "n/a"
+ found: set[str] = set()
+ for facts in members:
+ if facts.details.get("loop_magnitude") != "grows_with_data":
+ continue
+ if facts.details.get("loop_iterates") == "config_table":
+ found.add("registry")
+ elif is_cold_path(facts.file_path, facts.function_name):
+ found.add("cold_path")
+ else:
+ return "loop"
+ if "registry" in found:
+ return "registry"
+ return "cold_path" if found else "none"
+
+
def exposure(reachable: bool | None) -> str:
"""How closely an entry point reaches this group.
@@ -294,6 +325,7 @@ __all__ = [
"BOUNDARY_POINTS",
"CONTEXT_POINTS",
"CROSS_FUNCTION_POINTS",
+ "GROWTH_SOURCES",
"LEADING_ORMS",
"MAGNITUDE_POINTS",
"MULTIPLIER_POINTS",
@@ -301,11 +333,13 @@ __all__ = [
"PROVENANCE_POINTS",
"ROLE_POINTS",
"UNKNOWN_MULTIPLIER_POINTS",
+ "GrowthSource",
"amplification",
"band",
"change_risk",
"dominant_marker",
"exposure",
+ "growth_source",
"leverage",
"loop_magnitude",
"may_lead",
diff --git a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py b/packages/core/src/repowise/core/analysis/health/queue/eligibility.py
index 264423c17..98455c357 100644
--- a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py
+++ b/packages/core/src/repowise/core/analysis/health/queue/eligibility.py
@@ -62,6 +62,7 @@ Reason = Literal[
"unmeasured_cost",
"cold_role",
"background_unproven",
+ "unconfirmed_cost",
"terminal_flow",
"moderate_quiet",
]
@@ -431,10 +432,6 @@ QUEUE_ROLES = frozenset(EXECUTION_ROLES) - COLD_ROLES
"""Execution roles the performance queue holds; a scheduled job also needs
proven growth. ``unknown`` is no evidence either way, so it stays."""
-#: Causes whose cost is real only in shipped code over a loop that grows: a
-#: string built in a bounded loop, or in a script, costs nothing a user sees.
-GROWS_ONLY_MARKERS = frozenset({"string_concat_in_loop"})
-
def perf_strategy_verdict(
item: Any, contexts: frozenset[str] = DEFAULT_QUEUE_CONTEXTS
@@ -443,9 +440,7 @@ def perf_strategy_verdict(
Reads an opportunity, an ORM row or a plain row. *contexts* widens it for a
caller that asked for more (Fix first's ``scope="all"`` keeps test code);
- the state rule never moves. Fix first reads this rather than
- :func:`perf_queue_verdict` because it keeps an unproven cause, as a
- ``later`` item.
+ the state rule never moves.
"""
context = field(item, "execution_context")
if context not in contexts:
@@ -489,18 +484,55 @@ def queue_proof(item: Any) -> QueueProof:
return proof
-def perf_queue_verdict(item: Any) -> Verdict:
+def perf_queue_verdict(item: Any, contexts: frozenset[str] = DEFAULT_QUEUE_CONTEXTS) -> Verdict:
"""Whether the performance default queue holds *item*.
One reason per cause, context first and role last, so the counts of every
reason and the queue add up to the whole.
"""
- verdict = perf_strategy_verdict(item)
+ verdict = perf_strategy_verdict(item, contexts)
if verdict.eligible and cost_proof(item) not in DEFAULT_QUEUE_PROOFS:
return Verdict("unmeasured_cost")
return verdict if not verdict.eligible else _verdict(_role_reason(item))
+def _unconfirmed(item: Any) -> bool:
+ """Whether nothing but a name or a guess says a queued cause costs anything.
+
+ Its cost must be one that may lead (:func:`worth.lead_reason`); a loop's
+ growth must come from a loop outside a registry and a cold path
+ (``opportunity_rank.growth_source``, absent on rows stored before it); and
+ with no known role, an entry point must reach it. Only a ``plan_ready``
+ cause qualifies.
+ """
+ # Deliberate ceiling: advisory causes in the default queue labelled 0 TRUE
+ # of 14 on our index, dify-api and polar-server (2026-10-19). Admit
+ # advisory once a blind held-out sample of it clears 90%.
+ if field(item, "actionability_state") != "plan_ready":
+ return True
+ facets = perf_facets(item)
+ if lead_reason(field(item, "biomarker_type"), facets) is not None:
+ return True
+ if facets.get("loop_magnitude") == "grows_with_data" and facets.get("growth_source") != "loop":
+ return True
+ return execution_role(item) == "unknown" and facets.get("exposure") != "entry_reachable"
+
+
+def perf_confident_verdict(
+ item: Any, contexts: frozenset[str] = DEFAULT_QUEUE_CONTEXTS
+) -> Verdict:
+ """Whether *item* is a cause sure enough to be told to do: the only
+ performance work Fix first, Do next and the queue's lead name.
+
+ A default-queue cause (:func:`perf_queue_verdict`) that :func:`_unconfirmed`
+ clears; the rest stay listed in the performance queue.
+ """
+ verdict = perf_queue_verdict(item, contexts)
+ if verdict.eligible and _unconfirmed(item):
+ return Verdict("unconfirmed_cost")
+ return verdict
+
+
def perf_queue_counts(items: Iterable[Any]) -> dict[str, Any]:
"""The performance default queue's size and what it leaves out, by reason."""
tally = Tally(DEFAULT_QUEUE_EXCLUSIONS)
@@ -524,37 +556,32 @@ def _has_plan(row: Any) -> bool:
return field(row, "plan_state") == "available" and bool(field(row, "fix_strategy"))
-def _perf_worth(row: Any) -> bool:
- """Whether a planned cause is worth an item at all."""
- return field(row, "biomarker_type") not in GROWS_ONLY_MARKERS or perf_low_priority(row) is None
-
-
def perf_fix_verdict(
rows: list[Any], contexts: frozenset[str], unreachable: Callable[[], bool]
) -> tuple[Verdict, list[Any]]:
"""Whether the causes one intervention groups make a Fix first item, and
the rows worth one.
- The performance queue's context and actionability rule decides which
- causes are work; an unproven cost stays in, tiered later by
- :func:`perf_low_priority`. An item needs a stored plan to quote.
- ``unreachable()`` says whether dead code covers the intervention.
+ Only a confident cause (:func:`perf_confident_verdict`) is work here. An
+ item needs a stored plan to quote. ``unreachable()`` says whether dead
+ code covers the intervention.
"""
- verdicts = [perf_strategy_verdict(r, contexts) for r in rows]
- queued = [r for r, v in zip(rows, verdicts, strict=True) if v.eligible]
- ready = [r for r in queued if _has_plan(r)]
+ # A row with no plan is judged on strategy alone: its facets are not loaded,
+ # and it is no item either way, so it counts as ``no_plan``.
+ verdicts = [
+ perf_confident_verdict(r, contexts) if _has_plan(r) else perf_strategy_verdict(r, contexts)
+ for r in rows
+ ]
+ ready = [r for r, v in zip(rows, verdicts, strict=True) if v.eligible and _has_plan(r)]
if not ready:
- if queued:
+ if any(v.eligible for v in verdicts):
return Verdict("no_plan"), []
# Dormant only when every row is: one live row speaks for the group.
live = [v for v in verdicts if v.reason != "gated_off"]
return (live[0] if live else Verdict("gated_off")), []
- worth = [r for r in ready if _perf_worth(r)]
- if not worth:
- return Verdict("below_min_worth"), []
if unreachable():
return Verdict("unreachable"), []
- return ELIGIBLE, worth
+ return ELIGIBLE, ready
__all__ = [
@@ -564,7 +591,6 @@ __all__ = [
"DEFAULT_QUEUE_PROOFS",
"DEFAULT_QUEUE_STATES",
"ELIGIBLE",
- "GROWS_ONLY_MARKERS",
"LOW_VALUE_DETAIL_KINDS",
"LOW_VALUE_KINDS",
"MIN_WORTH",
@@ -586,6 +612,7 @@ __all__ = [
"dead_target",
"finding_verdict",
"path_verdict",
+ "perf_confident_verdict",
"perf_fix_verdict",
"perf_low_priority",
"perf_queue_counts",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
index 153c0761a..788155e3a 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
@@ -249,23 +249,28 @@ async def _recent(
async def _proven_performance(session: AsyncSession, repo_id: str, paths: set[str]) -> list[Any]:
- """The queue's open causes in ``paths``; none when the store cannot be
- read, which costs only the performance regressions, not the week's rest."""
+ """The queue's open causes in ``paths``, with what ``perf_confident_verdict``
+ reads; none when the store cannot be read, which costs only the
+ performance regressions, not the week's rest."""
+ p = PerformanceOpportunity
try:
async with session.begin_nested():
return (
await session.execute(
select(
- PerformanceOpportunity.file_path,
- PerformanceOpportunity.biomarker_type,
- PerformanceOpportunity.status,
- PerformanceOpportunity.queue_eligible,
- PerformanceOpportunity.cost_proof,
+ p.file_path,
+ p.biomarker_type,
+ p.status,
+ p.queue_eligible,
+ p.execution_context,
+ p.actionability_state,
+ p.execution_role,
+ p.details_json,
).where(
- PerformanceOpportunity.repository_id == repo_id,
- PerformanceOpportunity.status == "open",
- PerformanceOpportunity.queue_eligible.is_(True),
- PerformanceOpportunity.file_path.in_(paths),
+ p.repository_id == repo_id,
+ p.status == "open",
+ p.queue_eligible.is_(True),
+ p.file_path.in_(paths),
)
)
).all()
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
index 8712ebb55..0a4f29537 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
@@ -160,8 +160,8 @@ def _summary_payload(
"""The compact current headline, written once and read by primary key."""
from ....analysis.health.perf.serving import intervention_file
from ....analysis.health.queue.eligibility import (
+ perf_confident_verdict,
perf_queue_counts,
- perf_queue_verdict,
queue_proof,
)
@@ -176,14 +176,10 @@ def _summary_payload(
boundaries[key] = boundaries.get(key, 0) + 1
proof = queue_proof(item)
proofs[proof] = proofs.get(proof, 0) + 1
- # The lead is the head of the default queue, so it is production work with a
- # strategy; never a marker whose measured precision is below the bar for leading.
+ # The lead is the first confident cause of the default queue; never a marker
+ # whose measured precision is below the bar for leading.
lead = next(
- (
- o
- for o in opportunities
- if perf_queue_verdict(o).eligible and o.may_lead
- ),
+ (o for o in opportunities if perf_confident_verdict(o).eligible and o.may_lead),
None,
)
return {
diff --git a/packages/types/src/fix-first.ts b/packages/types/src/fix-first.ts
index 052d96e47..538315e56 100644
--- a/packages/types/src/fix-first.ts
+++ b/packages/types/src/fix-first.ts
@@ -47,7 +47,11 @@ export type FixExclusion =
| "low_value_kind"
| "kind_unaudited"
| "terminal_flow"
- | "moderate_quiet";
+ | "moderate_quiet"
+ | "unmeasured_cost"
+ | "cold_role"
+ | "background_unproven"
+ | "unconfirmed_cost";
/** `all` keeps test files, labelled in `context`. */
export type FixScope = "production" | "all";
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index e272b6ee9..a49075ce4 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -435,6 +435,13 @@ export interface PerformanceWhyRanked {
*/
export type PerformanceLoopMagnitude = "grows_with_data" | "bounded" | "unknown" | "n/a";
+/**
+ * Which member loop shows the cost grows: `loop` one outside a registry and a
+ * cold path, `registry` only loops over a registry or configuration table,
+ * `cold_path` only migration, startup or recovery loops, `none` no loop grows.
+ */
+export type PerformanceGrowthSource = "loop" | "registry" | "cold_path" | "none" | "n/a";
+
/**
* The facets that are not published anywhere else on the row.
* `confidence` stays evidence confidence and `fix.safety` stays fix safety,
@@ -449,6 +456,8 @@ export interface PerformanceOpportunityFacets {
/** Absent on rows stored before the fact existed. */
loop_magnitude?: PerformanceLoopMagnitude;
/** Absent on rows stored before the fact existed. */
+ growth_source?: PerformanceGrowthSource;
+ /** Absent on rows stored before the fact existed. */
execution_role?: PerformanceExecutionRole;
}
diff --git a/packages/types/src/queue.ts b/packages/types/src/queue.ts
index a85cf5ee0..4a3ff73bc 100644
--- a/packages/types/src/queue.ts
+++ b/packages/types/src/queue.ts
@@ -33,6 +33,7 @@ export type QueueReason =
| "unmeasured_cost"
| "cold_role"
| "background_unproven"
+ | "unconfirmed_cost"
| "terminal_flow"
| "moderate_quiet"
| "not_judged"
diff --git a/packages/ui/__tests__/health/fixtures/fix-first.ts b/packages/ui/__tests__/health/fixtures/fix-first.ts
index d1c9db983..1223dbc93 100644
--- a/packages/ui/__tests__/health/fixtures/fix-first.ts
+++ b/packages/ui/__tests__/health/fixtures/fix-first.ts
@@ -629,7 +629,11 @@ export const FIX_FIRST_QUEUE: FixFirstQueue = {
"low_value_kind": 0,
"kind_unaudited": 0,
"terminal_flow": 0,
- "moderate_quiet": 0
+ "moderate_quiet": 0,
+ "unmeasured_cost": 0,
+ "cold_role": 0,
+ "background_unproven": 0,
+ "unconfirmed_cost": 0
},
"dormant": 0
},
diff --git a/packages/ui/src/health/fix-first/scope.ts b/packages/ui/src/health/fix-first/scope.ts
index d842ac046..4c5236956 100644
--- a/packages/ui/src/health/fix-first/scope.ts
+++ b/packages/ui/src/health/fix-first/scope.ts
@@ -53,6 +53,10 @@ export const EXCLUSION_LABEL: Record<FixExclusion, string> = {
kind_unaudited: "of a kind not yet audited for this list",
terminal_flow: "print and prompt flows",
moderate_quiet: "moderate functions that rarely change or break",
+ unmeasured_cost: "performance causes whose loop is not shown to grow",
+ cold_role: "performance causes only startup, a CLI, tooling or tests run",
+ background_unproven: "scheduled-job causes not shown to grow",
+ unconfirmed_cost: "performance causes whose cost rests on a name or a guess",
};
const EXCLUSION_ORDER: FixExclusion[] = [
@@ -78,6 +82,10 @@ const EXCLUSION_ORDER: FixExclusion[] = [
"kind_unaudited",
"terminal_flow",
"moderate_quiet",
+ "unmeasured_cost",
+ "cold_role",
+ "background_unproven",
+ "unconfirmed_cost",
];
/**
diff --git a/packages/web/src/components/code-health/fix-first-section.test.tsx b/packages/web/src/components/code-health/fix-first-section.test.tsx
index d356906af..980892919 100644
--- a/packages/web/src/components/code-health/fix-first-section.test.tsx
+++ b/packages/web/src/components/code-health/fix-first-section.test.tsx
@@ -80,6 +80,10 @@ function queue(items: FixItem[]): FixFirstQueue {
kind_unaudited: 0,
terminal_flow: 0,
moderate_quiet: 0,
+ unmeasured_cost: 0,
+ cold_role: 0,
+ background_unproven: 0,
+ unconfirmed_cost: 0,
},
dormant: 0,
},
diff --git a/tests/fixtures/perf_corpus/golden_opportunities.json b/tests/fixtures/perf_corpus/golden_opportunities.json
index c477397b9..ffe36a552 100644
--- a/tests/fixtures/perf_corpus/golden_opportunities.json
+++ b/tests/fixtures/perf_corpus/golden_opportunities.json
@@ -58,6 +58,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "entry_reachable",
+ "growth_source": "none",
"leverage": "local",
"loop_magnitude": "unknown"
},
@@ -168,6 +169,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "local",
"loop_magnitude": "unknown"
},
@@ -258,6 +260,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "loop",
"leverage": "isolated",
"loop_magnitude": "grows_with_data"
},
@@ -372,6 +375,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "entry_reachable",
+ "growth_source": "none",
"leverage": "local",
"loop_magnitude": "unknown"
},
@@ -480,6 +484,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "local",
"loop_magnitude": "unknown"
},
@@ -584,6 +589,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "entry_reachable",
+ "growth_source": "none",
"leverage": "local",
"loop_magnitude": "unknown"
},
@@ -693,6 +699,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "entry_reachable",
+ "growth_source": "none",
"leverage": "local",
"loop_magnitude": "unknown"
},
@@ -802,6 +809,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "local",
"loop_magnitude": "unknown"
},
@@ -895,6 +903,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -984,6 +993,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1067,6 +1077,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1152,6 +1163,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1239,6 +1251,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1331,6 +1344,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1420,6 +1434,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1504,6 +1519,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1591,6 +1607,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "not_entry_reachable",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1684,6 +1701,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "not_entry_reachable",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1777,6 +1795,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "not_entry_reachable",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1867,6 +1886,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -1947,6 +1967,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2027,6 +2048,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2156,6 +2178,7 @@
"change_risk": "moderate",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "shared",
"loop_magnitude": "unknown"
},
@@ -2239,6 +2262,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "bounded"
},
@@ -2320,6 +2344,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2413,6 +2438,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2506,6 +2532,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2599,6 +2626,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2685,6 +2713,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2771,6 +2800,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2862,6 +2892,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -2940,6 +2971,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -3018,6 +3050,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
@@ -3103,6 +3136,7 @@
"change_risk": "contained",
"execution_role": "unknown",
"exposure": "unknown",
+ "growth_source": "none",
"leverage": "isolated",
"loop_magnitude": "unknown"
},
diff --git a/tests/unit/analysis/test_actions_rules.py b/tests/unit/analysis/test_actions_rules.py
index 3501a13b1..bd91353cb 100644
--- a/tests/unit/analysis/test_actions_rules.py
+++ b/tests/unit/analysis/test_actions_rules.py
@@ -365,7 +365,7 @@ def _fix_items():
from repowise.core.analysis.health.fix_first import build_fix_first
from tests.unit.health import fix_first_rows as rows
- return build_fix_first(
+ items = build_fix_first(
metrics=rows.METRICS,
findings=rows.FINDINGS,
refactoring=rows.REFACTORING,
@@ -373,6 +373,8 @@ def _fix_items():
plans=rows.PLANS,
limit=3,
).items
+ # The rules read the tier as given: the perf item stands in for a next one.
+ return (replace(items[0], tier="next"), *items[1:])
def test_fix_first_emits_now_and_next_and_leaves_later() -> None:
diff --git a/tests/unit/health/fix_first_rows.py b/tests/unit/health/fix_first_rows.py
index 2537d1f70..53253a638 100644
--- a/tests/unit/health/fix_first_rows.py
+++ b/tests/unit/health/fix_first_rows.py
@@ -103,13 +103,14 @@ def _perf(opp: str, sink: str, **over) -> dict:
"opportunity_id": opp, "rank_position": 0, "rank_score": 20,
"execution_context": "production", "execution_role": "request", "boundary_kind": "db",
"biomarker_type": "io_in_loop",
- "actionability_state": "advisory", "plan_state": "available",
+ "actionability_state": "plan_ready", "plan_state": "available",
"fix_strategy": "batch_or_prefetch_io", "fix_safety": "advisory",
"file_path": "src/repo.py", "intervention_symbol": "src/repo.py::load_all",
"terminal_sink": sink, "affected_call_sites_total": 3, "affected_files_total": 2,
"details": {
"facets": {"exposure": "entry_reachable", "loop_magnitude": "grows_with_data",
- "amplification": "per_iteration", "actionability_confidence": "medium"},
+ "growth_source": "loop", "amplification": "per_iteration",
+ "actionability_confidence": "medium"},
"plan": {"effort_bucket": "M", "steps": [
{"order": 1, "action": "Collect the keys before the loop", "symbol": "load_all",
"file_path": "src/repo.py", "line": 12, "applicability": "judgment"}]},
diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.py
index 9b6600120..06e608e3a 100644
--- a/tests/unit/health/test_fix_first_build.py
+++ b/tests/unit/health/test_fix_first_build.py
@@ -64,6 +64,10 @@ def test_each_exclusion_is_counted_by_reason() -> None:
"kind_unaudited": 0,
"terminal_flow": 0,
"moderate_quiet": 0,
+ "unmeasured_cost": 0,
+ "cold_role": 0,
+ "background_unproven": 0,
+ "unconfirmed_cost": 0,
}
assert queue.totals.dormant == 0
assert queue.totals.eligible == 3
@@ -126,7 +130,7 @@ def test_an_excluded_plan_leaves_the_files_findings_to_compete() -> None:
def test_tiers_follow_value_confidence_and_readiness() -> None:
by_kind = {i.kind: i for i in _build().items}
assert by_kind["refactor"].tier == "now"
- assert by_kind["perf_fix"].tier == "next" # advisory plan: needs judgment
+ assert by_kind["perf_fix"].tier == "now" # a plan-ready cause with a proven plan
assert by_kind["finding"].tier == "later"
assert all(i.why_ranked[-1].factor == "tier" for i in by_kind.values())
@@ -157,10 +161,13 @@ def test_no_kind_takes_more_than_three_of_the_first_five() -> None:
row["file_path"] = f"src/core{n}.py"
row["details"]["steps"] = row["details"]["steps"][:1]
refactors.append(row)
- # A loop that grows but no request, message or job is known to run:
- # worth doing, ranked below the refactors' value.
+ # A loop that grows, reached from an entry point, but no request, message
+ # or job is known to run: worth doing, ranked below the refactors' value.
perf = _perf("perf2_a", "s", execution_role="unknown")
- perf["details"] = {**perf["details"], "facets": {"loop_magnitude": "grows_with_data"}}
+ perf["details"] = {**perf["details"], "facets": {
+ "loop_magnitude": "grows_with_data", "growth_source": "loop",
+ "exposure": "entry_reachable",
+ }}
queue = _build(refactoring=refactors, performance=[perf], findings=[])
# The fourth place goes to the perf fix; the fifth back to a refactor,
# since no other kind has anything left at value 2 or above.
diff --git a/tests/unit/health/test_fix_first_closeout.py b/tests/unit/health/test_fix_first_closeout.py
index 863a4dc8c..b3c5ec72b 100644
--- a/tests/unit/health/test_fix_first_closeout.py
+++ b/tests/unit/health/test_fix_first_closeout.py
@@ -125,7 +125,8 @@ def _validated(magnitude: str, via: str, dependents: int) -> FixFirstQueue:
@pytest.mark.parametrize("magnitude", ["n/a", "grows_with_data", "unknown"])
def test_no_text_field_carries_an_internal_token(via: str, magnitude: str) -> None:
queue = _validated(magnitude, via, dependents=1)
- assert len(queue.items) == 2
+ # A loop nobody measured is no item: only the finding is left to read.
+ assert len(queue.items) == (1 if magnitude == "unknown" else 2)
for item in queue.items:
for line in _texts(item):
assert not _RAW.search(line), line
diff --git a/tests/unit/health/test_fix_first_precision.py b/tests/unit/health/test_fix_first_precision.py
index 4f0db975f..c2503240a 100644
--- a/tests/unit/health/test_fix_first_precision.py
+++ b/tests/unit/health/test_fix_first_precision.py
@@ -294,58 +294,51 @@ def _perf_queue(*rows):
def test_string_concat_needs_a_loop_that_grows() -> None:
assert len(_perf_queue(_concat()).items) == 1
- for magnitude in ("bounded", "unknown"):
+ for magnitude, reason in (("bounded", "unconfirmed_cost"), ("unknown", "unmeasured_cost")):
queue = _perf_queue(_concat(loop_magnitude=magnitude))
- assert queue.items == () and queue.totals.excluded["below_min_worth"] == 1
+ assert queue.items == () and queue.totals.excluded[reason] == 1
-def test_other_causes_keep_an_unknown_loop() -> None:
- from tests.unit.health.fix_first_rows import _perf
-
- row = _perf("perf3_db", "src/db.py::fetch")
- row["details"] = {**row["details"], "facets": {"loop_magnitude": "unknown"}}
- assert len(_perf_queue(row).items) == 1
+# --- F8: only a cause we are sure of is an item --------------------------------------
+_GROWS = {"loop_magnitude": "grows_with_data", "growth_source": "loop"}
-# --- F8: unknown loops no request, message or job runs ------------------------------
-
-def _value(role: str = "unknown", **facets) -> str:
+def _row(role: str, facets: dict) -> dict:
from tests.unit.health.fix_first_rows import _perf
row = _perf("perf3_v", "src/db.py::fetch", execution_role=role)
row["details"] = {**row["details"], "facets": facets}
- item = _perf_queue(row).lead
+ return row
+
+
+def _value(role: str = "unknown", **facets) -> str:
+ item = _perf_queue(_row(role, facets)).lead
return next(f.value for f in item.why_ranked if f.factor in ("value", "value within later"))
-def test_only_a_loop_known_to_grow_leads() -> None:
- from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL
- from tests.unit.health.fix_first_rows import _perf
+def _excluded(role: str = "unknown", **facets) -> dict:
+ queue = _perf_queue(_row(role, facets))
+ assert queue.items == ()
+ return {k: n for k, n in queue.totals.excluded.items() if n}
- def lead(**facets):
- row = _perf("perf3_t", "src/db.py::fetch")
- row["details"] = {**row["details"], "facets": facets}
- return _perf_queue(row).lead
- unknown = lead(loop_magnitude="unknown", exposure="entry_reachable")
- assert unknown.tier == "later"
- assert ("tier", LOW_PRIORITY_LABEL["unmeasured_cost"]) in [
- (f.factor, f.value) for f in unknown.why_ranked
- ]
- assert lead(loop_magnitude="grows_with_data").tier != "later"
+def test_an_unmeasured_loop_is_never_an_item() -> None:
+ for role in ("request", "unknown"):
+ for reach in ("entry_reachable", "unknown"):
+ assert _excluded(role, loop_magnitude="unknown", exposure=reach) == {
+ "unmeasured_cost": 1
+ }
-def test_an_unknown_loop_no_hot_role_runs_drops_a_step() -> None:
- assert _value(loop_magnitude="unknown") == "0"
- # A name-derived entry point no longer counts: only the role does.
- assert _value(loop_magnitude="unknown", exposure="entry_reachable") == "0"
+def test_growth_only_a_registry_or_a_migration_shows_is_never_an_item() -> None:
+ for source in ("registry", "cold_path", None):
+ facets = {**_GROWS, "growth_source": source, "exposure": "entry_reachable"}
+ assert _excluded("request", **facets) == {"unconfirmed_cost": 1}
-def test_reach_keeps_an_unknown_loop_a_step_below_a_known_one() -> None:
- # An unproven cost never earns the value a loop known to grow does.
- assert _value("request", loop_magnitude="unknown") == "1"
- assert _value(loop_magnitude="grows_with_data") == "2"
+def test_only_a_loop_known_to_grow_leads() -> None:
+ assert _perf_queue(_row("request", _GROWS)).lead.tier != "later"
# --- lift: a duplicate inside the function ---------------------------------------
@@ -501,13 +494,12 @@ def test_a_module_scope_cause_reads_module_scope_of_its_file() -> None:
def test_a_production_reachable_growing_db_loop_is_in_the_top_band() -> None:
from repowise.core.analysis.health.queue.value import VALUE_MAX
- grows = {"loop_magnitude": "grows_with_data"}
- # Request or message, then a scheduled job, then no role evidence; a cold
- # role never leads.
- assert _value("request", **grows) == _value("event_consumer", **grows) == str(VALUE_MAX)
- assert _value("scheduled_job", **grows) == "3"
- assert _value("unknown", **grows) == "2"
- assert _value("cli", **grows) == "1"
+ # Request or message, then a scheduled job, then no role evidence but a
+ # reaching entry point; a cold role is never an item.
+ assert _value("request", **_GROWS) == _value("event_consumer", **_GROWS) == str(VALUE_MAX)
+ assert _value("scheduled_job", **_GROWS) == "3"
+ assert _value("unknown", **_GROWS, exposure="entry_reachable") == "2"
+ assert _excluded("cli", **_GROWS) == {"cold_role": 1}
def test_it_outranks_a_large_function_that_needs_judgment_on_score() -> None:
@@ -522,8 +514,8 @@ def test_it_outranks_a_large_function_that_needs_judgment_on_score() -> None:
assert {i.kind for i in queue.items[:2]} == {"finding", "perf_fix"}
-def test_without_reach_it_stays_below_the_top_band() -> None:
- assert _value(loop_magnitude="grows_with_data", exposure="not_entry_reachable") == "2"
+def test_with_no_role_and_no_reach_it_is_no_item() -> None:
+ assert _excluded(**_GROWS, exposure="not_entry_reachable") == {"unconfirmed_cost": 1}
# --- titles and steps name what they mean -----------------------------------------
diff --git a/tests/unit/health/test_perf_cold_paths.py b/tests/unit/health/test_perf_cold_paths.py
index 29c72fcfe..5b14377d4 100644
--- a/tests/unit/health/test_perf_cold_paths.py
+++ b/tests/unit/health/test_perf_cold_paths.py
@@ -142,3 +142,22 @@ def test_gated_off_takes_precedence_over_cold_path() -> None:
assert opportunity.actionability_reason == "gated_off"
assert perf_queue_verdict(opportunity).reason == "gated_off"
+
+
+def test_growth_only_a_registry_or_a_migration_loop_shows_is_named_for_it() -> None:
+ from types import SimpleNamespace
+
+ from repowise.core.analysis.health.perf.opportunity_rank import growth_source
+
+ def member(path: str, function: str, iterates: str = "query"):
+ details = {"loop_magnitude": "grows_with_data", "loop_iterates": iterates}
+ return SimpleNamespace(details=details, file_path=path, function_name=function)
+
+ registry = member("app/scheduler.py", "poll", "config_table")
+ migration = member("app/db_migration.py", "backfill")
+ warm = member("app/views.py", "list_items")
+ assert growth_source("io_in_loop", [registry, migration]) == "registry"
+ assert growth_source("io_in_loop", [migration]) == "cold_path"
+ assert growth_source("io_in_loop", [registry, warm]) == "loop"
+ assert growth_source("io_in_loop", []) == "none"
+ assert growth_source("hot_path_sync_io", [warm]) == "n/a"
diff --git a/tests/unit/health/test_queue_eligibility.py b/tests/unit/health/test_queue_eligibility.py
index 5272b4031..b5d154773 100644
--- a/tests/unit/health/test_queue_eligibility.py
+++ b/tests/unit/health/test_queue_eligibility.py
@@ -10,6 +10,7 @@ from repowise.core.analysis.health.queue.eligibility import (
Verdict,
finding_verdict,
path_verdict,
+ perf_confident_verdict,
perf_fix_verdict,
refactor_verdict,
unit_verdict,
@@ -37,7 +38,11 @@ def _cause(**over):
"plan_state": "available",
"fix_strategy": "batch_or_prefetch_io",
"biomarker_type": "io_in_loop",
- "facets": {"loop_magnitude": "grows_with_data"},
+ "facets": {
+ "loop_magnitude": "grows_with_data",
+ "growth_source": "loop",
+ "execution_role": "request",
+ },
}
return {**row, **over}
@@ -93,14 +98,57 @@ def test_a_cause_group_asks_about_dead_code_only_once_it_is_worth_an_item() -> N
asked.append(True)
return True
- bounded = _cause(biomarker_type="string_concat_in_loop", facets={"loop_magnitude": "bounded"})
+ bounded = _cause(
+ biomarker_type="string_concat_in_loop",
+ facets={"loop_magnitude": "bounded", "execution_role": "request"},
+ )
contexts = frozenset({"production"})
- assert perf_fix_verdict([bounded], contexts, unreachable)[0].reason == "below_min_worth"
+ assert perf_fix_verdict([bounded], contexts, unreachable)[0].reason == "unconfirmed_cost"
assert not asked
assert perf_fix_verdict([_cause()], contexts, unreachable)[0].reason == "unreachable"
assert asked == [True]
+ ("facets", "reason"),
+ [
+ # A registry loop's growth rests on its name.
+ ({"growth_source": "registry"}, "unconfirmed_cost"),
+ # Growth seen only in a migration loop is paid once per deploy.
+ ({"growth_source": "cold_path"}, "unconfirmed_cost"),
+ # Stored before the fact existed: nothing confirms it.
+ ({"growth_source": None}, "unconfirmed_cost"),
+ # No known role and no entry point reaching it.
+ ({"execution_role": "unknown", "exposure": "unknown"}, "unconfirmed_cost"),
+ ({"execution_role": "unknown", "exposure": "entry_reachable"}, None),
+ # Still the queue's own reasons first.
+ ({"loop_magnitude": "unknown"}, "unmeasured_cost"),
+ ({"execution_role": "cli"}, "cold_role"),
+ ({}, None),
+ ],
+)
+def test_a_confident_cause_is_a_queued_one_whose_growth_a_warm_loop_shows(facets, reason) -> None:
+ row = _cause()
+ row["facets"] = {k: v for k, v in {**row["facets"], **facets}.items() if v is not None}
+ assert perf_confident_verdict(row).reason == reason
+
+
+def test_an_advisory_cause_is_queued_but_never_confident() -> None:
+ from repowise.core.analysis.health.queue.eligibility import perf_queue_verdict
+
+ advisory = _cause(actionability_state="advisory")
+ assert perf_queue_verdict(advisory).eligible
+ assert perf_confident_verdict(advisory).reason == "unconfirmed_cost"
+
+
+def test_a_per_call_cause_is_confident_only_once_an_entry_point_reaches_it() -> None:
+ hot = {"loop_magnitude": "n/a", "growth_source": "n/a", "execution_role": "request"}
+ reached = _cause(biomarker_type="hot_path_sync_io", facets={**hot, "exposure": "entry_reachable"})
+ assert perf_confident_verdict(reached).eligible
+ unreached = _cause(biomarker_type="hot_path_sync_io", facets={**hot, "exposure": "unknown"})
+ assert perf_confident_verdict(unreached).reason == "unconfirmed_cost"
+
+
class _Shaped(_Facts):
def __init__(self, shape, *, dead=False, cloned=False):
self._shape, self._dead, self._cloned = shape, dead, cloned
diff --git a/tests/unit/health/test_queue_value_order.py b/tests/unit/health/test_queue_value_order.py
index 4bf325847..fa1c6204e 100644
--- a/tests/unit/health/test_queue_value_order.py
+++ b/tests/unit/health/test_queue_value_order.py
@@ -66,10 +66,10 @@ PERFORMANCE = [
#: (finding's function or cause's id, value band, why it sits here).
GOLDEN = [
+ ("perf_req", "4", "request-run growing db loop: top band, and its plan is safe to start"),
("run_conversation", "4", "largest complexity removed (963) x reach of 32 importers"),
("load_gateway_config", "4", "CCN 151 x reach of 487 importers outweighs the wizard"),
("show_status", "4", "the wizard: band 4 on size, CCN 153 x reach of only 7 importers"),
- ("perf_req", "4", "request-run growing db loop: top band, worth a CCN 40 x 3 call sites"),
("perf_unknown", "2", "the same loop with no role evidence: band 2, worth 103"),
]
@@ -123,7 +123,8 @@ def test_history_orders_within_a_band_and_never_lifts_one() -> None:
calm = build_fix_first(metrics=quiet, findings=FINDINGS, performance=PERFORMANCE,
hot_cuts=_CUTS, limit=None)
assert {_key(i): _value(i) for i in calm.items} == base
- churn = {f.factor: f.value for f in calm.items[0].why_ranked}["changes often"]
+ giant = next(i for i in calm.items if i.target.symbol == "run_conversation")
+ churn = {f.factor: f.value for f in giant.why_ranked}["changes often"]
assert churn == "no"
diff --git a/tests/unit/persistence/test_actions_build.py b/tests/unit/persistence/test_actions_build.py
index 3f2896580..a95690562 100644
--- a/tests/unit/persistence/test_actions_build.py
+++ b/tests/unit/persistence/test_actions_build.py
@@ -80,6 +80,7 @@ PERFORMANCE = [
"file_path": "src/repo.py", "intervention_symbol": "src/repo.py::Repo.load",
"affected_call_sites_total": 4, "affected_files_total": 2, "queue_eligible": True,
"details": {"facets": {"exposure": "entry_reachable", "loop_magnitude": "grows_with_data",
+ "growth_source": "loop",
"actionability_confidence": "medium"},
"plan": {"effort_bucket": "S"}}},
{"opportunity_id": "perf2", "execution_context": "production",
diff --git a/tests/unit/persistence/test_actions_loader.py b/tests/unit/persistence/test_actions_loader.py
index 07a502b3a..2e03e0e34 100644
--- a/tests/unit/persistence/test_actions_loader.py
+++ b/tests/unit/persistence/test_actions_loader.py
@@ -135,6 +135,7 @@ async def _seed(session) -> str:
affected_files_total=2, queue_eligible=True,
details_json=json.dumps(
{"facets": {"exposure": "entry_reachable", "loop_magnitude": "grows_with_data",
+ "growth_source": "loop",
"actionability_confidence": "medium"},
"plan": {"effort_bucket": "S"}}
),
diff --git a/tests/unit/persistence/test_performance_materialization.py b/tests/unit/persistence/test_performance_materialization.py
index ef2b40ba2..539eba928 100644
--- a/tests/unit/persistence/test_performance_materialization.py
+++ b/tests/unit/persistence/test_performance_materialization.py
@@ -50,6 +50,7 @@ def _finding(path: str, line: int, *, marker: str = "serial_await_in_loop", **de
"resolution_basis": "call-site",
"dataflow_verified": True,
"loop_magnitude": "grows_with_data",
+ "execution_role": "request",
**details,
},
health_impact=0.0,
@@ -110,7 +111,9 @@ async def test_one_pass_materializes_the_queue_its_plans_and_its_headline(
summary = await crud.get_performance_summary(async_session, repo.id)
assert summary.opportunities_total == 1
- assert json.loads(summary.summary_json)["lead"]["opportunity_id"] == row.opportunity_id
+ # An advisory cause is queued but never the lead: only a plan-ready one is.
+ assert row.actionability_state == "advisory"
+ assert json.loads(summary.summary_json)["lead"] is None
@pytest.mark.asyncio
@@ -381,17 +384,24 @@ def test_a_non_leading_marker_never_leads_the_summary():
def _opp(oid: str, marker: str, may_lead: bool):
return SimpleNamespace(
- opportunity_id=oid, actionability_state="advisory", biomarker_type=marker,
+ opportunity_id=oid, actionability_state="plan_ready", biomarker_type=marker,
boundary_kind="db", execution_context="production", intervention_symbol=None,
terminal_sink=None, evidence=[{"file_path": "a.py"}], observations_total=1,
affected_call_sites_total=1, affected_files_total=1, why_ranked=[],
prerequisites=(), actionability_reason="", may_lead=may_lead,
- facets={"loop_magnitude": "grows_with_data"},
+ facets={
+ "loop_magnitude": "grows_with_data",
+ "growth_source": "loop",
+ "execution_role": "request",
+ },
)
ranked = [_opp("lazy", "lazy_load_in_loop", False), _opp("io", "io_in_loop", True)]
assert _summary_payload(ranked, {})["lead"]["opportunity_id"] == "io"
assert _summary_payload(ranked[:1], {})["lead"] is None
+ # A queued cause whose growth only a registry loop shows never leads.
+ ranked[1].facets = {**ranked[1].facets, "growth_source": "registry"}
+ assert _summary_payload(ranked, {})["lead"] is None
@pytest.mark.asyncio
diff --git a/tests/unit/server/mcp/test_performance_levels.py b/tests/unit/server/mcp/test_performance_levels.py
index d577b8f56..9564e0d9b 100644
--- a/tests/unit/server/mcp/test_performance_levels.py
+++ b/tests/unit/server/mcp/test_performance_levels.py
@@ -39,6 +39,7 @@ def _row(repo_id: str, caller: str, line: int) -> HealthFinding:
"resolution_basis": "call-site",
"loop_magnitude": "grows_with_data",
"dataflow_verified": True,
+ "execution_role": "request",
}
),
health_impact=0.0,
@@ -88,14 +89,24 @@ async def _lead_id(get_health) -> str:
@pytest.mark.asyncio
-async def test_a_bare_dashboard_leads_with_something_to_do(setup_mcp, materialized):
+async def test_a_bare_dashboard_leads_with_something_to_do(setup_mcp, materialized, factory):
"""Performance carries no defect impact, so it used to lead nowhere.
- Fix first ranks the intervention beside the code-shape work, with the call
- that opens its plan.
+ Fix first ranks a plan-ready intervention beside the code-shape work, with
+ the call that opens its plan; an advisory one stays in the performance queue.
"""
+ from sqlalchemy import update
+
+ from repowise.core.persistence.crud.analysis.fix_first import clear_fix_first_cache
+ from repowise.core.persistence.models import PerformanceOpportunity
from repowise.server.mcp_server import get_health
+ advisory = await get_health()
+ assert not [i for i in advisory["fix_first"]["items"] if i["kind"] == "perf_fix"]
+ async with factory() as s:
+ await s.execute(update(PerformanceOpportunity).values(actionability_state="plan_ready"))
+ await s.commit()
+ clear_fix_first_cache()
result = await get_health()
assert "performance_directive" not in result
perf = [i for i in result["fix_first"]["items"] if i["kind"] == "perf_fix"]
diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.py
index 87d8dd3fb..c39799aa0 100644
--- a/tests/unit/server/test_performance_opportunities.py
+++ b/tests/unit/server/test_performance_opportunities.py
@@ -431,6 +431,7 @@ async def test_detail_carries_the_facets_and_evidence_for_one_cause(
"leverage",
"change_risk",
"loop_magnitude",
+ "growth_source",
"execution_role",
}
assert body["evidence_total"] == 2