Skip to content

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

feat(health): rank and queue performance causes by execution role (#3347)

Raghav Chamadiyafd0e6d1b3f48
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.md
index 9539f7c0c..067ee18b4 100644
--- a/docs/layers/PERFORMANCE.md
+++ b/docs/layers/PERFORMANCE.md
@@ -57,6 +57,7 @@ graph and the import graph. An opportunity with a supported shared fix links to
The default queue holds production opportunities in the `plan_ready` and
`advisory` states. They are ranked by cost first; state only breaks ties.
Only opportunities whose cost is measured are in it. A loop whose size nothing measured is `cost_proof = unproven`, never leads, and shows only with the `proof=unproven` filter.
+Each opportunity also says what runs its loop (`execution_role`: request, event consumer, scheduled job, startup, CLI, UI, tooling, test or unknown), and loops run per request rank above the rest. Roles are read for Python and TypeScript/JavaScript; other languages show `unknown`. The `role` filter lists any one role, or `all`.
Everything else is counted by reason, not hidden:
@@ -69,6 +70,8 @@ Everything else is counted by reason, not hidden:
| `gated_off` | The function is switched off by a constant flag; see [dormant functions](CODE_HEALTH.md#fix-first) |
| `cold_path` | The function is named for a migration, startup, shutdown or crash recovery, so it runs rarely |
| `no_strategy` | The state is `investigate`: there is no supported fix to offer |
+| `cold_role` | Only startup, a CLI command, tooling, tests or client UI code run the loop, so no server pays it per request |
+| `background_unproven` | A scheduled job runs the loop and nothing shows it grows with the data; listed under `proof=background_unproven` |
To see them, widen the filter (below). Performance work also appears in
[Fix first](CODE_HEALTH.md#fix-first), where it competes with other kinds of work.
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.ts
index 01899ee36..08dbc2bf2 100644
--- a/packages/api-client/src/code-health.ts
+++ b/packages/api-client/src/code-health.ts
@@ -134,6 +134,7 @@ export async function getPerformanceOpportunities(
confidence: opts.confidence,
actionability: opts.actionability,
proof: opts.proof,
+ role: opts.role,
view: opts.view,
sort: opts.sort,
file_paths: opts.file_paths?.length ? opts.file_paths.join(",") : undefined,
diff --git a/packages/core/alembic/versions/0102_performance_execution_role.py b/packages/core/alembic/versions/0102_performance_execution_role.py
new file mode 100644
index 000000000..baf3f3741
--- /dev/null
+++ b/packages/core/alembic/versions/0102_performance_execution_role.py
@@ -0,0 +1,38 @@
+"""Persist ``performance_opportunities.execution_role`` so the default queue can filter it.
+
+The role (request, event consumer, scheduled job, startup, CLI, tooling, test or
+unknown) says what runs a cause's loop. The queue leaves startup, CLI, tooling
+and test loops out in SQL, so the role is a column. Rows written before it read
+``unknown`` until the next analysis rewrites them.
+
+Local SQLite stores get the column from ``init_db``'s additive reconciler; this
+migration covers managed Postgres.
+
+Revision ID: 0102
+Revises: 0101
+Create Date: 2026-10-10
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0102"
+down_revision: str | None = "0101"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.add_column(
+ "performance_opportunities",
+ sa.Column("execution_role", sa.String(16), nullable=False, server_default="unknown"),
+ )
+
+
+def downgrade() -> None:
+ op.drop_column("performance_opportunities", "execution_role")
diff --git a/packages/core/src/repowise/core/analysis/execution_graph.py b/packages/core/src/repowise/core/analysis/execution_graph.py
index 5bdf69f84..755d92eb2 100644
--- a/packages/core/src/repowise/core/analysis/execution_graph.py
+++ b/packages/core/src/repowise/core/analysis/execution_graph.py
@@ -18,7 +18,7 @@ from __future__ import annotations
import re
from collections import deque
-from collections.abc import Callable, Hashable, Iterable, Mapping
+from collections.abc import Callable, Container, Hashable, Iterable, Mapping
from dataclasses import dataclass
from typing import Any, Literal, TypeVar
@@ -375,8 +375,18 @@ class ExecutionGraphIndex:
walk(self.reverse, forward_reached, reverse_depth)
return affected
- def forward_reachable(self, seeds: Iterable[str], *, max_depth: int | None = None) -> set[str]:
- """Reliable execution nodes reachable from all *seeds* in one BFS."""
+ def forward_reachable(
+ self,
+ seeds: Iterable[str],
+ *,
+ max_depth: int | None = None,
+ stop_at: Container[str] = frozenset(),
+ ) -> set[str]:
+ """Reliable execution nodes reachable from all *seeds* in one BFS.
+
+ A node in *stop_at* is never entered, so nothing past it is reached
+ through it.
+ """
reached = set(seeds)
queue: deque[tuple[str, int]] = deque((seed, 0) for seed in sorted(reached))
while queue:
@@ -384,7 +394,7 @@ class ExecutionGraphIndex:
if max_depth is not None and depth >= max_depth:
continue
for target in self.forward.get(node, ()):
- if target not in reached:
+ if target not in reached and target not in stop_at:
reached.add(target)
queue.append((target, depth + 1))
return reached
diff --git a/packages/core/src/repowise/core/analysis/execution_roles.py b/packages/core/src/repowise/core/analysis/execution_roles.py
new file mode 100644
index 000000000..2ac5b9500
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/execution_roles.py
@@ -0,0 +1,490 @@
+"""What kind of run reaches a function: a request, a job, startup, a CLI, a test.
+
+Performance ranking needs "is this on a hot path", which name-derived entry
+files cannot answer: a CLI ``main`` and a web app reach the same code. Here
+each role starts from its own seeds, read off what ingestion already put in
+the graph (decorators, framework edges, route files, registrations), and the
+hot roles spread with one breadth-first walk each over the reliable execution
+edges. A function reached by several roles takes the hottest.
+
+Startup and CLI never spread: a helper they call is cold only when every one
+of its callers is. Seeds cover Python and TypeScript/JavaScript only. Anything
+no seed reaches is ``unknown``, which is an answer ("no evidence"), never
+"not reachable" and never cold.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import deque
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass, field
+from functools import cache
+from typing import Any, Literal, get_args
+
+from repowise.core.code_origin import path_origin
+from repowise.core.ingestion.framework_routes import flask_routes, next_app_router_file
+from repowise.core.test_paths import is_test_path
+
+from .execution_graph import ExecutionGraphIndex, file_of_symbol
+
+ExecutionRole = Literal[
+ "request",
+ "event_consumer",
+ "scheduled_job",
+ "startup",
+ "cli",
+ "ui",
+ "tooling",
+ "test",
+ "unknown",
+]
+EXECUTION_ROLES: tuple[str, ...] = get_args(ExecutionRole)
+"""Every role, hottest first. The order is the precedence when roles meet."""
+
+LEADING_ROLES = frozenset({"request", "event_consumer"})
+"""Roles whose work repeats per request or per message."""
+
+COLD_ROLES = frozenset({"startup", "cli", "ui", "tooling", "test"})
+"""Roles whose loops are not served: once per process or command, or on the
+user's own machine (a browser, desktop or terminal UI)."""
+
+_HOT: tuple[ExecutionRole, ...] = ("request", "event_consumer", "scheduled_job")
+_SEEDED: tuple[ExecutionRole, ...] = (*_HOT, "startup", "cli")
+_SEEDED_LANGUAGES = frozenset({"python", "typescript", "javascript"})
+_TS_JS = frozenset({"typescript", "javascript"})
+_CALLABLE_KINDS = frozenset({"function", "method"})
+
+# Decorators no shared recogniser reads. ``flask_routes`` already reads the verb
+# decorators FastAPI spells the same way (``@router.get("/x")``); the workspace
+# HTTP dialects match whole files for route paths and sit in a layer analysis
+# does not import. ``execution_flows``' name tiers score "looks like an entry"
+# over every ``handle_``/``get_`` and are deliberately not reused as seeds.
+_PY_REQUEST_DECORATOR = re.compile(
+ r"^@\w+(?:\.\w+)*\.(?:api_route|websocket|head|options|tool)\s*\("
+ r"|^@(?:\w+\.)*method\s*\(\s*['\"]" # JSON-RPC ``@method("session.list")``
+)
+_TS_REQUEST_DECORATOR = re.compile(r"^@(?:Get|Post|Put|Patch|Delete|All|Sse|MessagePattern)\s*\(")
+_STARTUP_DECORATOR = re.compile(
+ r"^@\w+(?:\.\w+)*\.(?:on_event\s*\(\s*['\"](?:startup|shutdown)|on_startup|before_serving)"
+)
+_SCHEDULED_DECORATOR = re.compile(
+ r"^@(?:\w+\.)*(?:task|shared_task|periodic_task|scheduled_job|cron)\b"
+)
+_CLI_DECORATOR = re.compile(r"^@(?:\w+\.)*(?:command|group)\s*\(")
+_ROUTE_REGISTRAR_NAME = re.compile(
+ r"(?i)^(?:register|mount|setup|install|attach)\w*(?:routes?|router|endpoints?)$"
+)
+_WORD = re.compile(r"[A-Z]?[a-z]+|[A-Z]+(?![a-z])|\d+")
+
+# Imports under which a function named but not called is registered (``add_job(fn)``,
+# ``.action(fn)``), or which corroborate a name. No import seeds a whole file.
+_SCHEDULER_IMPORTS = frozenset(
+ {
+ "apscheduler",
+ "celery",
+ "schedule",
+ "croniter",
+ "aiocron",
+ "crontab",
+ "node-cron",
+ "cron",
+ }
+)
+# ``vscode``: ``registerCommand(id, fn)`` names a command a person runs.
+_CLI_IMPORTS = frozenset({"commander", "yargs", "cac", "@oclif", "clipanion", "citty", "vscode"})
+_EXPRESS_IMPORTS = frozenset({"express", "@nestjs"})
+_LAMBDA_CONFIG_SUFFIXES = (".yml", ".yaml", ".json", ".tf")
+
+# Name-derived seeds, each kept only with a corroborating place in the path.
+_CONSUMER_TAILS = frozenset({"inbound", "webhook", "webhooks"})
+_CONSUMER_PLACES = frozenset(
+ {
+ "gateway",
+ "gateways",
+ "inbound",
+ "webhook",
+ "webhooks",
+ "channels",
+ "consumers",
+ "listeners",
+ "adapters",
+ "platforms",
+ "monitor",
+ }
+)
+_BACKGROUND_TAILS = frozenset({"poller", "watcher", "ticker", "heartbeat", "sweeper", "reaper"})
+_BACKGROUND_PLACES = frozenset(
+ {
+ "worker",
+ "workers",
+ "jobs",
+ "job",
+ "scheduler",
+ "cron",
+ "daemon",
+ "background",
+ "tasks",
+ "gateway",
+ "watchers",
+ "executor",
+ "queue",
+ }
+)
+_ROUTE_PLACES = frozenset({"routes", "route", "router", "routers", "server", "api", "http"})
+# Client code by file: component files, and JS/TS under a UI, renderer or TUI tree.
+_JS_EXTS = frozenset({"ts", "tsx", "js", "jsx", "mjs", "cjs", "mts", "cts", "vue", "svelte"})
+_COMPONENT_EXTS = frozenset({"tsx", "jsx", "vue", "svelte"})
+_UI_PLACES = frozenset(
+ {
+ "ui",
+ "renderer",
+ "components",
+ "component",
+ "views",
+ "hooks",
+ "desktop",
+ "tui",
+ "ink",
+ "frontend",
+ "webview",
+ }
+)
+
+
+def _words(text: str) -> list[str]:
+ return [word.lower() for word in _WORD.findall(text)]
+
+
+@cache
+def _place_words(path: str) -> frozenset[str]:
+ """Every word of *path*'s directories and file stem."""
+ return frozenset(_words(path.rsplit(".", 1)[0]))
+
+
+@cache
+def _path_role(path: str) -> ExecutionRole | None:
+ """``test``, ``tooling`` or ``ui`` when the file alone decides the role.
+
+ A Next.js app-router file renders on the server per request, so it is
+ never ``ui`` here.
+ """
+ if is_test_path(path):
+ return "test"
+ if path_origin(path) in ("tooling", "build"):
+ return "tooling"
+ ext = path.rsplit(".", 1)[-1].lower()
+ if ext not in _JS_EXTS or next_app_router_file(path):
+ return None
+ return "ui" if ext in _COMPONENT_EXTS or _place_words(path) & _UI_PLACES else None
+
+
+def _import_root(target: str) -> str | None:
+ """``external:apscheduler.schedulers`` -> ``apscheduler``; ``@nestjs/core`` -> ``@nestjs``."""
+ if not target.startswith("external:"):
+ return None
+ name = target[len("external:") :]
+ return name.split("/", 1)[0].split(".", 1)[0]
+
+
+@dataclass(slots=True)
+class _Scan:
+ """What one pass over the graph's nodes and edges says about each file."""
+
+ symbols: dict[str, list[tuple[str, Mapping[str, Any]]]] = field(default_factory=dict)
+ imports: dict[str, set[str]] = field(default_factory=dict)
+ url_targets: set[str] = field(default_factory=set)
+ binds: list[tuple[str, str]] = field(default_factory=list)
+ references: list[tuple[str, str]] = field(default_factory=list)
+ referenced: set[str] = field(default_factory=set)
+
+
+def _scan(graph: Any) -> _Scan:
+ scan = _Scan()
+ for node, attrs in graph.nodes(data=True):
+ if attrs.get("node_type") == "symbol" and attrs.get("kind") in _CALLABLE_KINDS:
+ path = attrs.get("file_path") or file_of_symbol(node)
+ scan.symbols.setdefault(path, []).append((node, attrs))
+ for source, target, data in graph.edges(data=True):
+ edge_type = (data or {}).get("edge_type")
+ if edge_type == "imports":
+ root = _import_root(target)
+ if root is not None:
+ scan.imports.setdefault(source, set()).add(root)
+ elif edge_type == "framework" and source.endswith("urls.py"):
+ scan.url_targets.add(target)
+ elif edge_type == "framework_binds":
+ scan.binds.append((source, target))
+ elif edge_type == "references":
+ scan.references.append((source, target))
+ scan.referenced.add(target)
+ return scan
+
+
+def _decorator_role(decorators: Iterable[str], language: str) -> ExecutionRole | None:
+ for text in decorators:
+ if language == "python" and (any(flask_routes(text)) or _PY_REQUEST_DECORATOR.match(text)):
+ return "request"
+ if language in _TS_JS and _TS_REQUEST_DECORATOR.match(text):
+ return "request"
+ if _STARTUP_DECORATOR.match(text):
+ return "startup"
+ if _SCHEDULED_DECORATOR.match(text):
+ return "scheduled_job"
+ if language == "python" and _CLI_DECORATOR.match(text):
+ return "cli"
+ return None
+
+
+def _strong_role(path: str, attrs: Mapping[str, Any], imports: set[str]) -> ExecutionRole | None:
+ """The role a function's declaration or its file's framework convention states."""
+ language = attrs.get("language") or ""
+ role = _decorator_role(attrs.get("decorators") or (), language)
+ if role is not None:
+ return role
+ if language in _TS_JS and (next_app_router_file(path) or "/pages/api/" in f"/{path}"):
+ return "request"
+ if attrs.get("name") == "main" and "argparse" in imports:
+ return "cli"
+ return None
+
+
+def _named_role(
+ path: str, attrs: Mapping[str, Any], imports: set[str], referenced: bool
+) -> ExecutionRole | None:
+ """The role a function's name implies, kept only when its file or a
+ registration corroborates it; otherwise no evidence, so no seed."""
+ name = attrs.get("name") or ""
+ words = _words(name)
+ if not words:
+ return None
+ places = _place_words(path)
+ if name == "lifespan" or (name == "activate" and "vscode" in imports):
+ return "startup"
+ if _request_named(name, words, attrs, imports, places):
+ return "request"
+ if words[0] in ("handle", "on") and words[-1] in _CONSUMER_TAILS:
+ return "event_consumer" if referenced or places & _CONSUMER_PLACES else None
+ return "scheduled_job" if _background_named(words, imports, places, referenced) else None
+
+
+def _background_named(
+ words: list[str], imports: set[str], places: frozenset[str], referenced: bool
+) -> bool:
+ scheduler = bool(imports & _SCHEDULER_IMPORTS)
+ if _background_shaped(words) and (referenced or places & _BACKGROUND_PLACES or scheduler):
+ return True
+ # ``setup_scheduler`` registering closures with ``add_job``: closures are no
+ # symbols, so their loops belong to the function that builds the scheduler.
+ return words[-1] == "scheduler" and scheduler
+
+
+def _request_named(
+ name: str,
+ words: list[str],
+ attrs: Mapping[str, Any],
+ imports: set[str],
+ places: frozenset[str],
+) -> bool:
+ # aiohttp registers ``self._handle_x`` with ``router.add_get``: a mention, never a call.
+ if "aiohttp" in imports and words[0] == "handle":
+ return True
+ return bool(
+ attrs.get("language") in _TS_JS
+ and _ROUTE_REGISTRAR_NAME.match(name)
+ and places & _ROUTE_PLACES
+ )
+
+
+def _background_shaped(words: list[str]) -> bool:
+ """A poller, watcher or job runner by whole words: ``poll_once``,
+ ``_notification_poller_loop``, ``execute_job``; never ``polling_config``."""
+ if words[-1] in _BACKGROUND_TAILS:
+ return True
+ if words[-1] == "loop" and len(words) > 1 and words[-2] in {*_BACKGROUND_TAILS, "poll"}:
+ return True
+ if words[0] == "poll" and len(words) > 1:
+ return True
+ return words[0] in ("run", "execute", "process") and words[-1] in ("job", "jobs")
+
+
+@dataclass(slots=True)
+class Seeds:
+ """Seed symbol ids per role, and the ones a declaration or framework states."""
+
+ by_role: dict[str, set[str]]
+ strong: set[str]
+
+ def add(self, role: str, node: str, *, strong: bool) -> None:
+ self.by_role[role].add(node)
+ if strong:
+ self.strong.add(node)
+
+
+def _seed_symbols(scan: _Scan, seeds: Seeds) -> dict[str, Mapping[str, Any]]:
+ callables: dict[str, Mapping[str, Any]] = {}
+ for path, symbols in scan.symbols.items():
+ imports = scan.imports.get(path, set())
+ for node, attrs in symbols:
+ callables[node] = attrs
+ if attrs.get("language") not in _SEEDED_LANGUAGES:
+ continue
+ role = "request" if path in scan.url_targets else _strong_role(path, attrs, imports)
+ if role is not None:
+ seeds.add(role, node, strong=True)
+ continue
+ role = _named_role(path, attrs, imports, node in scan.referenced)
+ if role is not None:
+ seeds.add(role, node, strong=False)
+ return callables
+
+
+def _seed_binds(scan: _Scan, callables: Mapping[str, Mapping[str, Any]], seeds: Seeds) -> None:
+ for source, target in scan.binds:
+ attrs = callables.get(target)
+ if attrs is None:
+ continue
+ source_file = file_of_symbol(source)
+ if source_file.endswith(_LAMBDA_CONFIG_SUFFIXES):
+ seeds.add("event_consumer", target, strong=True)
+ continue
+ express = scan.imports.get(source_file, set()) & _EXPRESS_IMPORTS
+ if attrs.get("language") in _TS_JS and express:
+ seeds.add("request", target, strong=True)
+
+
+def _seed_references(scan: _Scan, callables: Mapping[str, Any], seeds: Seeds) -> None:
+ """Functions a file registers by name: ``add_job(fn)`` for a scheduler,
+ ``set_defaults(func=cmd)`` or ``.action(cmd)`` for a CLI. Named, never
+ called, so only a reference shows it."""
+ for source, target in scan.references:
+ if target not in callables:
+ continue
+ imports = scan.imports.get(file_of_symbol(source), set())
+ if imports & _SCHEDULER_IMPORTS:
+ seeds.add("scheduled_job", target, strong=True)
+ elif "argparse" in imports or imports & _CLI_IMPORTS:
+ seeds.add("cli", target, strong=True)
+
+
+def seed_roles(graph: Any) -> Seeds:
+ """Seed symbol ids per role, from one scan of *graph*."""
+ scan = _scan(graph)
+ seeds = Seeds({role: set() for role in _SEEDED}, set())
+ callables = _seed_symbols(scan, seeds)
+ _seed_binds(scan, callables, seeds)
+ _seed_references(scan, callables, seeds)
+ return seeds
+
+
+def _settle_cold(index: ExecutionGraphIndex, reached: dict[str, ExecutionRole]) -> None:
+ """Mark cold every function whose known callers are all cold.
+
+ A caller in a test or tooling file counts as cold. One caller nothing
+ classified keeps the function ``unknown``: that caller is no evidence.
+ """
+ remaining: dict[str, int] = {}
+ queue = deque(node for node, role in reached.items() if role in COLD_ROLES)
+ while queue:
+ node = queue.popleft()
+ for target in index.forward.get(node, ()):
+ if target in reached:
+ continue
+ if target not in remaining:
+ remaining[target] = sum(
+ 1
+ for caller in index.reverse.get(target, ())
+ if _path_role(file_of_symbol(caller)) is None
+ )
+ remaining[target] -= 1
+ if remaining[target] <= 0:
+ reached[target] = reached[node]
+ queue.append(target)
+
+
+@dataclass(frozen=True, slots=True)
+class ExecutionRoles:
+ """The hottest role reaching each function, ready to look up.
+
+ *index* is the graph the roles were walked over, kept so a stored finding
+ that predates ``role_owner`` can still be keyed on its loop owner.
+ """
+
+ reached: Mapping[str, ExecutionRole]
+ index: ExecutionGraphIndex | None = field(default=None, compare=False, repr=False)
+
+ @classmethod
+ def build(cls, graph: Any, index: ExecutionGraphIndex) -> ExecutionRoles:
+ """Seed once, walk each hot role, then settle what only cold roles call.
+
+ A hot walk stops at another role's declared seed (a route handler, a
+ registered job): that is where the other role's work begins. A seed
+ named only by convention does not stop it, because calling a function
+ runs it whatever it is called.
+ """
+ seeds = seed_roles(graph)
+ reached: dict[str, ExecutionRole] = {}
+ for role in _HOT:
+ if seeds.by_role[role]:
+ stop_at = seeds.strong - seeds.by_role[role]
+ for node in index.forward_reachable(seeds.by_role[role], stop_at=stop_at):
+ reached.setdefault(node, role)
+ for role in ("startup", "cli"):
+ for node in seeds.by_role[role]:
+ reached.setdefault(node, role)
+ _settle_cold(index, reached)
+ return cls(reached, index)
+
+ def owner_of(self, file_path: str, line: int | None, details: Mapping[str, Any]) -> str | None:
+ """The function that owns a performance finding's loop.
+
+ The path's first node when the cost crosses functions, else the
+ symbol holding the finding's line.
+ """
+ path = details.get("path")
+ if isinstance(path, list) and path:
+ return path[0]
+ return self.index.resolve_function(file_path, line or 0) if self.index else None
+
+ def role_of(self, symbol: str | None, file_path: str) -> ExecutionRole:
+ """The role of the function *symbol* in *file_path*.
+
+ A test or tooling file is that role whatever reaches it: a loop in a
+ test is a test's cost.
+ """
+ by_path = _path_role(file_path)
+ if by_path is not None:
+ return by_path
+ return self.reached.get(symbol, "unknown") if symbol else "unknown"
+
+
+_GROUP_ORDER: tuple[ExecutionRole, ...] = (
+ "request",
+ "event_consumer",
+ "scheduled_job",
+ "unknown",
+ "startup",
+ "cli",
+ "ui",
+ "tooling",
+ "test",
+)
+
+
+def hottest_role(roles: Iterable[str | None]) -> ExecutionRole:
+ """The role of a group of functions: one request member makes it a request,
+ and one member nothing reached keeps it from reading as cold."""
+ present = {role or "unknown" for role in roles}
+ return next((role for role in _GROUP_ORDER if role in present), "unknown")
+
+
+__all__ = [
+ "COLD_ROLES",
+ "EXECUTION_ROLES",
+ "LEADING_ROLES",
+ "ExecutionRole",
+ "ExecutionRoles",
+ "Seeds",
+ "hottest_role",
+ "seed_roles",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index a69fe2fd2..aee1b3b76 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -41,6 +41,7 @@ from ...ingestion.package_roots import scan_package_roots as _scan_package_roots
from ...installed_components import is_installed_component
from ...test_paths import paired_test_names
from ..dead_code.file_reachability import file_dependency_neighbors
+from ..execution_roles import ExecutionRoles
from ..graph_view import HasEdge, ImportEdgeView
from ..test_reachability import files_reached_by_tests, files_with_paired_tests
from .asserts.lexicon import AssertVocabulary
@@ -1037,7 +1038,7 @@ class HealthAnalyzer:
timings_finalize = timed(timings, "analysis.health.finalize")
timings_finalize.__enter__()
- self._mark_perf_entry_reachability(findings)
+ execution_roles = self._mark_perf_entry_reachability(findings)
link_performance_findings(findings)
opportunities = build_performance_opportunities(findings)
if refactoring_enabled and "performance_fix" not in disabled_refactorings:
@@ -1058,6 +1059,7 @@ class HealthAnalyzer:
metrics=metrics,
kpis=kpis,
function_blame_rows=self._function_blame_rows(walked),
+ execution_roles=execution_roles,
repo_function_mod_p80=full_repo_fn_mod_p80,
refactoring_suggestions=suggestions,
performance_plan_policy=PerformancePlanPolicy(
@@ -1242,7 +1244,7 @@ class HealthAnalyzer:
else:
kpis = {}
- self._mark_perf_entry_reachability(findings)
+ execution_roles = self._mark_perf_entry_reachability(findings)
link_performance_findings(findings)
opportunities = build_performance_opportunities(findings)
if refactoring_enabled and "performance_fix" not in disabled_refactorings:
@@ -1262,6 +1264,7 @@ class HealthAnalyzer:
metrics=metrics,
kpis=kpis,
function_blame_rows=self._function_blame_rows(walked),
+ execution_roles=execution_roles,
repo_function_mod_p80=full_repo_fn_mod_p80,
refactoring_suggestions=suggestions,
performance_plan_policy=PerformancePlanPolicy(
@@ -1372,28 +1375,41 @@ class HealthAnalyzer:
log.debug("health_crossfn_perf_failed", error=str(exc))
return
- def _mark_perf_entry_reachability(self, findings: list[HealthFindingData]) -> None:
- """Stamp reliable entry reachability without walking once per row."""
+ def _mark_perf_entry_reachability(
+ self, findings: list[HealthFindingData]
+ ) -> ExecutionRoles | None:
+ """Stamp entry reachability and execution role without walking once per row.
+
+ The role is keyed on the loop-owning function: the path's first node
+ when the cost crosses functions, else the symbol holding the finding.
+ The owner is stored too, so the writer can restamp a stored finding
+ this run did not rescan. Returns the roles for that writer.
+ """
index = self._execution_graph()
+ perf = [finding for finding in findings if finding.dimension == "performance"]
if index is None or self.graph is None:
- return
- entry_files: set[str] = set()
- try:
- for node_id, data in self.graph.nodes(data=True):
- if data.get("node_type") == "file" and data.get("is_entry_point"):
- entry_files.add(node_id)
- except Exception:
- return
+ return None
+ entry_files = {
+ node_id
+ for node_id, data in self.graph.nodes(data=True)
+ if data.get("node_type") == "file" and data.get("is_entry_point")
+ }
seeds = {symbol for path in entry_files for symbol in index.declares.get(path, ())}
- if not seeds:
- return
- reachable = index.forward_reachable(seeds)
- for finding in findings:
- if finding.dimension != "performance":
- continue
+ reachable = index.forward_reachable(seeds) if seeds and perf else None
+ try:
+ roles = ExecutionRoles.build(self.graph, index)
+ except Exception as exc:
+ log.debug("health_execution_roles_failed", error=str(exc))
+ roles = None
+ for finding in perf:
path = finding.details.get("path")
- if isinstance(path, list) and path:
+ if reachable is not None and isinstance(path, list) and path:
finding.details["reliable_entry_reachability"] = path[0] in reachable
+ if roles is not None:
+ owner = roles.owner_of(finding.file_path, finding.line_start, finding.details)
+ finding.details["role_owner"] = owner
+ finding.details["execution_role"] = roles.role_of(owner, finding.file_path)
+ return roles
def _function_blame_rows(self, walked: list[tuple[Any, FileComplexity]]) -> list[dict]:
"""Build the per-function blame rollup from the walked files + the
diff --git a/packages/core/src/repowise/core/analysis/health/finding_identity.py b/packages/core/src/repowise/core/analysis/health/finding_identity.py
index 1a1dc2c30..72399f5d0 100644
--- a/packages/core/src/repowise/core/analysis/health/finding_identity.py
+++ b/packages/core/src/repowise/core/analysis/health/finding_identity.py
@@ -75,6 +75,8 @@ _DERIVED_DETAIL_KEYS = frozenset(
{
"opportunity_id",
"reliable_entry_reachability",
+ "execution_role",
+ "role_owner",
"dispatch_share",
"deprecated",
"gated_off",
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index a8ddcc895..186df2d43 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -238,3 +238,7 @@ class HealthReport:
# against the merged stored set, and need this configuration to get there.
# Typed ``Any`` for the same reason as ``refactoring_suggestions``.
performance_plan_policy: Any | None = None
+ # ``execution_roles.ExecutionRoles`` over the whole graph, so the writer can
+ # restamp stored performance findings this run did not rescan. Typed ``Any``
+ # for the same reason as ``refactoring_suggestions``.
+ execution_roles: Any | None = None
diff --git a/packages/core/src/repowise/core/analysis/health/perf/facts.py b/packages/core/src/repowise/core/analysis/health/perf/facts.py
index f4f3e9309..f8a800fba 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/facts.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/facts.py
@@ -40,6 +40,8 @@ class ObservationFacts:
cross_function: bool
resolution_basis: Any
reliable_entry_reachability: Any
+ # ``execution_roles.ExecutionRole`` of the loop-owning function, when stamped.
+ execution_role: str | None
details: dict[str, Any]
@property
@@ -122,6 +124,7 @@ def observation_facts(row: Any) -> ObservationFacts:
cross_function=bool(details.get("cross_function")),
resolution_basis=details.get("resolution_basis", "direct"),
reliable_entry_reachability=details.get("reliable_entry_reachability"),
+ execution_role=details.get("execution_role"),
details=details,
)
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 fafc7f15a..3428ff954 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py
@@ -19,6 +19,7 @@ from __future__ import annotations
from dataclasses import dataclass
from typing import Any
+from ...execution_roles import hottest_role
from .actionability import (
ActionabilityState,
FixSafety,
@@ -68,10 +69,10 @@ from .siblings import link_siblings
class PerformanceOpportunity:
"""One cause, its evidence, and what can be done about it.
- Seven facets are reported separately and must not be read as one another.
+ Its facets are reported separately and must not be read as one another.
Two of them keep the names callers already join on: ``confidence`` is
- evidence confidence, and ``fix.safety`` is fix safety. The remaining five
- live in ``facets``, so no number or label is published twice.
+ evidence confidence, and ``fix.safety`` is fix safety. The rest live in
+ ``facets``, so no number or label is published twice.
"""
opportunity_id: str
@@ -168,6 +169,7 @@ def _assemble(key: Any, members: list[Any], cap: int) -> PerformanceOpportunity:
provenance = weakest_provenance({facts.provenance for facts in members})
evidence_confidence = provenance_confidence(provenance)
reachable = _reachability({facts.reliable_entry_reachability for facts in members})
+ role = hottest_role(facts.execution_role for facts in members)
sinks = tuple(sorted({facts.terminal_sink for facts in members if facts.terminal_sink}))
assessment = assess_fix(
marker,
@@ -186,7 +188,7 @@ def _assemble(key: Any, members: list[Any], cap: int) -> PerformanceOpportunity:
marker=marker,
boundary=boundary,
context=context,
- reachable=reachable,
+ role=role,
site_count=len(sites),
provenance=provenance,
magnitude=magnitude,
@@ -198,6 +200,7 @@ def _assemble(key: Any, members: list[Any], cap: int) -> PerformanceOpportunity:
"leverage": leverage(len(sites)),
"change_risk": change_risk(len(files)),
"loop_magnitude": magnitude,
+ "execution_role": role,
}
return PerformanceOpportunity(
opportunity_id=stable_id(key),
@@ -234,7 +237,7 @@ def _assemble(key: Any, members: list[Any], cap: int) -> PerformanceOpportunity:
"multiplier_shape": marker,
"boundary_kind": boundary,
"execution_context": context,
- "entry_reachability": reachable,
+ "execution_role": role,
"affected_call_sites": len(sites),
"provenance": provenance,
"loop_magnitude": magnitude,
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 34c1b067f..a4b6b8fc0 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
@@ -20,6 +20,7 @@ from collections.abc import Mapping
from math import log2
from typing import Any
+from ...execution_roles import COLD_ROLES
from ..rank_common import top_factors, weakest
from ..worth import lead_reason
@@ -109,6 +110,16 @@ MAGNITUDE_POINTS = {"grows_with_data": 2, "n/a": 1, "bounded": 0, "unknown": 0}
"""A loop over a query result is paid again as the data grows; a retry loop or a
constant-width slice is not. Unknown earns nothing, so a guess never outranks a fact."""
PROVENANCE_POINTS = {"call-site": 3, "direct": 3, "reliable-edge": 2, "name-fallback": 0}
+ROLE_POINTS = {
+ "request": 3,
+ "event_consumer": 2,
+ "scheduled_job": 1,
+ "unknown": 1,
+ **dict.fromkeys(COLD_ROLES, 0),
+}
+"""What runs the loop: once per request outranks once per message, a scheduled
+job, and a run nobody's seeds reached; startup, CLI, tooling and tests earn
+nothing, since their loops run once per process."""
AMPLIFICATION = {
"nested_loop_with_io": "quadratic",
@@ -229,7 +240,7 @@ def rank_factors(
marker: str,
boundary: str | None,
context: str,
- reachable: bool | None,
+ role: str,
site_count: int,
provenance: str,
magnitude: str,
@@ -243,7 +254,7 @@ def rank_factors(
"multiplier_shape": MULTIPLIER_POINTS.get(marker, 1),
"boundary_kind": BOUNDARY_POINTS.get(boundary or "", 0),
"execution_context": CONTEXT_POINTS.get(context, 1),
- "entry_reachability": 3 if reachable is True else 0,
+ "execution_role": ROLE_POINTS.get(role, 1),
"affected_call_sites": min(8, int(log2(site_count + 1) * 2)),
"provenance": PROVENANCE_POINTS.get(provenance, 0),
"loop_magnitude": MAGNITUDE_POINTS[magnitude],
@@ -288,6 +299,7 @@ __all__ = [
"MULTIPLIER_POINTS",
"NON_LEADING_MARKERS",
"PROVENANCE_POINTS",
+ "ROLE_POINTS",
"UNKNOWN_MULTIPLIER_POINTS",
"amplification",
"band",
diff --git a/packages/core/src/repowise/core/analysis/health/perf/serving.py b/packages/core/src/repowise/core/analysis/health/perf/serving.py
index 246eb1241..4e827bad3 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/serving.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/serving.py
@@ -16,17 +16,20 @@ from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal
+from repowise.core.analysis.execution_roles import EXECUTION_ROLES
from repowise.core.analysis.health import queue_rules
from repowise.core.analysis.health.finding_identity import finding_public_id
from repowise.core.analysis.health.fix_first.text import perf_cost
from repowise.core.analysis.health.queue.eligibility import (
DEFAULT_QUEUE_PROOFS,
DEFAULT_QUEUE_STATES,
+ QUEUE_PROOFS,
+ QUEUE_ROLES,
perf_low_priority,
)
from repowise.core.analysis.health.queue_rules import NULL_VALUE, Facet, FilterRule, SortKeys
from repowise.core.analysis.health.rows import detail_map, field, json_field
-from repowise.core.analysis.health.worth import COST_PROOFS, LOW_PRIORITY_LABEL
+from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL
from .opportunities import PERFORMANCE_MODEL_VERSION
from .opportunity_rank import NON_LEADING_MARKERS
@@ -63,6 +66,8 @@ CANONICAL_VIEWS = ("detail", "summary")
CONFIDENCES = ("high", "medium", "low")
ACTIONABILITIES = ("plan_ready", "advisory", "investigate", "expected")
BOUNDARIES = ("db", "network", "filesystem", "subprocess", "lock", NULL_VALUE)
+ROLES = (*EXECUTION_ROLES, "all")
+"""One execution role, or ``all``. Absent means the roles the default queue holds."""
DEFAULT_ACTIONABILITIES = DEFAULT_QUEUE_STATES
"""``expected`` rows offer nothing to change and ``investigate`` rows no strategy to apply,
@@ -115,6 +120,7 @@ FILTERS: tuple[FilterRule, ...] = (
FilterRule("confidence", "evidence_confidence", "eq", "set"),
FilterRule("actionabilities", "actionability_state", "in", "set"),
FilterRule("proofs", "cost_proof", "in", "set"),
+ FilterRule("roles", "execution_role", "in", "set"),
FilterRule("file_paths", "file_path", "in", "set"),
)
@@ -127,6 +133,7 @@ FACETS: tuple[Facet, ...] = (
("actionability", "actionability_state", "actionabilities"),
("plan_state", "plan_state", None),
("proof", "cost_proof", "proofs"),
+ ("role", "execution_role", "roles"),
)
FACET_FIELDS = tuple(column for _, column, _ in FACETS)
@@ -157,6 +164,7 @@ def _facet_selection(query: PerformanceQuery) -> dict[str, Any]:
None if query.actionability is None else frozenset({query.actionability})
),
"proofs": None if query.proof is None else frozenset({query.proof}),
+ "roles": None if query.role in (None, "all") else frozenset({query.role}),
}
@@ -205,6 +213,7 @@ class PerformanceQuery:
confidence: str | None = None
actionability: str | None = None
proof: str | None = None
+ role: str | None = None
view: str = "detail"
sort: str = DEFAULT_SORT
file_paths: tuple[str, ...] | None = None
@@ -238,6 +247,15 @@ class PerformanceQuery:
return DEFAULT_QUEUE_PROOFS
return frozenset({self.proof})
+ @property
+ def roles(self) -> frozenset[str] | None:
+ """One role when asked for, every role under ``all``; else the roles
+ the default queue holds, so startup, CLI, tooling and test loops sit
+ one filter away and the ``role`` facet counts them."""
+ if self.role is None:
+ return QUEUE_ROLES
+ return None if self.role == "all" else frozenset({self.role})
+
def _resolve_context(context: str | None, ignored: dict[str, str]) -> PerformanceContext:
if not context:
@@ -259,6 +277,7 @@ def parse_query(
confidence: str | None = None,
actionability: str | None = None,
proof: str | None = None,
+ role: str | None = None,
view: str | None = None,
sort: str | None = None,
file_paths: tuple[str, ...] | None = None,
@@ -288,7 +307,8 @@ def parse_query(
boundary=pick("performance_boundary", boundary, BOUNDARIES),
confidence=pick("performance_confidence", confidence, CONFIDENCES),
actionability=pick("performance_actionability", actionability, ACTIONABILITIES),
- proof=pick("performance_proof", proof, COST_PROOFS),
+ proof=pick("performance_proof", proof, QUEUE_PROOFS),
+ role=pick("performance_role", role, ROLES),
view=pick("performance_view", view, CANONICAL_VIEWS) or "detail",
sort=pick("performance_sort", sort, CANONICAL_SORTS) or DEFAULT_SORT,
file_paths=file_paths,
@@ -492,7 +512,8 @@ def rescope_summary(
proof: dict[str, int] = {}
total = 0
with_plan = 0
- for execution_context, boundary_kind, _confidence, state, plan_state, cost, count in groups:
+ for group in groups:
+ execution_context, boundary_kind, _confidence, state, plan_state, cost, _role, count = group
if execution_context not in contexts:
continue
total += count
@@ -562,6 +583,7 @@ __all__ = [
"FACET_FIELDS",
"FILTERS",
"PLAN_REASONS",
+ "ROLES",
"SORTS",
"SUMMARY_UNAVAILABLE",
"PerformanceContext",
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 3cd7c132c..5ebe15e30 100644
--- a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py
+++ b/packages/core/src/repowise/core/analysis/health/queue/eligibility.py
@@ -19,6 +19,7 @@ from typing import Any, Literal, Protocol, get_args
from repowise.core.code_origin import path_origin
+from ...execution_roles import COLD_ROLES, EXECUTION_ROLES
from ..perf.actionability import EXPECTED_REASONS
from ..perf.causal import code_context
from ..rows import detail_map, field
@@ -54,6 +55,8 @@ Reason = Literal[
"low_value_kind",
"kind_unaudited",
"unmeasured_cost",
+ "cold_role",
+ "background_unproven",
]
"""Why a unit is out of a default queue. Each surface counts the subset its
ladders can produce (``fix_first.model.FIX_EXCLUSIONS``,
@@ -379,10 +382,16 @@ DEFAULT_QUEUE_EXCLUSIONS = (
"expected",
"no_strategy",
"unmeasured_cost",
+ "cold_role",
+ "background_unproven",
)
"""Every reason the performance default queue leaves a cause out, in the order
it is checked."""
+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"})
@@ -411,16 +420,47 @@ def perf_strategy_verdict(
return _verdict(reason if reason in EXPECTED_REASONS else "expected")
+def _role_reason(item: Any) -> Reason | None:
+ """Why the role running *item*'s loop keeps it out, or ``None``.
+
+ A loop only startup, a CLI, tooling or tests run is paid once per process.
+ A scheduled job's loop matters only once it is shown to grow with the data.
+ """
+ facets = perf_facets(item)
+ role = field(item, "execution_role") or facets.get("execution_role") or "unknown"
+ if role in COLD_ROLES:
+ return "cold_role"
+ if role == "scheduled_job" and facets.get("loop_magnitude") != "grows_with_data":
+ return "background_unproven"
+ return None
+
+
+QueueProof = Literal["proven", "unproven", "background_unproven"]
+QUEUE_PROOFS: tuple[str, ...] = get_args(QueueProof)
+"""The stored ``cost_proof`` column: :data:`worth.COST_PROOFS` plus a scheduled
+job whose loop is not shown to grow. Only ``proven`` is in the default queue, so
+the column and :func:`perf_queue_verdict` agree on what it holds."""
+
+
+def queue_proof(item: Any) -> QueueProof:
+ """The proof the queue filters on, checked in the verdict's order: an
+ unmeasured loop first, then a background job without proven growth."""
+ proof = cost_proof(item)
+ if proof == "proven" and _role_reason(item) == "background_unproven":
+ return "background_unproven"
+ return proof
+
+
def perf_queue_verdict(item: Any) -> Verdict:
"""Whether the performance default queue holds *item*.
- One reason per cause, context first and proof last, so the counts of every
+ 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)
if verdict.eligible and cost_proof(item) not in DEFAULT_QUEUE_PROOFS:
return Verdict("unmeasured_cost")
- return verdict
+ return verdict if not verdict.eligible else _verdict(_role_reason(item))
def perf_queue_counts(items: Iterable[Any]) -> dict[str, Any]:
@@ -491,12 +531,15 @@ __all__ = [
"LOW_VALUE_KINDS",
"MIN_WORTH",
"ORIGIN_EXCLUSION",
+ "QUEUE_PROOFS",
+ "QUEUE_ROLES",
"REASONS",
"SCOPE_EXCLUSIONS",
"SMALL_CCN",
"SMALL_NLOC",
"UNAUDITED_KINDS",
"DeadSpan",
+ "QueueProof",
"Reason",
"Tally",
"UnitFacts",
@@ -510,6 +553,7 @@ __all__ = [
"perf_queue_counts",
"perf_queue_verdict",
"perf_strategy_verdict",
+ "queue_proof",
"refactor_verdict",
"small",
"unit_verdict",
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 b18b55c97..ff105be64 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
@@ -14,6 +14,7 @@ for the same reason - they can no longer describe the current tree.
from __future__ import annotations
import json
+from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, NamedTuple
from sqlalchemy import delete, func, select, update
@@ -31,6 +32,7 @@ from ...sql import order_by, rule_predicate
from .refactoring import _refactoring_row_kwargs
if TYPE_CHECKING:
+ from ....analysis.execution_roles import ExecutionRoles
from ....analysis.health.perf.opportunities import (
PerformanceOpportunity as OpportunityModel,
)
@@ -102,7 +104,7 @@ def _row_kwargs(
plan: dict[str, Any] | None = None,
) -> dict[str, Any]:
from ....analysis.health.perf.serving import intervention_file
- from ....analysis.health.worth import cost_proof
+ from ....analysis.health.queue.eligibility import queue_proof
fix = opportunity.fix
return {
@@ -117,7 +119,8 @@ def _row_kwargs(
"actionability_state": opportunity.actionability_state,
"evidence_confidence": opportunity.confidence,
"plan_state": plan_state,
- "cost_proof": cost_proof(opportunity),
+ "cost_proof": queue_proof(opportunity),
+ "execution_role": opportunity.facets.get("execution_role", "unknown"),
"fix_strategy": fix.strategy if fix else None,
"fix_safety": fix.safety if fix else None,
"file_path": intervention_file(opportunity),
@@ -138,8 +141,11 @@ def _summary_payload(
) -> dict:
"""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_queue_counts, perf_queue_verdict
- from ....analysis.health.worth import cost_proof
+ from ....analysis.health.queue.eligibility import (
+ perf_queue_counts,
+ perf_queue_verdict,
+ queue_proof,
+ )
counts: dict[str, int] = {}
contexts: dict[str, int] = {}
@@ -150,7 +156,7 @@ def _summary_payload(
contexts[item.execution_context] = contexts.get(item.execution_context, 0) + 1
key = item.boundary_kind or "none"
boundaries[key] = boundaries.get(key, 0) + 1
- proof = cost_proof(item)
+ 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.
@@ -198,6 +204,7 @@ async def finalize_performance_opportunities(
*,
analyzed_commit: str | None = None,
plan_policy: PerformancePlanPolicy | None = None,
+ execution_roles: ExecutionRoles | None = None,
) -> int:
"""Rebuild this repository's performance read model from stored findings.
@@ -205,6 +212,10 @@ async def finalize_performance_opportunities(
own rows land and inside their transaction, so the queue can never describe
a set of findings that was never committed. Returns the number of open
opportunities.
+
+ *execution_roles* is this run's role map over the whole graph. A role can
+ change in a file the run did not rescan (a seed or call moved elsewhere),
+ so every stored finding is restamped from it before grouping.
"""
# Deferred throughout this module: the analysis package imports
# persistence, so a module-level import here would close the cycle.
@@ -223,6 +234,8 @@ async def finalize_performance_opportunities(
)
).all()
)
+ if execution_roles is not None:
+ rows = await _restamp_roles(session, rows, execution_roles)
opportunities = build_performance_opportunities(rows, evidence_limit=_EVIDENCE_LIMIT)
await _restamp_findings(session, rows)
@@ -234,6 +247,35 @@ async def finalize_performance_opportunities(
return len(opportunities)
+async def _restamp_roles(
+ session: AsyncSession, rows: list[Any], roles: ExecutionRoles
+) -> list[Any]:
+ """Each stored finding with its loop owner's current role; changed rows are written.
+
+ A row stored before ``role_owner`` existed gets its owner found the way
+ the analysis finds it, and keeps it from then on.
+ """
+ out: list[Any] = []
+ changed = []
+ for row in rows:
+ details = json.loads(row.details_json or "{}")
+ if "role_owner" in details:
+ owner = details["role_owner"]
+ else:
+ owner = roles.owner_of(row.file_path, row.line_start, details)
+ role = roles.role_of(owner, row.file_path)
+ if details.get("execution_role") == role and "role_owner" in details:
+ out.append(row)
+ continue
+ stamped = {**details, "execution_role": role, "role_owner": owner}
+ details_json = json.dumps(stamped, separators=(",", ":"))
+ changed.append({"id": row.id, "details_json": details_json})
+ out.append(SimpleNamespace(**{**row._mapping, "details_json": details_json}))
+ if changed:
+ await session.execute(update(HealthFinding), changed)
+ return out
+
+
async def _restamp_findings(session: AsyncSession, rows: list[Any]) -> None:
"""Point every stored observation at its cause, and give it a public id.
@@ -465,6 +507,7 @@ async def list_performance_opportunities(
confidence: str | None = None,
actionabilities: frozenset[str] | None = None,
proofs: frozenset[str] | None = None,
+ roles: frozenset[str] | None = None,
file_paths: tuple[str, ...] | None = None,
sort: str = "rank",
limit: int = 20,
@@ -484,6 +527,7 @@ async def list_performance_opportunities(
confidence=confidence,
actionabilities=actionabilities,
proofs=proofs,
+ roles=roles,
file_paths=file_paths,
)
total = int(
@@ -514,7 +558,7 @@ async def performance_facet_counts(
repository_id: str,
*,
file_paths: tuple[str, ...] | None = None,
-) -> list[tuple[str, str | None, str, str, str, str, int]]:
+) -> list[tuple[str, str | None, str, str, str, str, str, int]]:
"""Grouped counts over every open opportunity, in one aggregate statement.
Returned pre-aggregation, one ``(*FACET_FIELDS, count)`` tuple per group,
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 5f0a21dae..4f89932fd 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -1959,6 +1959,11 @@ class PerformanceOpportunity(Base):
cost_proof: Mapped[str] = mapped_column(
String(16), nullable=False, default="proven", server_default="proven"
)
+ # ``execution_roles.ExecutionRole`` of the hottest member's loop owner, so
+ # the queue can leave out startup, CLI, tooling and test loops in SQL.
+ execution_role: Mapped[str] = mapped_column(
+ String(16), nullable=False, default="unknown", server_default="unknown"
+ )
fix_strategy: Mapped[str | None] = mapped_column(String(64), nullable=True)
fix_safety: Mapped[str | None] = mapped_column(String(16), nullable=True)
# The file holding the symbol worth editing, so target scoping is a column.
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 67e6d397d..d4287a402 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -1345,6 +1345,7 @@ async def persist_partial_health(
repo_id,
analyzed_commit=analyzed_commit,
plan_policy=getattr(report, "performance_plan_policy", None),
+ execution_roles=getattr(report, "execution_roles", None),
)
# Repository-wide, like the queue above and for the same reason: an
# opportunity folds a file's plans, and a file this run did not touch
@@ -2223,6 +2224,7 @@ async def persist_incremental_index(
repo_id,
analyzed_commit=analyzed_commit,
plan_policy=getattr(partial_health_report, "performance_plan_policy", None),
+ execution_roles=getattr(partial_health_report, "execution_roles", None),
)
await finalize_refactoring_opportunities(
session, repo_id, analyzed_commit=analyzed_commit
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 6f72bc007..12106d890 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1953,6 +1953,7 @@ async def save_full_health_report(
repo_id,
analyzed_commit=analyzed_commit,
plan_policy=getattr(hr, "performance_plan_policy", None),
+ execution_roles=getattr(hr, "execution_roles", None),
)
# Fold the plans just written into per-file opportunities. Last in the
# savepoint because it composes over the stored rows, so it has to see
diff --git a/packages/server/src/repowise/server/routers/code_health/performance_routes.py b/packages/server/src/repowise/server/routers/code_health/performance_routes.py
index bc52793a7..71fcb959c 100644
--- a/packages/server/src/repowise/server/routers/code_health/performance_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/performance_routes.py
@@ -71,6 +71,14 @@ async def list_performance_opportunities(
"to grow, kept out of the default queue and counted in its summary."
),
),
+ role: str | None = Query(
+ None,
+ description=(
+ "Execution role: request, event_consumer, scheduled_job, startup, cli, "
+ "tooling, test, unknown or all. Defaults to every role but startup, cli, "
+ "tooling and test, whose loops run once per process."
+ ),
+ ),
view: str = Query("detail"),
sort: str = Query("rank"),
file_paths: str | None = Query(
@@ -95,6 +103,7 @@ async def list_performance_opportunities(
confidence=confidence,
actionability=actionability,
proof=proof,
+ role=role,
view=view,
sort=sort,
file_paths=_paths(file_paths),
diff --git a/packages/server/src/repowise/server/services/performance_health.py b/packages/server/src/repowise/server/services/performance_health.py
index 52e55085a..08aab49df 100644
--- a/packages/server/src/repowise/server/services/performance_health.py
+++ b/packages/server/src/repowise/server/services/performance_health.py
@@ -97,6 +97,7 @@ class PerformanceHealthService:
confidence=query.confidence,
actionabilities=query.actionabilities,
proofs=query.proofs,
+ roles=query.roles,
file_paths=query.file_paths,
sort=query.sort,
limit=query.limit,
diff --git a/packages/types/src/health.ts b/packages/types/src/health.ts
index 108760142..dfe5539d3 100644
--- a/packages/types/src/health.ts
+++ b/packages/types/src/health.ts
@@ -353,6 +353,23 @@ export interface HealthFinding {
}
export type PerformanceExecutionContext = "production" | "tooling" | "test" | "unknown";
+
+/**
+ * What runs a cause's loop (`execution_roles.EXECUTION_ROLES`). `unknown` means
+ * no request, job, startup or CLI seed reaches it, not that nothing does.
+ */
+export const PERFORMANCE_EXECUTION_ROLES = [
+ "request",
+ "event_consumer",
+ "scheduled_job",
+ "startup",
+ "cli",
+ "ui",
+ "tooling",
+ "test",
+ "unknown",
+] as const;
+export type PerformanceExecutionRole = (typeof PERFORMANCE_EXECUTION_ROLES)[number];
export type PerformanceOpportunityConfidence = "high" | "medium" | "low";
export interface PerformanceOpportunityFix {
@@ -405,6 +422,8 @@ export interface PerformanceOpportunityFacets {
change_risk: string;
/** Absent on rows stored before the fact existed. */
loop_magnitude?: PerformanceLoopMagnitude;
+ /** Absent on rows stored before the fact existed. */
+ execution_role?: PerformanceExecutionRole;
}
/**
@@ -570,14 +589,16 @@ export type PerformanceFacetKey =
| "confidence"
| "actionability"
| "plan_state"
- | "proof";
+ | "proof"
+ | "role";
/**
* Whether anything measured that a cause's cost grows with the data
- * (`worth.COST_PROOFS`). The queue holds `proven` causes unless asked for
- * `unproven` ones, which never lead.
+ * (`eligibility.QUEUE_PROOFS`). The queue holds `proven` causes unless asked
+ * for another value. `background_unproven` is a scheduled job whose loop is
+ * not shown to grow; neither unproven kind leads.
*/
-export type PerformanceCostProof = "proven" | "unproven";
+export type PerformanceCostProof = "proven" | "unproven" | "background_unproven";
export type PerformanceFacets = Partial<Record<PerformanceFacetKey, PerformanceFacetCount[]>>;
@@ -602,6 +623,8 @@ export type PerformanceOpportunityQuery = {
actionability?: PerformanceActionabilityState;
/** Absent means `proven`; `unproven` lists the causes the default queue leaves out. */
proof?: PerformanceCostProof;
+ /** Absent means every role but startup, cli, ui, tooling and test; `all` lists every role. */
+ role?: PerformanceExecutionRole | "all";
/** `summary` drops the explanatory fields and keeps identity and counts. */
view?: "detail" | "summary";
sort?: "rank" | "leverage" | "observations";
@@ -624,7 +647,9 @@ export type PerformanceQueueExclusion =
| "cold_path"
| "expected"
| "no_strategy"
- | "unmeasured_cost";
+ | "unmeasured_cost"
+ | "cold_role"
+ | "background_unproven";
export interface PerformanceDefaultQueue {
total: number;
diff --git a/packages/ui/__tests__/health/performance-query.test.ts b/packages/ui/__tests__/health/performance-query.test.ts
index 3ce117522..67bb110e9 100644
--- a/packages/ui/__tests__/health/performance-query.test.ts
+++ b/packages/ui/__tests__/health/performance-query.test.ts
@@ -26,6 +26,7 @@ describe("performance filter state", () => {
confidence: "high" as const,
actionability: "plan_ready" as const,
proof: "unproven" as const,
+ role: "cli" as const,
sort: "leverage" as const,
offset: 40,
};
@@ -41,6 +42,15 @@ describe("performance filter state", () => {
expect(clearNarrowing(unproven).proof).toBeNull();
});
+ it("asks for a cold role only when chosen", () => {
+ // Absent means the server's default: every role but startup, CLI, tooling and test.
+ expect(toQuery(INITIAL_FILTERS, { limit: 20 }).role).toBeUndefined();
+ const cli = withFilter(INITIAL_FILTERS, "role", "cli");
+ expect(toQuery(cli, { limit: 20 }).role).toBe("cli");
+ expect(narrowingCount(cli)).toBe(1);
+ expect(clearNarrowing(cli).role).toBeNull();
+ });
+
it("round trips the expected actionability state", () => {
// expected sits out of the default queue but is still a real, selectable
// state: the round trip must not treat it as unrecognized.
diff --git a/packages/ui/src/health/performance/filters.tsx b/packages/ui/src/health/performance/filters.tsx
index 90896fac8..822d5676d 100644
--- a/packages/ui/src/health/performance/filters.tsx
+++ b/packages/ui/src/health/performance/filters.tsx
@@ -98,6 +98,9 @@ const NARROWING: NarrowingSpec[] = [
{ key: "confidence", facet: "confidence", anyLabel: "Any" },
// Unproven causes (loop size unknown) are counted but never queued by default.
{ key: "proof", facet: "proof", anyLabel: "Measured only" },
+ // Startup, CLI, tooling and test loops run once per process, so the default
+ // leaves them out; each role stays one selection away.
+ { key: "role", facet: "role", anyLabel: "Served paths" },
];
/**
diff --git a/packages/ui/src/health/performance/presentation.ts b/packages/ui/src/health/performance/presentation.ts
index 7967e7bd7..2067b6e98 100644
--- a/packages/ui/src/health/performance/presentation.ts
+++ b/packages/ui/src/health/performance/presentation.ts
@@ -65,11 +65,13 @@ export const FACET_LABEL: Record<PerformanceFacetKey, string> = {
actionability: "Actionability",
plan_state: "Plan",
proof: "Cost",
+ role: "Runs in",
};
const PROOF_LABEL: Record<PerformanceCostProof, string> = {
proven: "Measured",
unproven: "Unproven: loop size unknown",
+ background_unproven: "Unproven: scheduled job, growth not shown",
};
// "Stored plan", not "Plan ready": that name belongs to the actionability
@@ -191,6 +193,7 @@ export function facetValueLabel(facet: PerformanceFacetKey, value: string): stri
if (facet === "actionability")
return ACTIONABILITY_LABEL[value as PerformanceActionabilityState] ?? humanizeToken(value);
if (facet === "proof") return PROOF_LABEL[value as PerformanceCostProof] ?? humanizeToken(value);
+ if (facet === "role") return humanizeToken(value);
return PLAN_STATE_LABEL[value] ?? humanizeToken(value);
}
@@ -263,6 +266,13 @@ export function affectedSummary(opportunity: PerformanceOpportunity): string {
return `${sitePart} across ${filePart}`;
}
+const ROLE_PHRASE: Record<string, string> = {
+ request: "runs on every request",
+ event_consumer: "runs on every message",
+ scheduled_job: "runs on a schedule",
+ unknown: "no evidence of what runs it",
+};
+
const MULTIPLIER_PHRASE: Record<string, string> = {
io_in_loop: "runs once per loop iteration",
serial_await_in_loop: "awaited one at a time",
@@ -291,6 +301,8 @@ export function whyRankedPhrase(factor: PerformanceWhyRanked): string {
return `${contextLabel(String(value) as PerformanceExecutionContext).toLowerCase()} code`;
case "entry_reachability":
return "reachable from an entry point";
+ case "execution_role":
+ return ROLE_PHRASE[String(value)] ?? humanizeToken(String(value));
case "loop_magnitude":
return value === "grows_with_data" ? "grows with the data" : humanizeToken(String(value));
case "provenance":
diff --git a/packages/ui/src/health/performance/query.ts b/packages/ui/src/health/performance/query.ts
index d0592492d..8ae8aab71 100644
--- a/packages/ui/src/health/performance/query.ts
+++ b/packages/ui/src/health/performance/query.ts
@@ -1,7 +1,9 @@
+import { PERFORMANCE_EXECUTION_ROLES } from "@repowise-dev/types/health";
import type {
PerformanceActionabilityState,
PerformanceContextFilter,
PerformanceCostProof,
+ PerformanceExecutionRole,
PerformanceOpportunityConfidence,
PerformanceOpportunityQuery,
} from "@repowise-dev/types/health";
@@ -23,6 +25,7 @@ export interface PerformanceFilterState {
confidence: PerformanceOpportunityConfidence | null;
actionability: PerformanceActionabilityState | null;
proof: PerformanceCostProof | null;
+ role: PerformanceExecutionRole | "all" | null;
sort: PerformanceSort;
offset: number;
}
@@ -39,12 +42,13 @@ export const INITIAL_FILTERS: PerformanceFilterState = {
confidence: null,
actionability: null,
proof: null,
+ role: null,
sort: "rank",
offset: 0,
};
/** The narrowing filters, apart from context, which is a permanent tab row. */
-const NARROWING_KEYS = ["boundary", "confidence", "actionability", "proof"] as const;
+const NARROWING_KEYS = ["boundary", "confidence", "actionability", "proof", "role"] as const;
export type NarrowingKey = (typeof NARROWING_KEYS)[number];
const SORTS: readonly PerformanceSort[] = ["rank", "leverage", "observations"];
@@ -55,7 +59,8 @@ const ACTIONABILITIES: readonly PerformanceActionabilityState[] = [
"investigate",
"expected",
];
-const PROOFS: readonly PerformanceCostProof[] = ["proven", "unproven"];
+const PROOFS: readonly PerformanceCostProof[] = ["proven", "unproven", "background_unproven"];
+const ROLES: readonly (PerformanceExecutionRole | "all")[] = ["all", ...PERFORMANCE_EXECUTION_ROLES];
const CONTEXTS: readonly PerformanceContextFilter[] = [
"all",
"production",
@@ -88,6 +93,7 @@ export function toQuery(
if (state.confidence) query.confidence = state.confidence;
if (state.actionability) query.actionability = state.actionability;
if (state.proof) query.proof = state.proof;
+ if (state.role) query.role = state.role;
return query;
}
@@ -108,6 +114,7 @@ export function serializeFilters(state: PerformanceFilterState): string {
if (state.confidence) params.set("confidence", state.confidence);
if (state.actionability) params.set("actionability", state.actionability);
if (state.proof) params.set("proof", state.proof);
+ if (state.role) params.set("role", state.role);
if (state.sort !== INITIAL_FILTERS.sort) params.set("sort", state.sort);
if (state.offset > 0) params.set("offset", String(state.offset));
return params.toString();
@@ -131,6 +138,7 @@ export function parseFilters(search: string | URLSearchParams): PerformanceFilte
confidence: oneOf(params.get("confidence"), CONFIDENCES),
actionability: oneOf(params.get("actionability"), ACTIONABILITIES),
proof: oneOf(params.get("proof"), PROOFS),
+ role: oneOf(params.get("role"), ROLES),
sort: oneOf(params.get("sort"), SORTS) ?? INITIAL_FILTERS.sort,
offset: Number.isFinite(offset) && offset > 0 ? offset : 0,
};
@@ -147,7 +155,7 @@ export function withFilter<K extends keyof PerformanceFilterState>(
}
export function clearNarrowing(state: PerformanceFilterState): PerformanceFilterState {
- return { ...state, boundary: null, confidence: null, actionability: null, proof: null, offset: 0 };
+ return { ...state, boundary: null, confidence: null, actionability: null, proof: null, role: null, offset: 0 };
}
export function narrowingCount(state: PerformanceFilterState): number {
diff --git a/tests/fixtures/perf_corpus/golden_opportunities.json b/tests/fixtures/perf_corpus/golden_opportunities.json
index e1c5d5a82..b3615977c 100644
--- a/tests/fixtures/perf_corpus/golden_opportunities.json
+++ b/tests/fixtures/perf_corpus/golden_opportunities.json
@@ -56,6 +56,7 @@
"actionability_confidence": "medium",
"amplification": "quadratic",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "entry_reachable",
"leverage": "local",
"loop_magnitude": "unknown"
@@ -79,13 +80,13 @@
"rank_factors": {
"affected_call_sites": 4,
"boundary_kind": 4,
- "entry_reachability": 3,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 6,
"provenance": 3
},
- "rank_score": 23,
+ "rank_score": 21,
"reliable_entry_reachability": true,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -118,65 +119,55 @@
{
"actionability_reason": "strategy_requires_validation",
"actionability_state": "advisory",
- "affected_call_sites_total": 3,
+ "affected_call_sites_total": 2,
"affected_files_total": 1,
- "biomarker_type": "io_in_loop",
+ "biomarker_type": "nested_loop_with_io",
"biomarker_types": [
- "io_in_loop"
+ "io_in_loop",
+ "nested_loop_with_io"
],
"boundary_kind": "db",
"confidence": "high",
"evidence": [
{
"biomarker_type": "io_in_loop",
- "file_path": "src/app/ledger.py",
- "finding_id": "finding_bb8108f2272355e7bb47",
- "function_name": "apply",
- "line_end": 587,
- "line_start": 587,
- "path": [
- "src/app/ledger.py::apply",
- "src/app/ledger.py::_move"
- ],
- "provenance": "call-site",
- "reason": "one_loop_many_sinks: io_in_loop at src/app/ledger.py:587 repeats work per iteration."
- },
- {
- "biomarker_type": "io_in_loop",
- "file_path": "src/app/ledger.py",
- "finding_id": "finding_6679c8c4aeba8ea75c58",
- "function_name": "apply",
- "line_end": 590,
- "line_start": 590,
+ "file_path": "src/app/reindex.py",
+ "finding_id": "finding_dd1107d677ac5244c707",
+ "function_name": "one",
+ "line_end": 212,
+ "line_start": 210,
"path": [
- "src/app/ledger.py::apply",
- "src/app/ledger.py::_fold_one"
+ "src/app/reindex.py::one",
+ "src/app/reindex.py::_write",
+ "src/app/db.py::upsert"
],
"provenance": "call-site",
- "reason": "one_loop_many_sinks: io_in_loop at src/app/ledger.py:590 repeats work per iteration."
+ "reason": "cost_shape_merge: io_in_loop at src/app/reindex.py:210 repeats work per iteration."
},
{
- "biomarker_type": "io_in_loop",
- "file_path": "src/app/ledger.py",
- "finding_id": "finding_b80478e54b854ac7d586",
- "function_name": "apply",
- "line_end": 591,
- "line_start": 591,
+ "biomarker_type": "nested_loop_with_io",
+ "file_path": "src/app/reindex.py",
+ "finding_id": "finding_e7a60ff74d2f2b7ca67b",
+ "function_name": "many",
+ "line_end": 217,
+ "line_start": 215,
"path": [
- "src/app/ledger.py::apply",
- "src/app/ledger.py::_write_alias"
+ "src/app/reindex.py::many",
+ "src/app/reindex.py::_write",
+ "src/app/db.py::upsert"
],
"provenance": "call-site",
- "reason": "one_loop_many_sinks: io_in_loop at src/app/ledger.py:591 repeats work per iteration."
+ "reason": "cost_shape_merge: nested_loop_with_io at src/app/reindex.py:215 repeats work per iteration."
}
],
"evidence_truncated": false,
"execution_context": "production",
"facets": {
"actionability_confidence": "medium",
- "amplification": "per_iteration",
+ "amplification": "quadratic",
"change_risk": "contained",
- "exposure": "entry_reachable",
+ "execution_role": "unknown",
+ "exposure": "unknown",
"leverage": "local",
"loop_magnitude": "unknown"
},
@@ -185,11 +176,11 @@
"safety": "advisory",
"strategy": "batch_or_prefetch_io"
},
- "intervention_kind": "function",
- "intervention_symbol": "src/app/ledger.py::apply",
+ "intervention_kind": "shared_helper",
+ "intervention_symbol": "src/app/reindex.py::_write",
"may_lead": false,
- "observations_total": 3,
- "opportunity_id": "perf3_2719b6813419ad35948b",
+ "observations_total": 2,
+ "opportunity_id": "perf3_a123c4c38fdb1cabaa6a",
"performance_model_version": 3,
"prerequisites": [
"batch_api_contract",
@@ -197,30 +188,31 @@
],
"provenance": "call-site",
"rank_factors": {
- "affected_call_sites": 4,
+ "affected_call_sites": 3,
"boundary_kind": 4,
- "entry_reachability": 3,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
- "multiplier_shape": 4,
+ "multiplier_shape": 6,
"provenance": 3
},
- "rank_score": 21,
- "reliable_entry_reachability": true,
+ "rank_score": 20,
+ "reliable_entry_reachability": null,
"resource_fingerprints": [],
- "shared_path_suffix": [],
+ "shared_path_suffix": [
+ "src/app/reindex.py::_write",
+ "src/app/db.py::upsert"
+ ],
"siblings": [],
- "terminal_sink": null,
+ "terminal_sink": "src/app/db.py::upsert",
"terminal_sinks": [
- "src/app/ledger.py::_fold_one",
- "src/app/ledger.py::_move",
- "src/app/ledger.py::_write_alias"
+ "src/app/db.py::upsert"
],
"why_ranked": [
{
- "factor": "affected_call_sites",
- "points": 4,
- "value": 3
+ "factor": "multiplier_shape",
+ "points": 6,
+ "value": "nested_loop_with_io"
},
{
"factor": "boundary_kind",
@@ -228,16 +220,16 @@
"value": "db"
},
{
- "factor": "multiplier_shape",
- "points": 4,
- "value": "io_in_loop"
+ "factor": "affected_call_sites",
+ "points": 3,
+ "value": 2
}
]
},
{
- "actionability_reason": "strategy_requires_validation",
- "actionability_state": "advisory",
- "affected_call_sites_total": 2,
+ "actionability_reason": "proven_strategy",
+ "actionability_state": "plan_ready",
+ "affected_call_sites_total": 1,
"affected_files_total": 1,
"biomarker_type": "io_in_loop",
"biomarker_types": [
@@ -248,82 +240,57 @@
"evidence": [
{
"biomarker_type": "io_in_loop",
- "file_path": "src/app/entry.py",
- "finding_id": "finding_d1b7702a840faaee6230",
- "function_name": "a",
- "line_end": 252,
- "line_start": 250,
- "path": [
- "src/app/entry.py::a",
- "src/app/entry.py::_hit",
- "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": "finding_66292afa8823b8db693a",
- "function_name": "b",
- "line_end": 257,
- "line_start": 255,
- "path": [
- "src/app/entry.py::b",
- "src/app/entry.py::_hit",
- "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."
+ "file_path": "src/app/owners.py",
+ "finding_id": "finding_c7e0cff49d2e4944af6c",
+ "function_name": "load_owners",
+ "line_end": 22,
+ "line_start": 20,
+ "path": [],
+ "provenance": "direct",
+ "reason": "batch_form_equivalent: io_in_loop at src/app/owners.py:20 repeats work per iteration."
}
],
"evidence_truncated": false,
"execution_context": "production",
"facets": {
- "actionability_confidence": "medium",
+ "actionability_confidence": "high",
"amplification": "per_iteration",
"change_risk": "contained",
- "exposure": "entry_reachable",
- "leverage": "local",
- "loop_magnitude": "unknown"
+ "execution_role": "unknown",
+ "exposure": "unknown",
+ "leverage": "isolated",
+ "loop_magnitude": "grows_with_data"
},
"fix": {
- "rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
- "safety": "advisory",
+ "api": ".in_(\"repo_id\", keys)",
+ "rationale": "Every call filters on the loop's own key, so .in_(\"repo_id\", keys) covers the same rows, and nothing else in the loop can observe the difference.",
+ "safety": "proven",
"strategy": "batch_or_prefetch_io"
},
- "intervention_kind": "shared_helper",
- "intervention_symbol": "src/app/entry.py::_hit",
- "may_lead": false,
- "observations_total": 2,
- "opportunity_id": "perf3_6690af4c5e3f269c266e",
+ "intervention_kind": "function",
+ "intervention_symbol": "src/app/owners.py::load_owners",
+ "may_lead": true,
+ "observations_total": 1,
+ "opportunity_id": "perf3_83d258547498bed60226",
"performance_model_version": 3,
- "prerequisites": [
- "batch_api_contract",
- "result_equivalence"
- ],
- "provenance": "call-site",
+ "prerequisites": [],
+ "provenance": "direct",
"rank_factors": {
- "affected_call_sites": 3,
+ "affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 3,
"execution_context": 3,
- "loop_magnitude": 0,
+ "execution_role": 1,
+ "loop_magnitude": 2,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 20,
- "reliable_entry_reachability": true,
+ "rank_score": 19,
+ "reliable_entry_reachability": null,
"resource_fingerprints": [],
- "shared_path_suffix": [
- "src/app/entry.py::_hit",
- "src/app/db.py::reach_sink"
- ],
+ "shared_path_suffix": [],
"siblings": [],
- "terminal_sink": "src/app/db.py::reach_sink",
- "terminal_sinks": [
- "src/app/db.py::reach_sink"
- ],
+ "terminal_sink": null,
+ "terminal_sinks": [],
"why_ranked": [
{
"factor": "boundary_kind",
@@ -336,16 +303,16 @@
"value": "io_in_loop"
},
{
- "factor": "affected_call_sites",
+ "factor": "execution_context",
"points": 3,
- "value": 2
+ "value": "production"
}
]
},
{
"actionability_reason": "strategy_requires_validation",
"actionability_state": "advisory",
- "affected_call_sites_total": 2,
+ "affected_call_sites_total": 3,
"affected_files_total": 1,
"biomarker_type": "io_in_loop",
"biomarker_types": [
@@ -356,33 +323,45 @@
"evidence": [
{
"biomarker_type": "io_in_loop",
- "file_path": "src/app/api.py",
- "finding_id": "finding_165492e638f0ce198bad",
- "function_name": "list_users",
- "line_end": 32,
- "line_start": 30,
+ "file_path": "src/app/ledger.py",
+ "finding_id": "finding_bb8108f2272355e7bb47",
+ "function_name": "apply",
+ "line_end": 587,
+ "line_start": 587,
"path": [
- "src/app/api.py::list_users",
- "src/app/repo.py::fetch_page",
- "src/app/db.py::execute"
+ "src/app/ledger.py::apply",
+ "src/app/ledger.py::_move"
],
"provenance": "call-site",
- "reason": "specific_shared_helper: io_in_loop at src/app/api.py:30 repeats work per iteration."
+ "reason": "one_loop_many_sinks: io_in_loop at src/app/ledger.py:587 repeats work per iteration."
},
{
"biomarker_type": "io_in_loop",
- "file_path": "src/app/api.py",
- "finding_id": "finding_7a74222fa7b3681d4b81",
- "function_name": "list_orders",
- "line_end": 33,
- "line_start": 31,
+ "file_path": "src/app/ledger.py",
+ "finding_id": "finding_6679c8c4aeba8ea75c58",
+ "function_name": "apply",
+ "line_end": 590,
+ "line_start": 590,
"path": [
- "src/app/api.py::list_orders",
- "src/app/repo.py::fetch_page",
- "src/app/db.py::execute"
+ "src/app/ledger.py::apply",
+ "src/app/ledger.py::_fold_one"
],
"provenance": "call-site",
- "reason": "specific_shared_helper: io_in_loop at src/app/api.py:31 repeats work per iteration."
+ "reason": "one_loop_many_sinks: io_in_loop at src/app/ledger.py:590 repeats work per iteration."
+ },
+ {
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/ledger.py",
+ "finding_id": "finding_b80478e54b854ac7d586",
+ "function_name": "apply",
+ "line_end": 591,
+ "line_start": 591,
+ "path": [
+ "src/app/ledger.py::apply",
+ "src/app/ledger.py::_write_alias"
+ ],
+ "provenance": "call-site",
+ "reason": "one_loop_many_sinks: io_in_loop at src/app/ledger.py:591 repeats work per iteration."
}
],
"evidence_truncated": false,
@@ -391,6 +370,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "entry_reachable",
"leverage": "local",
"loop_magnitude": "unknown"
@@ -400,11 +380,11 @@
"safety": "advisory",
"strategy": "batch_or_prefetch_io"
},
- "intervention_kind": "shared_helper",
- "intervention_symbol": "src/app/repo.py::fetch_page",
+ "intervention_kind": "function",
+ "intervention_symbol": "src/app/ledger.py::apply",
"may_lead": false,
- "observations_total": 2,
- "opportunity_id": "perf3_8456a319d03ac90c6041",
+ "observations_total": 3,
+ "opportunity_id": "perf3_2719b6813419ad35948b",
"performance_model_version": 3,
"prerequisites": [
"batch_api_contract",
@@ -412,27 +392,31 @@
],
"provenance": "call-site",
"rank_factors": {
- "affected_call_sites": 3,
+ "affected_call_sites": 4,
"boundary_kind": 4,
- "entry_reachability": 3,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 20,
+ "rank_score": 19,
"reliable_entry_reachability": true,
"resource_fingerprints": [],
- "shared_path_suffix": [
- "src/app/repo.py::fetch_page",
- "src/app/db.py::execute"
- ],
+ "shared_path_suffix": [],
"siblings": [],
- "terminal_sink": "src/app/db.py::execute",
+ "terminal_sink": null,
"terminal_sinks": [
- "src/app/db.py::execute"
+ "src/app/ledger.py::_fold_one",
+ "src/app/ledger.py::_move",
+ "src/app/ledger.py::_write_alias"
],
"why_ranked": [
+ {
+ "factor": "affected_call_sites",
+ "points": 4,
+ "value": 3
+ },
{
"factor": "boundary_kind",
"points": 4,
@@ -442,110 +426,100 @@
"factor": "multiplier_shape",
"points": 4,
"value": "io_in_loop"
- },
- {
- "factor": "affected_call_sites",
- "points": 3,
- "value": 2
}
]
},
{
- "actionability_reason": "strategy_requires_validation",
- "actionability_state": "advisory",
+ "actionability_reason": "no_supported_strategy",
+ "actionability_state": "investigate",
"affected_call_sites_total": 2,
"affected_files_total": 1,
- "biomarker_type": "nested_loop_with_io",
+ "biomarker_type": "blocking_io_under_lock",
"biomarker_types": [
- "io_in_loop",
- "nested_loop_with_io"
+ "blocking_io_under_lock"
],
"boundary_kind": "db",
"confidence": "high",
"evidence": [
{
- "biomarker_type": "io_in_loop",
- "file_path": "src/app/reindex.py",
- "finding_id": "finding_dd1107d677ac5244c707",
- "function_name": "one",
- "line_end": 212,
- "line_start": 210,
+ "biomarker_type": "blocking_io_under_lock",
+ "file_path": "src/app/pool.py",
+ "finding_id": "finding_2cca2a2e17c82f868f98",
+ "function_name": "reaper",
+ "line_end": 132,
+ "line_start": 130,
"path": [
- "src/app/reindex.py::one",
- "src/app/reindex.py::_write",
- "src/app/db.py::upsert"
+ "src/app/pool.py::reaper",
+ "src/app/store.py::flush_all",
+ "src/app/store.py::flush"
],
"provenance": "call-site",
- "reason": "cost_shape_merge: io_in_loop at src/app/reindex.py:210 repeats work per iteration."
+ "reason": "distinct_lock_owners: blocking_io_under_lock at src/app/pool.py:130 repeats work per iteration."
},
{
- "biomarker_type": "nested_loop_with_io",
- "file_path": "src/app/reindex.py",
- "finding_id": "finding_e7a60ff74d2f2b7ca67b",
- "function_name": "many",
- "line_end": 217,
- "line_start": 215,
+ "biomarker_type": "blocking_io_under_lock",
+ "file_path": "src/app/pool.py",
+ "finding_id": "finding_401246625d2b912b7c5c",
+ "function_name": "writer",
+ "line_end": 132,
+ "line_start": 130,
"path": [
- "src/app/reindex.py::many",
- "src/app/reindex.py::_write",
- "src/app/db.py::upsert"
+ "src/app/pool.py::writer",
+ "src/app/store.py::flush_all",
+ "src/app/store.py::flush"
],
"provenance": "call-site",
- "reason": "cost_shape_merge: nested_loop_with_io at src/app/reindex.py:215 repeats work per iteration."
+ "reason": "distinct_lock_owners: blocking_io_under_lock at src/app/pool.py:130 repeats work per iteration."
}
],
"evidence_truncated": false,
"execution_context": "production",
"facets": {
- "actionability_confidence": "medium",
- "amplification": "quadratic",
+ "actionability_confidence": "low",
+ "amplification": "per_iteration",
"change_risk": "contained",
- "exposure": "unknown",
- "leverage": "local",
- "loop_magnitude": "unknown"
- },
- "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"
+ "execution_role": "unknown",
+ "exposure": "unknown",
+ "leverage": "local",
+ "loop_magnitude": "unknown"
},
+ "fix": null,
"intervention_kind": "shared_helper",
- "intervention_symbol": "src/app/reindex.py::_write",
+ "intervention_symbol": "src/app/store.py::flush_all",
"may_lead": false,
"observations_total": 2,
- "opportunity_id": "perf3_a123c4c38fdb1cabaa6a",
+ "opportunity_id": "perf3_d3dace3672249fc9bd03",
"performance_model_version": 3,
"prerequisites": [
- "batch_api_contract",
- "result_equivalence"
+ "single_lock_owner"
],
"provenance": "call-site",
"rank_factors": {
"affected_call_sites": 3,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
- "multiplier_shape": 6,
+ "multiplier_shape": 5,
"provenance": 3
},
"rank_score": 19,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
- "src/app/reindex.py::_write",
- "src/app/db.py::upsert"
+ "src/app/store.py::flush_all",
+ "src/app/store.py::flush"
],
"siblings": [],
- "terminal_sink": "src/app/db.py::upsert",
+ "terminal_sink": "src/app/store.py::flush",
"terminal_sinks": [
- "src/app/db.py::upsert"
+ "src/app/store.py::flush"
],
"why_ranked": [
{
"factor": "multiplier_shape",
- "points": 6,
- "value": "nested_loop_with_io"
+ "points": 5,
+ "value": "blocking_io_under_lock"
},
{
"factor": "boundary_kind",
@@ -560,9 +534,9 @@
]
},
{
- "actionability_reason": "proven_strategy",
- "actionability_state": "plan_ready",
- "affected_call_sites_total": 1,
+ "actionability_reason": "strategy_requires_validation",
+ "actionability_state": "advisory",
+ "affected_call_sites_total": 2,
"affected_files_total": 1,
"biomarker_type": "io_in_loop",
"biomarker_types": [
@@ -573,56 +547,83 @@
"evidence": [
{
"biomarker_type": "io_in_loop",
- "file_path": "src/app/owners.py",
- "finding_id": "finding_c7e0cff49d2e4944af6c",
- "function_name": "load_owners",
- "line_end": 22,
- "line_start": 20,
- "path": [],
- "provenance": "direct",
- "reason": "batch_form_equivalent: io_in_loop at src/app/owners.py:20 repeats work per iteration."
+ "file_path": "src/app/entry.py",
+ "finding_id": "finding_d1b7702a840faaee6230",
+ "function_name": "a",
+ "line_end": 252,
+ "line_start": 250,
+ "path": [
+ "src/app/entry.py::a",
+ "src/app/entry.py::_hit",
+ "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": "finding_66292afa8823b8db693a",
+ "function_name": "b",
+ "line_end": 257,
+ "line_start": 255,
+ "path": [
+ "src/app/entry.py::b",
+ "src/app/entry.py::_hit",
+ "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",
"facets": {
- "actionability_confidence": "high",
+ "actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
- "exposure": "unknown",
- "leverage": "isolated",
- "loop_magnitude": "grows_with_data"
+ "execution_role": "unknown",
+ "exposure": "entry_reachable",
+ "leverage": "local",
+ "loop_magnitude": "unknown"
},
"fix": {
- "api": ".in_(\"repo_id\", keys)",
- "rationale": "Every call filters on the loop's own key, so .in_(\"repo_id\", keys) covers the same rows, and nothing else in the loop can observe the difference.",
- "safety": "proven",
+ "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_kind": "function",
- "intervention_symbol": "src/app/owners.py::load_owners",
- "may_lead": true,
- "observations_total": 1,
- "opportunity_id": "perf3_83d258547498bed60226",
+ "intervention_kind": "shared_helper",
+ "intervention_symbol": "src/app/entry.py::_hit",
+ "may_lead": false,
+ "observations_total": 2,
+ "opportunity_id": "perf3_6690af4c5e3f269c266e",
"performance_model_version": 3,
- "prerequisites": [],
- "provenance": "direct",
+ "prerequisites": [
+ "batch_api_contract",
+ "result_equivalence"
+ ],
+ "provenance": "call-site",
"rank_factors": {
- "affected_call_sites": 2,
+ "affected_call_sites": 3,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
- "loop_magnitude": 2,
+ "execution_role": 1,
+ "loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
"rank_score": 18,
- "reliable_entry_reachability": null,
+ "reliable_entry_reachability": true,
"resource_fingerprints": [],
- "shared_path_suffix": [],
+ "shared_path_suffix": [
+ "src/app/entry.py::_hit",
+ "src/app/db.py::reach_sink"
+ ],
"siblings": [],
- "terminal_sink": null,
- "terminal_sinks": [],
+ "terminal_sink": "src/app/db.py::reach_sink",
+ "terminal_sinks": [
+ "src/app/db.py::reach_sink"
+ ],
"why_ranked": [
{
"factor": "boundary_kind",
@@ -635,108 +636,114 @@
"value": "io_in_loop"
},
{
- "factor": "execution_context",
+ "factor": "affected_call_sites",
"points": 3,
- "value": "production"
+ "value": 2
}
]
},
{
- "actionability_reason": "no_supported_strategy",
- "actionability_state": "investigate",
+ "actionability_reason": "strategy_requires_validation",
+ "actionability_state": "advisory",
"affected_call_sites_total": 2,
"affected_files_total": 1,
- "biomarker_type": "blocking_io_under_lock",
+ "biomarker_type": "io_in_loop",
"biomarker_types": [
- "blocking_io_under_lock"
+ "io_in_loop"
],
"boundary_kind": "db",
"confidence": "high",
"evidence": [
{
- "biomarker_type": "blocking_io_under_lock",
- "file_path": "src/app/pool.py",
- "finding_id": "finding_2cca2a2e17c82f868f98",
- "function_name": "reaper",
- "line_end": 132,
- "line_start": 130,
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/api.py",
+ "finding_id": "finding_165492e638f0ce198bad",
+ "function_name": "list_users",
+ "line_end": 32,
+ "line_start": 30,
"path": [
- "src/app/pool.py::reaper",
- "src/app/store.py::flush_all",
- "src/app/store.py::flush"
+ "src/app/api.py::list_users",
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
],
"provenance": "call-site",
- "reason": "distinct_lock_owners: blocking_io_under_lock at src/app/pool.py:130 repeats work per iteration."
+ "reason": "specific_shared_helper: io_in_loop at src/app/api.py:30 repeats work per iteration."
},
{
- "biomarker_type": "blocking_io_under_lock",
- "file_path": "src/app/pool.py",
- "finding_id": "finding_401246625d2b912b7c5c",
- "function_name": "writer",
- "line_end": 132,
- "line_start": 130,
+ "biomarker_type": "io_in_loop",
+ "file_path": "src/app/api.py",
+ "finding_id": "finding_7a74222fa7b3681d4b81",
+ "function_name": "list_orders",
+ "line_end": 33,
+ "line_start": 31,
"path": [
- "src/app/pool.py::writer",
- "src/app/store.py::flush_all",
- "src/app/store.py::flush"
+ "src/app/api.py::list_orders",
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
],
"provenance": "call-site",
- "reason": "distinct_lock_owners: blocking_io_under_lock at src/app/pool.py:130 repeats work per iteration."
+ "reason": "specific_shared_helper: io_in_loop at src/app/api.py:31 repeats work per iteration."
}
],
"evidence_truncated": false,
"execution_context": "production",
"facets": {
- "actionability_confidence": "low",
+ "actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
- "exposure": "unknown",
+ "execution_role": "unknown",
+ "exposure": "entry_reachable",
"leverage": "local",
"loop_magnitude": "unknown"
},
- "fix": null,
+ "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_kind": "shared_helper",
- "intervention_symbol": "src/app/store.py::flush_all",
+ "intervention_symbol": "src/app/repo.py::fetch_page",
"may_lead": false,
"observations_total": 2,
- "opportunity_id": "perf3_d3dace3672249fc9bd03",
+ "opportunity_id": "perf3_8456a319d03ac90c6041",
"performance_model_version": 3,
"prerequisites": [
- "single_lock_owner"
+ "batch_api_contract",
+ "result_equivalence"
],
"provenance": "call-site",
"rank_factors": {
"affected_call_sites": 3,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
- "multiplier_shape": 5,
+ "multiplier_shape": 4,
"provenance": 3
},
"rank_score": 18,
- "reliable_entry_reachability": null,
+ "reliable_entry_reachability": true,
"resource_fingerprints": [],
"shared_path_suffix": [
- "src/app/store.py::flush_all",
- "src/app/store.py::flush"
+ "src/app/repo.py::fetch_page",
+ "src/app/db.py::execute"
],
"siblings": [],
- "terminal_sink": "src/app/store.py::flush",
+ "terminal_sink": "src/app/db.py::execute",
"terminal_sinks": [
- "src/app/store.py::flush"
+ "src/app/db.py::execute"
],
"why_ranked": [
- {
- "factor": "multiplier_shape",
- "points": 5,
- "value": "blocking_io_under_lock"
- },
{
"factor": "boundary_kind",
"points": 4,
"value": "db"
},
+ {
+ "factor": "multiplier_shape",
+ "points": 4,
+ "value": "io_in_loop"
+ },
{
"factor": "affected_call_sites",
"points": 3,
@@ -793,6 +800,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "local",
"loop_magnitude": "unknown"
@@ -816,13 +824,13 @@
"rank_factors": {
"affected_call_sites": 3,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 17,
+ "rank_score": 18,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -885,6 +893,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -907,13 +916,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 5,
"provenance": 3
},
- "rank_score": 17,
+ "rank_score": 18,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -973,6 +982,7 @@
"actionability_confidence": "high",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -994,13 +1004,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -1055,6 +1065,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1078,13 +1089,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -1139,6 +1150,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1161,13 +1173,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -1225,6 +1237,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1248,13 +1261,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -1316,6 +1329,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1339,13 +1353,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -1404,6 +1418,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1426,13 +1441,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -1487,6 +1502,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1509,13 +1525,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -1573,6 +1589,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "not_entry_reachable",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1596,13 +1613,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": false,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -1665,6 +1682,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "not_entry_reachable",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1688,13 +1706,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": false,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -1754,6 +1772,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "bounded"
@@ -1777,13 +1796,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -1841,6 +1860,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "not_entry_reachable",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1864,13 +1884,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": false,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -1930,6 +1950,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -1948,13 +1969,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -2009,6 +2030,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2027,13 +2049,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -2088,6 +2110,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2106,13 +2129,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -2216,6 +2239,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "moderate",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "shared",
"loop_magnitude": "unknown"
@@ -2232,13 +2256,13 @@
"rank_factors": {
"affected_call_sites": 4,
"boundary_kind": 2,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -2301,6 +2325,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2324,13 +2349,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 2,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 15,
+ "rank_score": 16,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -2393,6 +2418,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2416,13 +2442,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 2
},
- "rank_score": 15,
+ "rank_score": 16,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -2485,6 +2511,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2508,13 +2535,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 1,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 14,
+ "rank_score": 15,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -2577,6 +2604,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2593,13 +2621,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 2,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 14,
+ "rank_score": 15,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -2662,6 +2690,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2678,13 +2707,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 2,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 14,
+ "rank_score": 15,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -2747,6 +2776,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2771,13 +2801,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 0
},
- "rank_score": 13,
+ "rank_score": 14,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [
@@ -2837,6 +2867,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2853,13 +2884,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 2,
- "entry_reachability": 0,
"execution_context": 1,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 12,
+ "rank_score": 13,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -2914,6 +2945,7 @@
"actionability_confidence": "low",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -2930,13 +2962,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 2,
- "entry_reachability": 0,
"execution_context": 1,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 12,
+ "rank_score": 13,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -2991,6 +3023,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -3014,13 +3047,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 0,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 3,
"provenance": 3
},
- "rank_score": 11,
+ "rank_score": 12,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
@@ -3075,6 +3108,7 @@
"actionability_confidence": "medium",
"amplification": "per_iteration",
"change_risk": "contained",
+ "execution_role": "unknown",
"exposure": "unknown",
"leverage": "isolated",
"loop_magnitude": "unknown"
@@ -3097,13 +3131,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 0,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 3,
"provenance": 3
},
- "rank_score": 11,
+ "rank_score": 12,
"reliable_entry_reachability": null,
"resource_fingerprints": [],
"shared_path_suffix": [],
diff --git a/tests/fixtures/perf_corpus/golden_plans.json b/tests/fixtures/perf_corpus/golden_plans.json
index d16ce5ca1..35672613c 100644
--- a/tests/fixtures/perf_corpus/golden_plans.json
+++ b/tests/fixtures/perf_corpus/golden_plans.json
@@ -23,13 +23,13 @@
"rank_factors": {
"affected_call_sites": 4,
"boundary_kind": 4,
- "entry_reachability": 3,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 6,
"provenance": 3
},
- "rank_score": 23,
+ "rank_score": 21,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": true
},
@@ -106,6 +106,184 @@
"source_biomarker": "nested_loop_with_io",
"target_symbol": "src/app/jobs.py::drain"
},
+ {
+ "blast_radius": {
+ "call_sites": 2,
+ "file_count": 1,
+ "files": [
+ "src/app/reindex.py"
+ ]
+ },
+ "confidence": "medium",
+ "evidence": {
+ "affected_files_total": 1,
+ "biomarker_type": "nested_loop_with_io",
+ "biomarker_types": [
+ "io_in_loop",
+ "nested_loop_with_io"
+ ],
+ "boundary_kind": "db",
+ "execution_context": "production",
+ "observations_total": 2,
+ "provenance": "call-site",
+ "rank_factors": {
+ "affected_call_sites": 3,
+ "boundary_kind": 4,
+ "execution_context": 3,
+ "execution_role": 1,
+ "loop_magnitude": 0,
+ "multiplier_shape": 6,
+ "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": null
+ },
+ "file_path": "src/app/reindex.py",
+ "impact_delta": 0.0,
+ "line_end": 212,
+ "line_start": 210,
+ "plan": {
+ "affected_locations": [
+ {
+ "call": "_write",
+ "file_path": "src/app/reindex.py",
+ "function_name": "one",
+ "line_end": 212,
+ "line_start": 210
+ },
+ {
+ "call": "_write",
+ "file_path": "src/app/reindex.py",
+ "function_name": "many",
+ "line_end": 217,
+ "line_start": 215
+ }
+ ],
+ "affected_locations_total": 2,
+ "api": null,
+ "evidence_truncated": false,
+ "intervention_symbol": "src/app/reindex.py::_write",
+ "judgment_steps": 3,
+ "mechanical_steps": 0,
+ "opportunity_id": "perf3_a123c4c38fdb1cabaa6a",
+ "paths": [
+ [
+ "src/app/reindex.py::one",
+ "src/app/reindex.py::_write",
+ "src/app/db.py::upsert"
+ ],
+ [
+ "src/app/reindex.py::many",
+ "src/app/reindex.py::_write",
+ "src/app/db.py::upsert"
+ ]
+ ],
+ "paths_total": 2,
+ "safety": "advisory",
+ "steps": [
+ {
+ "action": "Add a form of _write that takes every key at once",
+ "applicability": "judgment",
+ "file_path": "src/app/reindex.py",
+ "line": null,
+ "order": 1,
+ "symbol": "src/app/reindex.py::_write"
+ },
+ {
+ "action": "Collect the keys before the loop and replace the per-key _write call with one batched call",
+ "applicability": "judgment",
+ "file_path": "src/app/reindex.py",
+ "line": 210,
+ "order": 2,
+ "symbol": "one"
+ },
+ {
+ "action": "Collect the keys before the loop and replace the per-key _write call with one batched call",
+ "applicability": "judgment",
+ "file_path": "src/app/reindex.py",
+ "line": 215,
+ "order": 3,
+ "symbol": "many"
+ }
+ ],
+ "strategy": "batch_or_prefetch_io"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "nested_loop_with_io",
+ "target_symbol": "src/app/reindex.py::_write"
+ },
+ {
+ "blast_radius": {
+ "call_sites": 1,
+ "file_count": 1,
+ "files": [
+ "src/app/owners.py"
+ ]
+ },
+ "confidence": "high",
+ "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": "direct",
+ "rank_factors": {
+ "affected_call_sites": 2,
+ "boundary_kind": 4,
+ "execution_context": 3,
+ "execution_role": 1,
+ "loop_magnitude": 2,
+ "multiplier_shape": 4,
+ "provenance": 3
+ },
+ "rank_score": 19,
+ "rationale": "Every call filters on the loop's own key, so .in_(\"repo_id\", keys) covers the same rows, and nothing else in the loop can observe the difference.",
+ "reliable_entry_reachability": null
+ },
+ "file_path": "src/app/owners.py",
+ "impact_delta": 0.0,
+ "line_end": 22,
+ "line_start": 20,
+ "plan": {
+ "affected_locations": [
+ {
+ "file_path": "src/app/owners.py",
+ "function_name": "load_owners",
+ "line_end": 22,
+ "line_start": 20
+ }
+ ],
+ "affected_locations_total": 1,
+ "api": ".in_(\"repo_id\", keys)",
+ "evidence_truncated": false,
+ "intervention_symbol": "src/app/owners.py::load_owners",
+ "judgment_steps": 0,
+ "mechanical_steps": 1,
+ "opportunity_id": "perf3_83d258547498bed60226",
+ "paths": [],
+ "paths_total": 1,
+ "safety": "proven",
+ "steps": [
+ {
+ "action": "Collect the keys before the loop and make one call with .in_(\"repo_id\", keys) in place of the per-key call",
+ "applicability": "mechanical",
+ "file_path": "src/app/owners.py",
+ "line": 20,
+ "order": 1,
+ "symbol": "load_owners"
+ }
+ ],
+ "strategy": "batch_or_prefetch_io"
+ },
+ "refactoring_type": "performance_fix",
+ "source_biomarker": "io_in_loop",
+ "target_symbol": "src/app/owners.py::load_owners"
+ },
{
"blast_radius": {
"call_sites": 3,
@@ -128,13 +306,13 @@
"rank_factors": {
"affected_call_sites": 4,
"boundary_kind": 4,
- "entry_reachability": 3,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 21,
+ "rank_score": 19,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": true
},
@@ -243,13 +421,13 @@
"rank_factors": {
"affected_call_sites": 3,
"boundary_kind": 4,
- "entry_reachability": 3,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 20,
+ "rank_score": 18,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": true
},
@@ -349,13 +527,13 @@
"rank_factors": {
"affected_call_sites": 3,
"boundary_kind": 4,
- "entry_reachability": 3,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 20,
+ "rank_score": 18,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": true
},
@@ -433,184 +611,6 @@
"source_biomarker": "io_in_loop",
"target_symbol": "src/app/repo.py::fetch_page"
},
- {
- "blast_radius": {
- "call_sites": 2,
- "file_count": 1,
- "files": [
- "src/app/reindex.py"
- ]
- },
- "confidence": "medium",
- "evidence": {
- "affected_files_total": 1,
- "biomarker_type": "nested_loop_with_io",
- "biomarker_types": [
- "io_in_loop",
- "nested_loop_with_io"
- ],
- "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,
- "loop_magnitude": 0,
- "multiplier_shape": 6,
- "provenance": 3
- },
- "rank_score": 19,
- "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/reindex.py",
- "impact_delta": 0.0,
- "line_end": 212,
- "line_start": 210,
- "plan": {
- "affected_locations": [
- {
- "call": "_write",
- "file_path": "src/app/reindex.py",
- "function_name": "one",
- "line_end": 212,
- "line_start": 210
- },
- {
- "call": "_write",
- "file_path": "src/app/reindex.py",
- "function_name": "many",
- "line_end": 217,
- "line_start": 215
- }
- ],
- "affected_locations_total": 2,
- "api": null,
- "evidence_truncated": false,
- "intervention_symbol": "src/app/reindex.py::_write",
- "judgment_steps": 3,
- "mechanical_steps": 0,
- "opportunity_id": "perf3_a123c4c38fdb1cabaa6a",
- "paths": [
- [
- "src/app/reindex.py::one",
- "src/app/reindex.py::_write",
- "src/app/db.py::upsert"
- ],
- [
- "src/app/reindex.py::many",
- "src/app/reindex.py::_write",
- "src/app/db.py::upsert"
- ]
- ],
- "paths_total": 2,
- "safety": "advisory",
- "steps": [
- {
- "action": "Add a form of _write that takes every key at once",
- "applicability": "judgment",
- "file_path": "src/app/reindex.py",
- "line": null,
- "order": 1,
- "symbol": "src/app/reindex.py::_write"
- },
- {
- "action": "Collect the keys before the loop and replace the per-key _write call with one batched call",
- "applicability": "judgment",
- "file_path": "src/app/reindex.py",
- "line": 210,
- "order": 2,
- "symbol": "one"
- },
- {
- "action": "Collect the keys before the loop and replace the per-key _write call with one batched call",
- "applicability": "judgment",
- "file_path": "src/app/reindex.py",
- "line": 215,
- "order": 3,
- "symbol": "many"
- }
- ],
- "strategy": "batch_or_prefetch_io"
- },
- "refactoring_type": "performance_fix",
- "source_biomarker": "nested_loop_with_io",
- "target_symbol": "src/app/reindex.py::_write"
- },
- {
- "blast_radius": {
- "call_sites": 1,
- "file_count": 1,
- "files": [
- "src/app/owners.py"
- ]
- },
- "confidence": "high",
- "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": "direct",
- "rank_factors": {
- "affected_call_sites": 2,
- "boundary_kind": 4,
- "entry_reachability": 0,
- "execution_context": 3,
- "loop_magnitude": 2,
- "multiplier_shape": 4,
- "provenance": 3
- },
- "rank_score": 18,
- "rationale": "Every call filters on the loop's own key, so .in_(\"repo_id\", keys) covers the same rows, and nothing else in the loop can observe the difference.",
- "reliable_entry_reachability": null
- },
- "file_path": "src/app/owners.py",
- "impact_delta": 0.0,
- "line_end": 22,
- "line_start": 20,
- "plan": {
- "affected_locations": [
- {
- "file_path": "src/app/owners.py",
- "function_name": "load_owners",
- "line_end": 22,
- "line_start": 20
- }
- ],
- "affected_locations_total": 1,
- "api": ".in_(\"repo_id\", keys)",
- "evidence_truncated": false,
- "intervention_symbol": "src/app/owners.py::load_owners",
- "judgment_steps": 0,
- "mechanical_steps": 1,
- "opportunity_id": "perf3_83d258547498bed60226",
- "paths": [],
- "paths_total": 1,
- "safety": "proven",
- "steps": [
- {
- "action": "Collect the keys before the loop and make one call with .in_(\"repo_id\", keys) in place of the per-key call",
- "applicability": "mechanical",
- "file_path": "src/app/owners.py",
- "line": 20,
- "order": 1,
- "symbol": "load_owners"
- }
- ],
- "strategy": "batch_or_prefetch_io"
- },
- "refactoring_type": "performance_fix",
- "source_biomarker": "io_in_loop",
- "target_symbol": "src/app/owners.py::load_owners"
- },
{
"blast_radius": {
"call_sites": 2,
@@ -633,13 +633,13 @@
"rank_factors": {
"affected_call_sites": 3,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 17,
+ "rank_score": 18,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": null
},
@@ -739,13 +739,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 5,
"provenance": 3
},
- "rank_score": 17,
+ "rank_score": 18,
"rationale": "I/O under the lock is proven, but shared-state ordering must be validated before moving it.",
"reliable_entry_reachability": null
},
@@ -816,13 +816,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"rationale": "Iterations are independent and each await already runs under self._sem.",
"reliable_entry_reachability": null
},
@@ -887,13 +887,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"rationale": "Every call filters on the loop's own key, so .in_(\"repo_id\", keys) is the bulk form; the per-key call limits, orders or shares the loop with other I/O.",
"reliable_entry_reachability": null
},
@@ -958,13 +958,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"rationale": "Iteration independence is proven; the concurrency the fan-out would create is not bounded by anything this group can see.",
"reliable_entry_reachability": null
},
@@ -1029,13 +1029,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "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
},
@@ -1114,13 +1114,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "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
},
@@ -1197,13 +1197,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"rationale": "The relationship is declared lazy and the query that produced the rows does not load it; whether every iteration reaches the access, and whether another layer loads it first, is not proven.",
"reliable_entry_reachability": null
},
@@ -1259,13 +1259,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"rationale": "The relationship is declared lazy and the query that produced the rows does not load it; whether every iteration reaches the access, and whether another layer loads it first, is not proven.",
"reliable_entry_reachability": null
},
@@ -1321,13 +1321,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": false
},
@@ -1406,13 +1406,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": false
},
@@ -1491,13 +1491,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "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
},
@@ -1562,13 +1562,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 16,
+ "rank_score": 17,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": false
},
@@ -1647,13 +1647,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 2,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 3
},
- "rank_score": 15,
+ "rank_score": 16,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": null
},
@@ -1732,13 +1732,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 2
},
- "rank_score": 15,
+ "rank_score": 16,
"rationale": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available.",
"reliable_entry_reachability": null
},
@@ -1817,13 +1817,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 4,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 4,
"provenance": 0
},
- "rank_score": 13,
+ "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
},
@@ -1902,13 +1902,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 0,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 3,
"provenance": 3
},
- "rank_score": 11,
+ "rank_score": 12,
"rationale": "The collection is proven list-backed; element hashability and ordering/identity use still require validation.",
"reliable_entry_reachability": null
},
@@ -1973,13 +1973,13 @@
"rank_factors": {
"affected_call_sites": 2,
"boundary_kind": 0,
- "entry_reachability": 0,
"execution_context": 3,
+ "execution_role": 1,
"loop_magnitude": 0,
"multiplier_shape": 3,
"provenance": 3
},
- "rank_score": 11,
+ "rank_score": 12,
"rationale": "Repeated string accumulation is proven; intermediate accumulator observations still require validation.",
"reliable_entry_reachability": null
},
diff --git a/tests/unit/health/test_execution_roles.py b/tests/unit/health/test_execution_roles.py
new file mode 100644
index 000000000..8c038d20e
--- /dev/null
+++ b/tests/unit/health/test_execution_roles.py
@@ -0,0 +1,336 @@
+"""Execution roles: seeds per framework, hot walks, cold settling, keyed on the loop owner."""
+
+from __future__ import annotations
+
+import networkx as nx
+import pytest
+
+from repowise.core.analysis.execution_graph import ExecutionGraphIndex
+from repowise.core.analysis.execution_roles import (
+ EXECUTION_ROLES,
+ ExecutionRoles,
+ hottest_role,
+ seed_roles,
+)
+from repowise.core.analysis.health import HealthAnalyzer
+from repowise.core.analysis.health.models import HealthFindingData
+from repowise.core.analysis.health.perf.opportunity_rank import ROLE_POINTS
+from repowise.core.analysis.health.queue.eligibility import (
+ DEFAULT_QUEUE_PROOFS,
+ perf_queue_verdict,
+ queue_proof,
+)
+
+
+def _graph(*symbols: tuple[str, str, list[str]], start: int = 10) -> nx.DiGraph:
+ """Symbols as ``(id, language, decorators)``, each defined by its file."""
+ graph = nx.DiGraph()
+ for offset, (node, language, decorators) in enumerate(symbols):
+ path, _, name = node.partition("::")
+ graph.add_node(path, node_type="file")
+ graph.add_node(
+ node,
+ node_type="symbol",
+ kind="function",
+ name=name.rsplit("::", 1)[-1],
+ file_path=path,
+ language=language,
+ decorators=decorators,
+ start_line=start + offset * 20,
+ end_line=start + offset * 20 + 15,
+ )
+ graph.add_edge(path, node, edge_type="defines")
+ return graph
+
+
+def _seed_of(graph: nx.DiGraph, node: str) -> str | None:
+ by_role = seed_roles(graph).by_role
+ return next((role for role, nodes in by_role.items() if node in nodes), None)
+
+
+def _imports(graph: nx.DiGraph, path: str, module: str) -> None:
+ graph.add_edge(path, f"external:{module}", edge_type="imports")
+
+
+ ("node", "language", "decorators", "role"),
+ [
+ ("api/users.py::list_users", "python", ['@router.get("/users")'], "request"),
+ ("api/views.py::index", "python", ['@bp.route("/", methods=["GET"])'], "request"),
+ ("api/ws.py::stream", "python", ['@app.websocket("/ws")'], "request"),
+ ("mcp/tools.py::get_health", "python", ["@mcp.tool()"], "request"),
+ ("rpc/server.py::list_sessions", "python", ['@method("session.list")'], "request"),
+ ("api/app.py::boot", "python", ['@app.on_event("startup")'], "startup"),
+ ("worker/tasks.py::reindex", "python", ["@shared_task"], "scheduled_job"),
+ ("worker/tasks.py::rebuild", "python", ["@celery_app.task(bind=True)"], "scheduled_job"),
+ ("cli/main.py::init", "python", ["@click.command()", '@click.option("--x")'], "cli"),
+ ("cli/main.py::run", "python", ["@app.command()"], "cli"),
+ ("src/api.ts::list", "typescript", ['@Get(":id")'], "request"),
+ ("app/api/users/route.ts::GET", "typescript", [], "request"),
+ ("app/main.py::lifespan", "python", [], "startup"),
+ ("pkg/util.py::helper", "python", ["@functools.cache"], None),
+ # Other languages are never seeded: they read ``unknown``.
+ ("src/Api.java::list", "java", ['@Get("/x")'], None),
+ ],
+)
+def test_declaration_seeds(node, language, decorators, role) -> None:
+ assert _seed_of(_graph((node, language, decorators)), node) == role
+
+
+ ("node", "language", "role"),
+ [
+ # A name is kept only where the file corroborates it.
+ ("extensions/chat/src/inbound.ts::handleClickClackInbound", "typescript", "event_consumer"),
+ ("gateway/sms.py::_handle_webhook", "python", "event_consumer"),
+ ("gateway/run.py::_async_delegation_watcher", "python", "scheduled_job"),
+ ("server/job_executor.py::execute_job", "python", "scheduled_job"),
+ ("tui_gateway/server.py::_notification_poller_loop", "python", "scheduled_job"),
+ ("src/routes/permissions.ts::registerBrowserPermissionRoutes", "typescript", "request"),
+ ("lib/util.py::handle_webhook", "python", None),
+ ("lib/util.py::poll_once", "python", None),
+ ("gateway/hooks.py::handle_webhook_registration", "python", None),
+ # Whole words: none of these is a poller.
+ ("worker/env.py::pollutant_level", "python", None),
+ ("worker/env.py::polling_config", "python", None),
+ ("worker/jobs.py::process_jobless", "python", None),
+ ],
+)
+def test_name_seeds_need_a_corroborating_place(node, language, role) -> None:
+ assert _seed_of(_graph((node, language, [])), node) == role
+
+
+def test_a_registration_corroborates_a_name_anywhere() -> None:
+ graph = _graph(("lib/util.py::poll_once", "python", []), ("lib/boot.py::start", "python", []))
+ graph.add_edge("lib/boot.py::start", "lib/util.py::poll_once", edge_type="references")
+ assert _seed_of(graph, "lib/util.py::poll_once") == "scheduled_job"
+
+
+def test_a_scheduler_builder_owns_its_registered_closures() -> None:
+ graph = _graph(("server/scheduler.py::setup_scheduler", "python", []), ("server/util.py::setup_scheduler", "python", []))
+ _imports(graph, "server/scheduler.py", "apscheduler.schedulers.asyncio")
+ assert _seed_of(graph, "server/scheduler.py::setup_scheduler") == "scheduled_job"
+ assert _seed_of(graph, "server/util.py::setup_scheduler") is None
+
+
+def test_django_views_named_by_a_urlconf_are_request_seeds() -> None:
+ graph = _graph(("shop/views.py::detail", "python", []))
+ graph.add_node("shop/urls.py", node_type="file")
+ graph.add_edge("shop/urls.py", "shop/views.py", edge_type="framework")
+ assert _seed_of(graph, "shop/views.py::detail") == "request"
+
+
+def test_express_bound_handlers_seed_only_where_the_file_uses_express() -> None:
+ graph = _graph(
+ ("src/routes.ts::__module__", "typescript", []),
+ ("src/routes.ts::getUser", "typescript", []),
+ ("src/nav.ts::__module__", "typescript", []),
+ ("src/nav.ts::guard", "typescript", []),
+ )
+ graph.add_edge("src/routes.ts::__module__", "src/routes.ts::getUser", edge_type="framework_binds")
+ graph.add_edge("src/nav.ts::__module__", "src/nav.ts::guard", edge_type="framework_binds")
+ _imports(graph, "src/routes.ts", "express")
+ assert _seed_of(graph, "src/routes.ts::getUser") == "request"
+ assert _seed_of(graph, "src/nav.ts::guard") is None
+
+
+def test_lambda_config_binds_seed_event_consumers() -> None:
+ graph = _graph(("src/handler.py::main", "python", []))
+ graph.add_node("serverless.yml::__module__", node_type="symbol", kind="module")
+ graph.add_edge("serverless.yml::__module__", "src/handler.py::main", edge_type="framework_binds")
+ assert _seed_of(graph, "src/handler.py::main") == "event_consumer"
+
+
+def test_a_scheduler_import_seeds_only_registered_functions() -> None:
+ graph = _graph(
+ ("server/scheduler.py::setup_scheduler", "python", []),
+ ("server/scheduler.py::sync_repos", "python", []),
+ ("tool/cli.py::main", "python", []),
+ ("tool/cli.py::cmd_sync", "python", []),
+ )
+ _imports(graph, "server/scheduler.py", "apscheduler.schedulers.asyncio")
+ _imports(graph, "tool/cli.py", "argparse")
+ graph.add_edge(
+ "server/scheduler.py::setup_scheduler", "server/scheduler.py::sync_repos", edge_type="references"
+ )
+ graph.add_edge("tool/cli.py::main", "tool/cli.py::cmd_sync", edge_type="references")
+ seeds = seed_roles(graph)
+ # ``setup_scheduler`` itself is the scheduler builder (see the test above).
+ assert seeds.by_role["scheduled_job"] - {"server/scheduler.py::setup_scheduler"} == {
+ "server/scheduler.py::sync_repos"
+ }
+ assert {"tool/cli.py::main", "tool/cli.py::cmd_sync"} <= seeds.by_role["cli"]
+
+
+def test_vscode_activate_is_startup_and_registered_commands_are_cli() -> None:
+ graph = _graph(("src/extension.ts::activate", "typescript", []), ("src/extension.ts::refresh", "typescript", []))
+ _imports(graph, "src/extension.ts", "vscode")
+ graph.add_edge("src/extension.ts::activate", "src/extension.ts::refresh", edge_type="references")
+ assert _seed_of(graph, "src/extension.ts::activate") == "startup"
+ assert _seed_of(graph, "src/extension.ts::refresh") == "cli"
+
+
+def test_aiohttp_handlers_seed_requests() -> None:
+ graph = _graph(("gateway/api.py::_handle_get_job", "python", []), ("gateway/api.py::helper", "python", []))
+ _imports(graph, "gateway/api.py", "aiohttp")
+ by_role = seed_roles(graph).by_role
+ assert "gateway/api.py::_handle_get_job" in by_role["request"]
+ assert "gateway/api.py::helper" not in by_role["request"]
+
+
+def _call(graph: nx.DiGraph, source: str, target: str) -> None:
+ graph.add_edge(source, target, edge_type="calls", call_lines=[1])
+
+
+def _roles(graph: nx.DiGraph) -> ExecutionRoles:
+ return ExecutionRoles.build(graph, ExecutionGraphIndex(graph))
+
+
+def _reach_graph() -> nx.DiGraph:
+ graph = _graph(
+ ("api/routes.py::create", "python", ['@router.post("/items")']),
+ ("cli/main.py::sync", "python", ["@click.command()"]),
+ ("app/main.py::lifespan", "python", []),
+ ("svc/items.py::save_all", "python", []),
+ ("svc/items.py::warm_cache", "python", []),
+ ("svc/items.py::orphan", "python", []),
+ ("tests/test_items.py::test_save", "python", []),
+ )
+ _call(graph, "api/routes.py::create", "svc/items.py::save_all")
+ _call(graph, "cli/main.py::sync", "svc/items.py::save_all")
+ _call(graph, "app/main.py::lifespan", "svc/items.py::warm_cache")
+ _call(graph, "tests/test_items.py::test_save", "svc/items.py::orphan")
+ return graph
+
+
+def test_the_hottest_reaching_role_wins_and_paths_decide_test_tooling_and_ui() -> None:
+ roles = _roles(_reach_graph())
+ assert roles.role_of("svc/items.py::save_all", "svc/items.py") == "request"
+ # Only startup calls it, so it is startup's work.
+ assert roles.role_of("svc/items.py::warm_cache", "svc/items.py") == "startup"
+ # Reached only by a test: no evidence of how it runs in production.
+ assert roles.role_of("svc/items.py::orphan", "svc/items.py") == "unknown"
+ assert roles.role_of("tests/test_items.py::test_save", "tests/test_items.py") == "test"
+ assert roles.role_of("scripts/release.py::main", "scripts/release.py") == "tooling"
+ assert roles.role_of("web/src/Panel.tsx::Panel", "web/src/Panel.tsx") == "ui"
+ assert roles.role_of("apps/desktop/src/store/session.ts::set", "apps/desktop/src/store/session.ts") == "ui"
+ assert roles.role_of("app/dash/page.tsx::Page", "app/dash/page.tsx") == "unknown"
+
+
+def test_a_cold_caller_never_makes_a_shared_helper_cold() -> None:
+ """A helper an unseeded view and a CLI both call has no evidence: ``unknown``."""
+ graph = _graph(
+ ("cli/main.py::sync", "python", ["@click.command()"]),
+ ("web/views.py::page", "python", []),
+ ("svc/items.py::shared", "python", []),
+ ("svc/items.py::cli_only", "python", []),
+ ("svc/items.py::deeper", "python", []),
+ )
+ _call(graph, "cli/main.py::sync", "svc/items.py::shared")
+ _call(graph, "web/views.py::page", "svc/items.py::shared")
+ _call(graph, "cli/main.py::sync", "svc/items.py::cli_only")
+ _call(graph, "svc/items.py::cli_only", "svc/items.py::deeper")
+ roles = _roles(graph)
+ assert roles.role_of("svc/items.py::shared", "svc/items.py") == "unknown"
+ assert roles.role_of("svc/items.py::cli_only", "svc/items.py") == "cli"
+ assert roles.role_of("svc/items.py::deeper", "svc/items.py") == "cli"
+
+
+def test_a_hot_walk_runs_through_a_name_seed_and_stops_at_a_declared_one() -> None:
+ """Calling a function runs it: a request that calls ``execute_job`` directly
+ does that work per request. A declared job is where the job's own work begins."""
+ graph = _graph(
+ ("api/repos.py::sync", "python", ['@router.post("/sync")']),
+ ("server/jobs.py::execute_job", "python", []),
+ ("core/pipeline.py::persist_all", "python", []),
+ ("worker/tasks.py::reindex", "python", ["@shared_task"]),
+ ("core/pipeline.py::rebuild", "python", []),
+ )
+ _call(graph, "api/repos.py::sync", "server/jobs.py::execute_job")
+ _call(graph, "server/jobs.py::execute_job", "core/pipeline.py::persist_all")
+ _call(graph, "api/repos.py::sync", "worker/tasks.py::reindex")
+ _call(graph, "worker/tasks.py::reindex", "core/pipeline.py::rebuild")
+ roles = _roles(graph)
+ assert roles.role_of("core/pipeline.py::persist_all", "core/pipeline.py") == "request"
+ assert roles.role_of("worker/tasks.py::reindex", "worker/tasks.py") == "scheduled_job"
+ assert roles.role_of("core/pipeline.py::rebuild", "core/pipeline.py") == "scheduled_job"
+
+
+def _finding(file_path: str, line: int, details: dict | None = None) -> HealthFindingData:
+ return HealthFindingData(
+ biomarker_type="io_in_loop",
+ severity="low",
+ file_path=file_path,
+ function_name=None,
+ line_start=line,
+ line_end=line,
+ details=details or {},
+ health_impact=0.0,
+ dimension="performance",
+ )
+
+
+def test_the_role_is_keyed_on_the_loop_owner_even_without_a_path() -> None:
+ graph = _reach_graph()
+ analyzer = HealthAnalyzer(graph)
+ # save_all spans 70-85 and warm_cache 90-105 (see ``_graph``).
+ intra = _finding("svc/items.py", 95)
+ cross = _finding("svc/items.py", 72, {"path": ["svc/items.py::save_all", "db.py::write"]})
+ other = _finding("svc/items.py", 95)
+ other.dimension = "defect"
+ roles = analyzer._mark_perf_entry_reachability([intra, cross, other])
+ assert intra.details["execution_role"] == "startup"
+ assert intra.details["role_owner"] == "svc/items.py::warm_cache"
+ assert cross.details["execution_role"] == "request"
+ assert "execution_role" not in other.details
+ assert roles is not None and roles.role_of("svc/items.py::save_all", "svc/items.py") == "request"
+
+
+def test_group_role_prefers_hot_and_never_reads_unknown_as_cold() -> None:
+ assert hottest_role(["cli", "request"]) == "request"
+ assert hottest_role(["cli", None]) == "unknown"
+ assert hottest_role(["startup", "test"]) == "startup"
+ assert hottest_role([]) == "unknown"
+ assert set(ROLE_POINTS) == set(EXECUTION_ROLES)
+ assert ROLE_POINTS["unknown"] > ROLE_POINTS["cli"] == ROLE_POINTS["ui"] == 0
+
+
+def _opportunity(role: str, magnitude: str = "grows_with_data") -> dict:
+ return {
+ "execution_context": "production",
+ "actionability_state": "advisory",
+ "biomarker_type": "io_in_loop",
+ "facets": {"loop_magnitude": magnitude, "execution_role": role},
+ }
+
+
+ ("role", "magnitude", "reason", "proof"),
+ [
+ ("request", "grows_with_data", None, "proven"),
+ ("event_consumer", "grows_with_data", None, "proven"),
+ ("unknown", "grows_with_data", None, "proven"),
+ ("scheduled_job", "grows_with_data", None, "proven"),
+ ("scheduled_job", "bounded", "background_unproven", "background_unproven"),
+ # Unmeasured cost is checked first, so the count stays where it was.
+ ("scheduled_job", "unknown", "unmeasured_cost", "unproven"),
+ ("startup", "grows_with_data", "cold_role", "proven"),
+ ("cli", "grows_with_data", "cold_role", "proven"),
+ ("ui", "grows_with_data", "cold_role", "proven"),
+ ("cli", "unknown", "unmeasured_cost", "unproven"),
+ ],
+)
+def test_default_queue_eligibility_by_role(role, magnitude, reason, proof) -> None:
+ item = _opportunity(role, magnitude)
+ assert perf_queue_verdict(item).reason == reason
+ assert queue_proof(item) == proof
+
+
[email protected]("role", EXECUTION_ROLES)
[email protected]("magnitude", ["grows_with_data", "bounded", "unknown"])
+def test_the_stored_proof_never_disagrees_with_the_verdict(role, magnitude) -> None:
+ """The SQL queue filters the stored proof; the counts read the verdict."""
+ item = _opportunity(role, magnitude)
+ reason = perf_queue_verdict(item).reason
+ in_proof = queue_proof(item) in DEFAULT_QUEUE_PROOFS
+ assert in_proof == (reason not in ("unmeasured_cost", "background_unproven"))
diff --git a/tests/unit/health/test_perf_identity_contract.py b/tests/unit/health/test_perf_identity_contract.py
index e5ddecfd4..439e8ce1f 100644
--- a/tests/unit/health/test_perf_identity_contract.py
+++ b/tests/unit/health/test_perf_identity_contract.py
@@ -135,6 +135,8 @@ def test_display_only_fields_are_outside_the_opportunity_kernel(field, value) ->
("dataflow_verified", True),
("resource_invariant", True),
("reliable_entry_reachability", True),
+ ("execution_role", "request"),
+ ("role_owner", "src/app.py::run"),
("resolution_basis", "name-fallback"),
],
)
@@ -373,6 +375,9 @@ def test_the_public_finding_id_ignores_prose_and_derived_details() -> None:
assert finding_public_id(base) == finding_public_id(
_row(details={**base["details"], "reliable_entry_reachability": True})
)
+ assert finding_public_id(base) == finding_public_id(
+ _row(details={**base["details"], "execution_role": "cli"})
+ )
# Structural coordinates are in the kernel, so a real move is a new id.
assert finding_public_id(base) != finding_public_id(_row(line_start=999))
diff --git a/tests/unit/health/test_perf_serving.py b/tests/unit/health/test_perf_serving.py
index adf32a0f8..49844ae60 100644
--- a/tests/unit/health/test_perf_serving.py
+++ b/tests/unit/health/test_perf_serving.py
@@ -99,9 +99,9 @@ def test_summary_payload_names_absence_and_staleness() -> None:
def test_rescope_summary_recounts_one_context() -> None:
groups = [
- ("production", None, "high", "advisory", "available", "proven", 2),
- ("production", "db", "low", "plan_ready", "no_safe_plan", "unproven", 1),
- ("test", "db", "low", "advisory", "available", "proven", 5),
+ ("production", None, "high", "advisory", "available", "proven", "request", 2),
+ ("production", "db", "low", "plan_ready", "no_safe_plan", "unproven", "cli", 1),
+ ("test", "db", "low", "advisory", "available", "proven", "test", 5),
]
scoped = rescope_summary({"total": 8, "x": 1}, groups, frozenset({"production"}))
assert scoped == {
@@ -122,27 +122,27 @@ def test_rescope_summary_recounts_one_context() -> None:
_SEEDS: list[dict[str, Any]] = [
{"execution_context": "production", "boundary_kind": "db", "evidence_confidence": "high",
"actionability_state": "plan_ready", "plan_state": "available", "file_path": "a.py",
- "affected_call_sites_total": 4, "observations_total": 9, "cost_proof": "proven"},
+ "affected_call_sites_total": 4, "observations_total": 9, "cost_proof": "proven", "execution_role": "request"},
{"execution_context": "production", "boundary_kind": None, "evidence_confidence": "medium",
"actionability_state": "advisory", "plan_state": "no_safe_plan", "file_path": "b.py",
- "affected_call_sites_total": 4, "observations_total": 2, "cost_proof": "unproven"},
+ "affected_call_sites_total": 4, "observations_total": 2, "cost_proof": "unproven", "execution_role": "cli"},
{"execution_context": "test", "boundary_kind": "network", "evidence_confidence": "low",
"actionability_state": "advisory", "plan_state": "not_persisted", "file_path": "a.py",
- "affected_call_sites_total": 7, "observations_total": 2, "cost_proof": "proven"},
+ "affected_call_sites_total": 7, "observations_total": 2, "cost_proof": "proven", "execution_role": "test"},
{"execution_context": "tooling", "boundary_kind": None, "evidence_confidence": "high",
"actionability_state": "expected", "plan_state": "no_safe_plan", "file_path": "c.py",
- "affected_call_sites_total": 1, "observations_total": 9, "cost_proof": "unproven"},
+ "affected_call_sites_total": 1, "observations_total": 9, "cost_proof": "unproven", "execution_role": "tooling"},
{"execution_context": "production", "boundary_kind": "db", "evidence_confidence": "high",
"actionability_state": "investigate", "plan_state": "no_safe_plan", "file_path": "c.py",
- "affected_call_sites_total": 0, "observations_total": 5, "cost_proof": "proven"},
+ "affected_call_sites_total": 0, "observations_total": 5, "cost_proof": "proven", "execution_role": "scheduled_job"},
{"execution_context": "unknown", "boundary_kind": "filesystem", "evidence_confidence": "medium",
"actionability_state": "plan_ready", "plan_state": "available", "file_path": "b.py",
- "affected_call_sites_total": 7, "observations_total": 1, "cost_proof": "proven"},
+ "affected_call_sites_total": 7, "observations_total": 1, "cost_proof": "proven", "execution_role": "unknown"},
# Resolved: in no queue and no facet.
{"execution_context": "production", "boundary_kind": "db", "evidence_confidence": "high",
"actionability_state": "plan_ready", "plan_state": "available", "file_path": "a.py",
"affected_call_sites_total": 99, "observations_total": 99, "status": "resolved",
- "cost_proof": "proven"},
+ "cost_proof": "proven", "execution_role": "request"},
]
_QUERIES: list[dict[str, Any]] = [
@@ -158,6 +158,9 @@ _QUERIES: list[dict[str, Any]] = [
{"boundary": "network"},
{"proof": "unproven"},
{"context": "all", "proof": "unproven", "actionability": "expected"},
+ {"context": "all", "role": "all"},
+ {"role": "cli"},
+ {"context": "all", "role": "scheduled_job", "actionability": "investigate"},
]
@@ -231,6 +234,7 @@ async def test_keep_and_sort_agree_with_the_store(store, args, sort) -> None:
confidence=query.confidence,
actionabilities=query.actionabilities,
proofs=query.proofs,
+ roles=query.roles,
file_paths=query.file_paths,
sort=query.sort,
limit=query.limit,
@@ -245,7 +249,7 @@ async def test_keep_and_sort_agree_with_the_store(store, args, sort) -> None:
def _reference_facets(groups: list[tuple], query: PerformanceQuery) -> dict[str, Any]:
"""The cross-filtered fold as the service wrote it before the rules were data."""
dimensions = {"context": 0, "boundary": 1, "confidence": 2, "actionability": 3,
- "plan_state": 4, "proof": 5}
+ "plan_state": 4, "proof": 5, "role": 6}
selected = {
"context": query.contexts,
"boundary": None if query.boundary is None else frozenset({query.boundary}),
@@ -255,6 +259,7 @@ def _reference_facets(groups: list[tuple], query: PerformanceQuery) -> dict[str,
),
"plan_state": None,
"proof": None if query.proof is None else frozenset({query.proof}),
+ "role": None if query.role in (None, "all") else frozenset({query.role}),
}
facets = {}
for name, index in dimensions.items():
@@ -266,7 +271,7 @@ def _reference_facets(groups: list[tuple], query: PerformanceQuery) -> dict[str,
for other, values in selected.items()
):
continue
- counts[row[index] or "none"] = counts.get(row[index] or "none", 0) + row[6]
+ counts[row[index] or "none"] = counts.get(row[index] or "none", 0) + row[7]
facets[name] = [
{"value": v, "total": t}
for v, t in sorted(counts.items(), key=lambda item: (-item[1], item[0]))
diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.py
index 0e7c72fd2..64df7b83c 100644
--- a/tests/unit/server/test_performance_opportunities.py
+++ b/tests/unit/server/test_performance_opportunities.py
@@ -8,13 +8,15 @@ never reaches.
from __future__ import annotations
+import json
+
from httpx import AsyncClient
from sqlalchemy import select
from repowise.core.analysis.health.models import HealthFindingData, Severity
from repowise.core.analysis.health.perf.opportunities import link_performance_findings
from repowise.core.persistence import crud
-from repowise.core.persistence.models import PerformanceOpportunity
+from repowise.core.persistence.models import HealthFinding, PerformanceOpportunity
from tests.unit.server.conftest import create_test_repo
@@ -343,6 +345,8 @@ async def test_the_default_queue_reports_what_it_leaves_out(app, client: AsyncCl
"expected": 1,
"no_strategy": 1,
"unmeasured_cost": 1,
+ "cold_role": 0,
+ "background_unproven": 0,
},
}
proof = {entry["value"]: entry["total"] for entry in default["facets"]["proof"]}
@@ -405,6 +409,7 @@ async def test_detail_carries_the_facets_and_evidence_for_one_cause(
"leverage",
"change_risk",
"loop_magnitude",
+ "execution_role",
}
assert body["evidence_total"] == 2
assert body["evidence_emitted"] == 1
@@ -533,3 +538,106 @@ async def test_the_bulk_call_a_plan_names_is_served(app, client: AsyncClient) ->
).json()
assert body["actionability_state"] == "plan_ready"
assert body["fix"]["api"] == '.in_("repo_id", keys)'
+
+
+async def test_cold_and_unproven_background_roles_sit_one_filter_away(
+ app, client: AsyncClient
+) -> None:
+ """Startup and CLI loops leave the default queue; a scheduled job needs growth."""
+ served = _finding("src/c.py", 40, ["src/c.py::run", "src/db.py::fetch"])
+ served.details["execution_role"] = "request"
+ cli = _finding("src/e.py", 60, ["src/e.py::run", "src/db.py::fetch"])
+ cli.details["execution_role"] = "cli"
+ job = _finding(
+ "src/f.py", 70, ["src/f.py::run", "src/db.py::fetch"], magnitude="bounded"
+ )
+ job.details["execution_role"] = "scheduled_job"
+ repo_id, _ = await _seed(app, client, [served, cli, job])
+
+ default = await _page(client, repo_id)
+ assert [item["intervention_symbol"] for item in default["items"]] == ["src/c.py::run"]
+ excluded = default["summary"]["default_queue"]["excluded"]
+ assert (excluded["cold_role"], excluded["background_unproven"]) == (1, 1)
+ roles = {entry["value"]: entry["total"] for entry in default["facets"]["role"]}
+ assert roles == {"request": 1, "cli": 1, "scheduled_job": 1}
+ assert default["items"][0]["facets"]["execution_role"] == "request"
+
+ asked = await _page(client, repo_id, role="cli")
+ assert [item["intervention_symbol"] for item in asked["items"]] == ["src/e.py::run"]
+ unproven = await _page(client, repo_id, proof="background_unproven")
+ assert [item["intervention_symbol"] for item in unproven["items"]] == ["src/f.py::run"]
+ everything = await _page(client, repo_id, role="all")
+ assert everything["total"] == 2
+
+
+async def test_a_stored_finding_takes_the_role_this_run_found(app, client: AsyncClient) -> None:
+ """A seed that moves in another file restamps a finding this run did not rescan."""
+ from repowise.core.analysis.execution_roles import ExecutionRoles
+
+ finding = _finding("src/c.py", 40, ["src/c.py::run", "src/db.py::fetch"])
+ finding.details.update(execution_role="cli", role_owner="src/c.py::run")
+ repo_id, _ = await _seed(app, client, [finding])
+ assert (await _page(client, repo_id))["total"] == 0
+
+ async with app.state.session_factory() as session:
+ await crud.finalize_performance_opportunities(
+ session,
+ repo_id,
+ analyzed_commit="a" * 40,
+ execution_roles=ExecutionRoles({"src/c.py::run": "request"}),
+ )
+ await session.commit()
+ page = await _page(client, repo_id)
+ assert [item["facets"]["execution_role"] for item in page["items"]] == ["request"]
+ async with app.state.session_factory() as session:
+ stored = (
+ await session.execute(
+ select(HealthFinding.details_json).where(
+ HealthFinding.repository_id == repo_id
+ )
+ )
+ ).scalar_one()
+ assert '"execution_role":"request"' in stored
+
+
+async def test_a_finding_stored_before_role_owner_is_keyed_on_its_loop_owner(
+ app, client: AsyncClient
+) -> None:
+ """A legacy row gets its owner found as the analysis finds it, then keeps it."""
+ import networkx as nx
+
+ from repowise.core.analysis.execution_graph import ExecutionGraphIndex
+ from repowise.core.analysis.execution_roles import ExecutionRoles
+
+ crossing = _finding("src/c.py", 40, ["src/c.py::run", "src/db.py::fetch"])
+ inside = _finding("src/e.py", 12, [])
+ inside.details.pop("path")
+ inside.details["cross_function"] = False
+ repo_id, _ = await _seed(app, client, [crossing, inside])
+
+ graph = nx.DiGraph()
+ graph.add_node(
+ "src/e.py::load", node_type="symbol", name="load", file_path="src/e.py",
+ start_line=10, end_line=20,
+ )
+ roles = ExecutionRoles(
+ {"src/c.py::run": "request", "src/e.py::load": "event_consumer"},
+ ExecutionGraphIndex(graph),
+ )
+ async with app.state.session_factory() as session:
+ await crud.finalize_performance_opportunities(
+ session, repo_id, analyzed_commit="a" * 40, execution_roles=roles
+ )
+ await session.commit()
+ stored = (
+ await session.execute(
+ select(HealthFinding.file_path, HealthFinding.details_json).where(
+ HealthFinding.repository_id == repo_id
+ )
+ )
+ ).all()
+ details = {path: json.loads(raw) for path, raw in stored}
+ assert details["src/c.py"]["role_owner"] == "src/c.py::run"
+ assert details["src/c.py"]["execution_role"] == "request"
+ assert details["src/e.py"]["role_owner"] == "src/e.py::load"
+ assert details["src/e.py"]["execution_role"] == "event_consumer"
diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.py
index f943859dc..e95a22e0d 100644
--- a/tests/unit/server/test_wire_vocabulary_parity.py
+++ b/tests/unit/server/test_wire_vocabulary_parity.py
@@ -141,9 +141,18 @@ def test_every_surface_counts_in_the_one_reason_vocabulary() -> None:
def test_performance_cost_proofs_match_python() -> None:
- from repowise.core.analysis.health.worth import COST_PROOFS
+ from repowise.core.analysis.health.queue.eligibility import QUEUE_PROOFS
- assert _union_members("PerformanceCostProof", "health.ts") == set(COST_PROOFS)
+ assert _union_members("PerformanceCostProof", "health.ts") == set(QUEUE_PROOFS)
+
+
+def test_performance_execution_roles_match_python() -> None:
+ from repowise.core.analysis.execution_roles import EXECUTION_ROLES
+
+ text = (_TYPES_SRC / "health.ts").read_text(encoding="utf-8")
+ match = re.search(r"export const PERFORMANCE_EXECUTION_ROLES = \[(.*?)\] as const;", text, re.S)
+ assert match, "PERFORMANCE_EXECUTION_ROLES is not declared in health.ts"
+ assert re.findall(r'"([a-z_]+)"', match.group(1)) == list(EXECUTION_ROLES)
def test_agent_prompt_flavors_match_python() -> None: