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(perf): flag a lazily loaded relationship read once per row in a loop (#2528)

Raghav Chamadiya0a1e44c064ed
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/lazy_load_in_loop.py b/packages/core/src/repowise/core/analysis/health/biomarkers/lazy_load_in_loop.py
new file mode 100644
index 000000000..ce22715f3
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/lazy_load_in_loop.py
@@ -0,0 +1,48 @@
+"""Lazily-declared relationship read on each iteration of a loop.
+
+Lifts ``perf.lazy_load`` hits. ``PerfHit.path`` carries ``(subject, fix)``: the
+relationship read (``Incident.owner``) and the eager load that replaces it
+(``selectinload(Incident.owner)``, ``select_related("owner")``).
+"""
+
+from __future__ import annotations
+
+from ..models import Severity
+from .base import BiomarkerResult, FileContext
+
+_KIND = "lazy_load_in_loop"
+
+
+class LazyLoadInLoopDetector:
+ name = _KIND
+ category = "performance"
+
+ def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
+ out: list[BiomarkerResult] = []
+ for hit in ctx.perf_hits:
+ if hit.kind != _KIND:
+ continue
+ subject, fix = hit.path
+ out.append(
+ BiomarkerResult(
+ biomarker_type=self.name,
+ severity=Severity.LOW,
+ function_name=hit.function,
+ line_start=hit.line,
+ line_end=hit.line,
+ details={
+ "boundary_kind": hit.detail,
+ "relationship": subject,
+ "eager_load": fix,
+ **hit.loop_facts(),
+ },
+ reason=(
+ f"{subject} is loaded lazily on each iteration of this loop, one "
+ f"query per row; load it with the rows: {fix}"
+ ),
+ )
+ )
+ return out
+
+
+BIOMARKER = LazyLoadInLoopDetector()
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
index 3ed2e8fbc..3a7d917f3 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/registry.py
@@ -41,6 +41,7 @@ from .json_parse_in_loop import JsonParseInLoopDetector
from .knowledge_loss import KnowledgeLossDetector
from .large_assertion_block import LargeAssertionBlockDetector
from .large_method import LargeMethodDetector
+from .lazy_load_in_loop import LazyLoadInLoopDetector
from .list_insert_zero_in_loop import ListInsertZeroInLoopDetector
from .lock_in_loop import LockInLoopDetector
from .low_cohesion import LowCohesionDetector
@@ -109,6 +110,7 @@ _DETECTOR_FACTORIES: list[type[Biomarker]] = [
SerialAwaitInLoopDetector, # type: ignore[list-item]
MembershipTestAgainstListInLoopDetector, # type: ignore[list-item]
UnboundedReadReducedInMemoryDetector, # type: ignore[list-item]
+ LazyLoadInLoopDetector, # type: ignore[list-item]
# Phase 7b — centrality-gated moat markers.
NestedLoopWithIoDetector, # type: ignore[list-item]
NestedLoopQuadraticDetector, # type: ignore[list-item]
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index daa51d080..3dd12d96b 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -58,6 +58,7 @@ from .perf import (
collect_crossfn_io_in_loop,
link_performance_findings,
)
+from .perf.lazy_load import collect_lazy_loads
from .perf.unbounded_reduction import collect_unbounded_reductions
from .refactoring import (
PerformancePlanPolicy,
@@ -111,6 +112,11 @@ log = structlog.get_logger(__name__)
# and a declining call's arguments are not scanned, so an assertion passed as an
# argument still does not stand in for the header's oracle.
#
+# v27: a new marker, ``lazy_load_in_loop`` (a lazy relationship read on each
+# iteration of a loop over its rows); and ``unbounded_read_reduced_in_memory`` now
+# runs on ``init`` too, where it never ran before. A v26 store built by ``init`` has
+# neither marker; one built by ``update`` has the second.
+#
# v26: ``.all()`` on an imported or module-global name (a plugin registry) is not a
# db sink, a SQL string saying ``LIMIT n`` caps a read, and a batched read is never
# proven for ``session.get`` or beside a call made for its effect; a v25 store differs.
@@ -257,7 +263,7 @@ log = structlog.get_logger(__name__)
# forms. Files that were counted untested and are not become tested, which
# moves untested-hotspot findings and the scores that carry them, on every
# language with a prefix or spec convention rather than Ruby alone.
-HEALTH_ANALYZER_VERSION = 26
+HEALTH_ANALYZER_VERSION = 27
def walked_functions(
@@ -675,9 +681,6 @@ class HealthAnalyzer:
repo_dependents_p80 = _compute_repo_dependents_p80(self.parsed_files, self.graph)
repo_active_contributors = _compute_repo_active_contributors(self.git_meta_map)
- # Cross-function N+1: augment perf_hits before the biomarker stage.
- with timed(timings, "analysis.health.crossfn"):
- self._apply_crossfn_perf(walked)
# Cross-file test oracles, same rule: resolve before the marker runs.
with timed(timings, "analysis.health.oracle_reach"):
self._apply_cross_file_oracles(walked)
@@ -685,13 +688,7 @@ class HealthAnalyzer:
# and the Extract Method detector below read the same lazily parsed
# per-file object, so no file is parsed twice for dataflow.
dataflow_cache = FileDataflowCache(self.read_source)
- # Dataflow promotion: mark advisory perf hits whose loop is provably
- # iteration-independent (runs after the graph passes so the
- # centrality-gated nested-loop hits are present to promote).
- with timed(timings, "analysis.health.promotions"):
- apply_perf_promotions(walked, dataflow=dataflow_cache)
- with timed(timings, "analysis.health.unbounded_reduction"):
- collect_unbounded_reductions(walked, read_source=self.read_source)
+ self._augment_perf_hits(walked, dataflow_cache, timings)
timings_evaluate = timed(timings, "analysis.health.evaluate")
timings_evaluate.__enter__()
@@ -894,16 +891,12 @@ class HealthAnalyzer:
repo_dependents_p80 = _compute_repo_dependents_p80(self.parsed_files, self.graph)
repo_active_contributors = _compute_repo_active_contributors(self.git_meta_map)
- # Cross-function N+1: augment perf_hits before the biomarker stage.
walked = list(walked)
- self._apply_crossfn_perf(walked)
# Cross-file test oracles, same rule: resolve before the marker runs.
self._apply_cross_file_oracles(walked)
# One shared dataflow service per pass (see the sync path above).
dataflow_cache = FileDataflowCache(self.read_source)
- # Dataflow promotion: mark advisory perf hits whose loop is provably
- # iteration-independent (after the graph passes populate the hits).
- apply_perf_promotions(walked, dataflow=dataflow_cache)
+ self._augment_perf_hits(walked, dataflow_cache, timings=None)
disabled_refactorings: list[str] = list(cfg.get("disabled_refactorings", ()))
refactoring_enabled: bool = bool(cfg.get("refactoring_enabled", True))
@@ -1026,6 +1019,26 @@ class HealthAnalyzer:
log.debug("health_cross_file_oracles_failed", error=str(exc))
return
+ def _augment_perf_hits(
+ self,
+ walked: list[tuple[Any, FileComplexity]],
+ dataflow: FileDataflowCache,
+ timings: Any | None,
+ ) -> None:
+ """Every post-walk perf pass, shared by ``analyze`` and ``analyze_async`` so
+ the two paths cannot drift apart again. Promotions read the crossfn hits,
+ so crossfn runs first."""
+ from repowise.core.pipeline.phase_timing import timed
+
+ with timed(timings, "analysis.health.crossfn"):
+ self._apply_crossfn_perf(walked)
+ with timed(timings, "analysis.health.promotions"):
+ apply_perf_promotions(walked, dataflow=dataflow)
+ with timed(timings, "analysis.health.unbounded_reduction"):
+ collect_unbounded_reductions(walked, read_source=self.read_source)
+ with timed(timings, "analysis.health.lazy_load"):
+ collect_lazy_loads(walked, self.parsed_files, read_source=self.read_source)
+
def _apply_crossfn_perf(self, walked: list[tuple[Any, FileComplexity]]) -> None:
"""Run the graph-dependent perf passes over the walked files, in place.
diff --git a/packages/core/src/repowise/core/analysis/health/perf/actionability.py b/packages/core/src/repowise/core/analysis/health/perf/actionability.py
index c3dfe5543..9f89ea5d7 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/actionability.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/actionability.py
@@ -33,6 +33,7 @@ FixStrategy = Literal[
"batch_or_prefetch_io",
"shrink_lock_scope",
"push_reduction_into_query",
+ "eager_load_relationship",
]
BATCHABLE_MARKERS = frozenset({"io_in_loop", "nested_loop_with_io"})
@@ -110,6 +111,53 @@ def provenance_confidence(provenance: str) -> OpportunityConfidence:
return "low"
+# Markers whose FixAssessment depends on nothing but the marker itself: looked up
+# once, at the point in the gate order the first of them used to sit.
+_CONSTANT_FIXES: dict[str, FixAssessment] = {
+ "membership_test_against_list_in_loop": FixAssessment(
+ PerformanceFix(
+ "replace_membership_collection",
+ "advisory",
+ "The collection is proven list-backed; element hashability and "
+ "ordering/identity use still require validation.",
+ ),
+ ("element_hashability", "ordering_and_identity_use"),
+ ),
+ "string_concat_in_loop": FixAssessment(
+ PerformanceFix(
+ "buffer_string_accumulation",
+ "advisory",
+ "Repeated string accumulation is proven; intermediate accumulator "
+ "observations still require validation.",
+ ),
+ ("accumulator_not_observed",),
+ ),
+ "unbounded_read_reduced_in_memory": FixAssessment(
+ PerformanceFix(
+ "push_reduction_into_query",
+ "advisory",
+ "The read is proven unbounded and the per-key selection proven "
+ "Python-side; whether the query layer can express that "
+ "selection (DISTINCT ON / a window function / a view) is not.",
+ ),
+ ("query_supports_group_selection",),
+ ),
+ "lazy_load_in_loop": FixAssessment(
+ PerformanceFix(
+ "eager_load_relationship",
+ "advisory",
+ "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.",
+ ),
+ ("relationship_not_loaded_elsewhere",),
+ ),
+ # Hoisting needs per-argument dataflow plus a guard against attribute mutation
+ # (``Client(token=self.token)``); neither exists, so no strategy.
+ "resource_construction_in_loop": FixAssessment(None, ("loop_invariant_construction_proof",)),
+}
+
+
def assess_fix(
marker: str,
markers: tuple[str, ...],
@@ -161,37 +209,8 @@ def assess_fix(
),
(),
)
- if marker == "membership_test_against_list_in_loop":
- return FixAssessment(
- PerformanceFix(
- "replace_membership_collection",
- "advisory",
- "The collection is proven list-backed; element hashability and "
- "ordering/identity use still require validation.",
- ),
- ("element_hashability", "ordering_and_identity_use"),
- )
- if marker == "string_concat_in_loop":
- return FixAssessment(
- PerformanceFix(
- "buffer_string_accumulation",
- "advisory",
- "Repeated string accumulation is proven; intermediate accumulator "
- "observations still require validation.",
- ),
- ("accumulator_not_observed",),
- )
- if marker == "unbounded_read_reduced_in_memory":
- return FixAssessment(
- PerformanceFix(
- "push_reduction_into_query",
- "advisory",
- "The read is proven unbounded and the per-key selection proven "
- "Python-side; whether the query layer can express that "
- "selection (DISTINCT ON / a window function / a view) is not.",
- ),
- ("query_supports_group_selection",),
- )
+ if marker in _CONSTANT_FIXES:
+ return _CONSTANT_FIXES[marker]
if set(markers) <= BATCHABLE_MARKERS:
if details and all(detail.get("chunked_iteration") for detail in details):
# The loop is already the batch; "batch this" repeats advice taken.
@@ -247,10 +266,6 @@ def assess_fix(
),
("shared_state_ordering",),
)
- if marker == "resource_construction_in_loop":
- # Hoisting needs per-argument dataflow plus a guard against attribute
- # mutation (``Client(token=self.token)``); neither exists, so no strategy.
- return FixAssessment(None, ("loop_invariant_construction_proof",))
return FixAssessment(None, ("supported_strategy_for_marker",))
diff --git a/packages/core/src/repowise/core/analysis/health/perf/lazy_load.py b/packages/core/src/repowise/core/analysis/health/perf/lazy_load.py
new file mode 100644
index 000000000..a184ea8f7
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/lazy_load.py
@@ -0,0 +1,725 @@
+"""A lazy relationship attribute read inside a loop over model rows.
+
+Typed against the cross-file model index (:mod:`orm_models`): the loop's
+iterable must resolve to one SQLAlchemy/Django model, and the accessed
+attribute must be a ``lazy=True`` relation of it, not already eager-loaded on
+the producer or a refinement. Python only.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+import structlog
+
+from ..complexity.ast_utils import _collect_function_nodes, _find_function_entry_name, _node_text
+from ..complexity.models import PerfHit
+from .dialects import PERF_DIALECTS
+from .io_boundaries import collect_io_names
+from .loop_facts import LoopFacts
+from .orm_models import (
+ ModelIndex,
+ Relation,
+ _call_args,
+ _string_content,
+ _target_name,
+ build_model_index,
+)
+from .reduction_idioms import field_text, ident, walk
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Iterable
+
+ from tree_sitter import Node
+
+ from ..complexity.models import FileComplexity
+ from ..source_reader import SourceReader
+ from .dialects.base import BasePerfDialect
+
+log = structlog.get_logger(__name__)
+
+_KIND = "lazy_load_in_loop"
+_ITER_HINTS: tuple[bytes, ...] = (b".query", b"query(", b".objects", b"select(", b"scalars(")
+_SCOPES = frozenset({"function_definition", "lambda"})
+_LOOP_KINDS = frozenset(
+ {
+ "for_statement", "list_comprehension", "set_comprehension",
+ "dictionary_comprehension", "generator_expression",
+ }
+)
+_SA_CHAIN_METHODS = frozenset(
+ {
+ "filter", "filter_by", "where", "order_by", "join", "outerjoin", "options", "limit",
+ "offset", "distinct", "group_by", "having", "all", "yield_per", "execution_options",
+ "params", "enable_eagerloads", "populate_existing", "with_for_update", "unique",
+ "scalars", "select_from", "correlate", "paginate",
+ }
+)
+_DJANGO_CHAIN_METHODS = frozenset(
+ {
+ "all", "filter", "exclude", "order_by", "select_related", "prefetch_related",
+ "distinct", "annotate", "only", "defer", "using", "iterator", "reverse",
+ "select_for_update",
+ }
+)
+_DJANGO_WRITE_METHODS = frozenset(
+ {
+ "add", "remove", "set", "clear", "create", "get_or_create", "update_or_create",
+ "update", "delete", "bulk_create",
+ }
+)
+# Column options load nothing related, so they hide nothing from the eager check.
+_SA_COLUMN_OPTIONS = frozenset(
+ {"load_only", "defer", "undefer", "undefer_group", "with_expression"}
+)
+_SA_EAGER_FUNCS = frozenset(
+ {
+ "joinedload", "selectinload", "subqueryload", "contains_eager", "immediateload",
+ "raiseload", "noload", "defaultload", "lazyload",
+ }
+)
+
+
+@dataclass(frozen=True, slots=True)
+class _FileScan:
+ """Per-file facts every loop check in this file needs."""
+
+ dialect: BasePerfDialect
+ io_names: dict[str, str]
+ has_db_import: bool
+ index: ModelIndex
+
+
+def collect_lazy_loads(
+ walked: Iterable[tuple[Any, FileComplexity]],
+ parsed_files: Iterable[Any],
+ read_source: SourceReader | None = None,
+) -> None:
+ """Append hits to each walked file's ``perf_hits``; one file failing skips only it."""
+ reader = read_source or _disk_read
+ index = build_model_index(parsed_files, reader)
+ for pf, fcx in walked:
+ try:
+ fcx.perf_hits.extend(_file_hits(pf, reader, index))
+ except Exception as exc:
+ log.debug("lazy_load_failed", path=pf.file_info.abs_path, error=str(exc))
+
+
+def _disk_read(abs_path: str) -> bytes | None:
+ try:
+ return Path(abs_path).read_bytes()
+ except OSError:
+ return None
+
+
+def _file_hits(pf: Any, read_source: SourceReader, index: ModelIndex) -> list[PerfHit]:
+ info = pf.file_info
+ if info.language != "python":
+ return []
+ source = read_source(info.abs_path)
+ if source is None or not any(h in source for h in _ITER_HINTS):
+ return []
+ from ..dataflow.parsing import parse_source # deferred: dataflow imports perf
+
+ parsed = parse_source(info.abs_path, info.language, source)
+ if parsed is None:
+ return []
+ root, lmap = parsed
+ dialect = PERF_DIALECTS.get("python")
+ if dialect is None:
+ return []
+ io_names = collect_io_names(root, "python")
+ scan = _FileScan(
+ dialect=dialect,
+ io_names=io_names,
+ has_db_import=any(v == "db" for v in io_names.values()),
+ index=index,
+ )
+ functions = _collect_function_nodes(root, lmap)
+ named = [(fn, _find_function_entry_name(fn, lmap)) for fn in functions]
+ return [hit for fn, name in named for hit in _function_hits(fn, name, scan)]
+
+
+def _function_hits(fn: Node, fn_name: str | None, scan: _FileScan) -> list[PerfHit]:
+ if scan.dialect.is_async_fn(fn):
+ return []
+ body = fn.child_by_field_name("body")
+ if body is None:
+ return []
+ hits: list[PerfHit] = []
+ for loop in (n for n in walk(body, _SCOPES) if n.type in _LOOP_KINDS):
+ hit = _loop_hit(loop, fn, fn_name, scan)
+ if hit is not None:
+ hits.append(hit)
+ return hits
+
+
+# -- loop header -----------------------------------------------------------------
+
+
+def _for_target(node: Node) -> tuple[str, Node] | None:
+ """``(target name, iterable expr)`` for a ``for_statement`` / ``for_in_clause``."""
+ left = node.child_by_field_name("left")
+ right = node.child_by_field_name("right")
+ if right is None:
+ return None
+ name = ident(left)
+ if name is not None:
+ return name, right
+ return _enumerate_target(left, right)
+
+
+def _enumerate_target(left: Node | None, right: Node) -> tuple[str, Node] | None:
+ """``for i, row in enumerate(xs):`` -> the second name and ``xs``."""
+ names = _tuple_pattern_names(left)
+ if names is None or right.type != "call" or not _is_enumerate_call(right):
+ return None
+ positional, _kw = _call_args(right)
+ if len(positional) != 1:
+ return None
+ return names[1], positional[0]
+
+
+def _tuple_pattern_names(left: Node | None) -> list[str] | None:
+ """The two bound names of a ``pattern_list``/``tuple_pattern``, else ``None``."""
+ if left is None or left.type not in ("pattern_list", "tuple_pattern"):
+ return None
+ names = [ident(c) for c in left.children if c.is_named]
+ return names if len(names) == 2 and all(names) else None
+
+
+def _is_enumerate_call(call: Node) -> bool:
+ callee = call.child_by_field_name("function")
+ return callee is not None and _node_text(callee) == "enumerate"
+
+
+def _loop_target(loop: Node) -> tuple[str, Node] | None:
+ if loop.type == "for_statement":
+ return _for_target(loop)
+ for_in = next((c for c in loop.children if c.type == "for_in_clause"), None)
+ return _for_target(for_in) if for_in is not None else None
+
+
+def _scan_scope(loop: Node) -> list[Node]:
+ """Nodes to search for a lazy access: the ``for`` body, or a comprehension's
+ element/key/value expressions and ``if`` clauses."""
+ if loop.type == "for_statement":
+ body = loop.child_by_field_name("body")
+ return [body] if body is not None else []
+ return [c for c in loop.children if c.is_named and c.type != "for_in_clause"]
+
+
+def _target_reassigned(nodes: list[Node], target: str) -> bool:
+ for root in nodes:
+ for node in walk(root, _SCOPES):
+ if node.type == "assignment" and ident(node.child_by_field_name("left")) == target:
+ return True
+ if node.type == "del_statement" and any(ident(c) == target for c in node.children):
+ return True
+ if node.type in ("for_statement", "for_in_clause") and target in _pattern_names(
+ node.child_by_field_name("left")
+ ):
+ return True
+ return False
+
+
+# -- typing: resolving the iterable to one model -----------------------------------
+
+
+def _single_model_arg(call: Node, index: ModelIndex) -> str | None:
+ positional, _kwargs = _call_args(call)
+ if len(positional) != 1:
+ return None
+ name = _target_name(positional[0])
+ return name if name in index.models else None
+
+
+def _match_select_chain(expr: Node, index: ModelIndex) -> str | None:
+ """``select(M)<chain>`` -> ``M``, walking the SQLAlchemy chain allowlist."""
+ if expr.type != "call":
+ return None
+ callee = expr.child_by_field_name("function")
+ if callee is None:
+ return None
+ if callee.type == "identifier" and _node_text(callee) == "select":
+ return _single_model_arg(expr, index)
+ if callee.type == "attribute":
+ method = field_text(callee, "attribute")
+ receiver = callee.child_by_field_name("object")
+ if receiver is not None and method in _SA_CHAIN_METHODS:
+ return _match_select_chain(receiver, index)
+ return None
+
+
+def _select_model(arg: Node | None, fn: Node, index: ModelIndex) -> str | None:
+ if arg is None:
+ return None
+ if arg.type == "identifier":
+ rhs = _assignments_before(fn, _node_text(arg) or "", arg.start_byte)
+ return _select_model(rhs[-1], fn, index) if rhs else None
+ return _match_select_chain(arg, index)
+
+
+def _match_producer(
+ expr: Node | None,
+ fn: Node,
+ index: ModelIndex,
+ self_name: str | None = None,
+ self_value: tuple[str, str] | None = None,
+) -> tuple[str, str] | None:
+ """``(model, orm)`` if *expr* is a producer chain typed to one model, else ``None``."""
+ if expr is None:
+ return None
+ if expr.type == "parenthesized_expression":
+ inner = next((c for c in expr.children if c.is_named), None)
+ return _match_producer(inner, fn, index, self_name, self_value)
+ if expr.type == "identifier":
+ return _match_self_producer(expr, self_name, self_value)
+ if expr.type == "subscript":
+ return _match_slice_producer(expr, fn, index, self_name, self_value)
+ if expr.type == "attribute":
+ return _match_attribute_producer(expr, fn, index, self_name, self_value)
+ if expr.type == "call":
+ return _match_call_producer(expr, fn, index, self_name, self_value)
+ return None
+
+
+def _match_self_producer(
+ expr: Node, self_name: str | None, self_value: tuple[str, str] | None
+) -> tuple[str, str] | None:
+ if self_name is None or _node_text(expr) != self_name:
+ return None
+ return self_value
+
+
+def _match_slice_producer(
+ expr: Node,
+ fn: Node,
+ index: ModelIndex,
+ self_name: str | None,
+ self_value: tuple[str, str] | None,
+) -> tuple[str, str] | None:
+ piece = expr.child_by_field_name("subscript")
+ value = expr.child_by_field_name("value")
+ if piece is None or piece.type != "slice" or value is None:
+ return None
+ return _match_producer(value, fn, index, self_name, self_value)
+
+
+def _match_attribute_producer(
+ expr: Node,
+ fn: Node,
+ index: ModelIndex,
+ self_name: str | None,
+ self_value: tuple[str, str] | None,
+) -> tuple[str, str] | None:
+ method = field_text(expr, "attribute")
+ obj = expr.child_by_field_name("object")
+ if obj is None:
+ return None
+ if method == "query":
+ model = ident(obj)
+ return (model, "sqlalchemy") if model in index.models else None
+ if method == "objects":
+ model = ident(obj)
+ typed = model in index.models and model not in index.custom_managers
+ return (model, "django") if typed else None
+ if method == "items" and obj.type == "call":
+ inner_fn = obj.child_by_field_name("function")
+ if inner_fn is not None and field_text(inner_fn, "attribute") == "paginate":
+ return _match_producer(obj, fn, index, self_name, self_value)
+ return None
+
+
+def _match_call_producer(
+ expr: Node,
+ fn: Node,
+ index: ModelIndex,
+ self_name: str | None,
+ self_value: tuple[str, str] | None,
+) -> tuple[str, str] | None:
+ callee = expr.child_by_field_name("function")
+ if callee is None or callee.type != "attribute":
+ return None
+ method = field_text(callee, "attribute")
+ receiver = callee.child_by_field_name("object")
+ if method == "query":
+ model = _single_model_arg(expr, index)
+ return (model, "sqlalchemy") if model else None
+ if method == "scalars":
+ return _match_scalars_producer(expr, fn, index, receiver)
+ if receiver is not None:
+ return _match_chain_producer(method, receiver, fn, index, self_name, self_value)
+ return None
+
+
+def _match_scalars_producer(
+ expr: Node, fn: Node, index: ModelIndex, receiver: Node | None
+) -> tuple[str, str] | None:
+ positional, _kw = _call_args(expr)
+ if len(positional) == 1:
+ model = _select_model(positional[0], fn, index)
+ return (model, "sqlalchemy") if model else None
+ if receiver is None or receiver.type != "call":
+ return None
+ inner_callee = receiver.child_by_field_name("function")
+ if inner_callee is None or field_text(inner_callee, "attribute") != "execute":
+ return None
+ exec_pos, _ek = _call_args(receiver)
+ model = _select_model(exec_pos[0], fn, index) if len(exec_pos) == 1 else None
+ return (model, "sqlalchemy") if model else None
+
+
+def _match_chain_producer(
+ method: str,
+ receiver: Node,
+ fn: Node,
+ index: ModelIndex,
+ self_name: str | None,
+ self_value: tuple[str, str] | None,
+) -> tuple[str, str] | None:
+ inner = _match_producer(receiver, fn, index, self_name, self_value)
+ if inner is None:
+ return None
+ model, orm = inner
+ allowed = _SA_CHAIN_METHODS if orm == "sqlalchemy" else _DJANGO_CHAIN_METHODS
+ return (model, orm) if method in allowed else None
+
+
+def _is_param(fn: Node, name: str) -> bool:
+ params = fn.child_by_field_name("parameters")
+ if params is None:
+ return False
+ for p in params.children:
+ if not p.is_named:
+ continue
+ if p.type == "identifier" and _node_text(p) == name:
+ return True
+ nm = p.child_by_field_name("name") or next(
+ (c for c in p.children if c.type == "identifier"), None
+ )
+ if nm is not None and _node_text(nm) == name:
+ return True
+ return False
+
+
+def _pattern_names(node: Node | None) -> set[str]:
+ if node is None:
+ return set()
+ return {ident(c) for c in walk(node) if ident(c) is not None}
+
+
+def _rebinds(fn: Node, name: str, before: int) -> bool:
+ """A parameter, an augmented assignment, or a ``for``/``with``/``except`` binding
+ of *name* anywhere before *before* -> the name is not a clean producer chain."""
+ for node in walk(fn, _SCOPES):
+ if node.start_byte >= before:
+ continue
+ if node.type == "augmented_assignment" and ident(node.child_by_field_name("left")) == name:
+ return True
+ left = node.child_by_field_name("left") if node.type == "for_statement" else None
+ if left is not None and name in _pattern_names(left):
+ return True
+ if node.type == "as_pattern":
+ named = [c for c in node.children if c.is_named]
+ target = named[-1] if len(named) >= 2 else None
+ if name in _pattern_names(target):
+ return True
+ return False
+
+
+def _assignments_before(fn: Node, name: str, before: int) -> list[Node]:
+ out = [
+ n.child_by_field_name("right")
+ for n in walk(fn, _SCOPES)
+ if n.type == "assignment"
+ and n.start_byte < before
+ and ident(n.child_by_field_name("left")) == name
+ ]
+ out = [n for n in out if n is not None]
+ out.sort(key=lambda n: n.start_byte)
+ return out
+
+
+def _model_of_iterable(
+ iterable: Node, loop: Node, fn: Node, index: ModelIndex
+) -> tuple[str, str] | None:
+ if iterable.type != "identifier":
+ return _match_producer(iterable, fn, index)
+ name = _node_text(iterable) or ""
+ if _is_param(fn, name) or _rebinds(fn, name, loop.start_byte):
+ return None
+ current: tuple[str, str] | None = None
+ for rhs in _assignments_before(fn, name, loop.start_byte):
+ matched = _match_producer(rhs, fn, index, self_name=name, self_value=current)
+ if matched is None or (current is not None and matched != current):
+ return None
+ current = matched
+ return current
+
+
+# -- eager check ------------------------------------------------------------------
+
+
+def _last_segment(callee: Node) -> str | None:
+ if callee.type == "identifier":
+ return _node_text(callee)
+ if callee.type == "attribute":
+ return field_text(callee, "attribute")
+ return None
+
+
+def _walk_scan_scope(nodes: list[Node]) -> Iterable[Node]:
+ """Flatten a scan scope's roots into one node stream."""
+ for root in nodes:
+ yield from walk(root, _SCOPES)
+
+
+def _sa_eager_names(nodes: list[Node]) -> tuple[set[str], bool]:
+ """Relations the loaders name, and whether an option hides what it loads (a helper
+ call, a variable, ``"*"``): then nothing on these rows is reported."""
+ names: set[str] = set()
+ opaque = False
+ for node in _walk_scan_scope(nodes):
+ if node.type == "call":
+ found_names, found_opaque = _sa_call_names(node)
+ names |= found_names
+ opaque |= found_opaque
+ return names, opaque
+
+
+def _sa_call_names(node: Node) -> tuple[set[str], bool]:
+ """Names and an opaque flag from one call, if it is a loader or ``.options()``."""
+ callee = node.child_by_field_name("function")
+ fname = _last_segment(callee) if callee is not None else None
+ if fname == "options":
+ return set(), any(_opaque_option(arg) for arg in _call_args(node)[0])
+ if fname not in _SA_EAGER_FUNCS:
+ return set(), False
+ names: set[str] = set()
+ opaque = False
+ for arg in _call_args(node)[0]:
+ if arg.type == "attribute":
+ names.add(field_text(arg, "attribute"))
+ elif (text := _string_content(arg)) == "*":
+ opaque = True
+ elif text:
+ names.update(text.split("."))
+ return names, opaque
+
+
+def _opaque_option(arg: Node) -> bool:
+ """An ``.options()`` argument that is not a loader or column option call we can read."""
+ callee = arg.child_by_field_name("function") if arg.type == "call" else None
+ return callee is None or _last_segment(callee) not in _SA_EAGER_FUNCS | _SA_COLUMN_OPTIONS
+
+
+def _django_eager_names(nodes: list[Node]) -> tuple[set[str], bool, bool]:
+ """``(names, bare select_related(), opaque argument)``."""
+ names: set[str] = set()
+ bare = opaque = False
+ for node in _walk_scan_scope(nodes):
+ result = _django_call_names(node)
+ if result is None:
+ continue
+ found_names, found_bare, found_opaque = result
+ names |= found_names
+ bare |= found_bare
+ opaque |= found_opaque
+ return names, bare, opaque
+
+
+def _django_call_names(node: Node) -> tuple[set[str], bool, bool] | None:
+ """``(names, bare select_related(), opaque)`` for one call, or ``None`` if not a loader."""
+ callee = node.child_by_field_name("function") if node.type == "call" else None
+ fname = _last_segment(callee) if callee is not None else None
+ if fname not in ("select_related", "prefetch_related"):
+ return None
+ positional = _call_args(node)[0]
+ bare = fname == "select_related" and not positional
+ names: set[str] = set()
+ opaque = False
+ for arg in positional:
+ found_names, found_opaque = _django_arg_names(arg)
+ names |= found_names
+ opaque |= found_opaque
+ return names, bare, opaque
+
+
+def _django_arg_names(arg: Node) -> tuple[set[str], bool]:
+ """``(names, opaque)`` for one ``select_related``/``prefetch_related`` argument."""
+ inner = arg.child_by_field_name("function") if arg.type == "call" else None
+ if inner is not None and _last_segment(inner) == "Prefetch":
+ arg = next(iter(_call_args(arg)[0]), arg)
+ text = _string_content(arg)
+ if text:
+ return set(text.split("__")), False
+ return set(), True
+
+
+def _eager_check(orm: str, nodes: list[Node]) -> Callable[[str, str], bool]:
+ """``(attr, kind) -> loaded with the rows?`` over the producer and its assignments."""
+ if orm == "sqlalchemy":
+ names, opaque = _sa_eager_names(nodes)
+ return lambda attr, kind: opaque or attr in names
+ names, bare, opaque = _django_eager_names(nodes)
+ # A bare ``select_related()`` follows forward FK / O2O only; ``kind`` cannot tell a
+ # reverse O2O from a forward one, so it is silenced too (recall only).
+ return lambda attr, kind: opaque or attr in names or (bare and kind == "object")
+
+
+# -- access + hit assembly ----------------------------------------------------------
+
+
+def _is_write_target(node: Node) -> bool:
+ parent = node.parent
+ if parent is None:
+ return False
+ if parent.type == "assignment" and parent.child_by_field_name("left") == node:
+ return True
+ if parent.type == "del_statement":
+ return any(c == node for c in parent.children if c.is_named)
+ return False
+
+
+def _writes_through_manager(node: Node) -> bool:
+ """``row.rel.add(x)`` / ``row.rel.all().update(...)``: a Django manager used to write.
+ The per-row query is a write, which no eager load removes."""
+ cur = node
+ while cur.parent is not None:
+ parent = cur.parent
+ if parent.type == "attribute" and parent.child_by_field_name("object") == cur:
+ if field_text(parent, "attribute") in _DJANGO_WRITE_METHODS:
+ return True
+ elif not (parent.type == "call" and parent.child_by_field_name("function") == cur):
+ return False
+ cur = parent
+ return False
+
+
+def _is_lazy_access(
+ node: Node,
+ target: str,
+ relations: dict[str, Relation],
+ orm: str,
+ loaded: Callable[[str, str], bool],
+) -> str | None:
+ """The relation name if *node* is an unresolved lazy access on *target*, else ``None``."""
+ if node.type != "attribute":
+ return None
+ obj = node.child_by_field_name("object")
+ if ident(obj) != target:
+ return None
+ attr = field_text(node, "attribute")
+ relation = relations.get(attr)
+ if relation is None or not relation.lazy or relation.orm != orm:
+ return None
+ if _is_write_target(node) or loaded(attr, relation.kind):
+ return None
+ manager = relation.orm == "django" and relation.kind == "collection"
+ if manager and _writes_through_manager(node):
+ return None
+ return attr
+
+
+def _find_access(
+ nodes: list[Node],
+ target: str,
+ relations: dict[str, Relation],
+ orm: str,
+ loaded: Callable[[str, str], bool],
+) -> tuple[Node, str] | None:
+ best: tuple[Node, str, tuple[int, int]] | None = None
+ for root in nodes:
+ for node in walk(root, _SCOPES):
+ attr = _is_lazy_access(node, target, relations, orm, loaded)
+ if attr is None:
+ continue
+ pos = (node.start_point[0], node.start_point[1])
+ if best is None or pos < best[2]:
+ best = (node, attr, pos)
+ return (best[0], best[1]) if best is not None else None
+
+
+def _fix_text(model: str, attr: str, relation: Relation) -> tuple[str, str]:
+ subject = f"{model}.{attr}"
+ if relation.orm == "sqlalchemy":
+ return subject, f"selectinload({subject})"
+ if relation.kind == "object":
+ return subject, f'select_related("{attr}")'
+ return subject, f'prefetch_related("{attr}")'
+
+
+def _loop_facts(loop: Node, scan: _FileScan) -> LoopFacts | None:
+ def probe(call: Node) -> str | None:
+ return scan.dialect.call_sink_kind(
+ call,
+ awaited=scan.dialect.is_awaited(call),
+ io_names=scan.io_names,
+ has_db_import=scan.has_db_import,
+ )
+
+ facts = LoopFacts(
+ chunked=scan.dialect.is_chunked_loop(loop),
+ magnitude=scan.dialect.loop_magnitude(loop, probe) or "unknown",
+ )
+ return None if facts == LoopFacts() else facts
+
+
+def _eager_candidate_nodes(iterable_expr: Node, fn: Node, loop: Node) -> list[Node]:
+ """The producer, and every assignment before the loop to a name it reads, transitively:
+ the rows' own refinements and a ``stmt = select(M).options(...)`` behind ``scalars``."""
+ eager_nodes = [iterable_expr]
+ seen: set[str] = set()
+ for node in eager_nodes:
+ for name in _pattern_names(node) - seen:
+ seen.add(name)
+ eager_nodes += _assignments_before(fn, name, loop.start_byte)
+ return eager_nodes
+
+
+def _loop_hit(
+ loop: Node,
+ fn: Node,
+ fn_name: str | None,
+ scan: _FileScan,
+) -> PerfHit | None:
+ is_for = loop.type == "for_statement"
+ if is_for and scan.dialect.is_constant_loop(loop):
+ return None
+ target_info = _loop_target(loop)
+ if target_info is None:
+ return None
+ target, iterable_expr = target_info
+ typed = _model_of_iterable(iterable_expr, loop, fn, scan.index)
+ if typed is None:
+ return None
+ model, orm = typed
+ relations = scan.index.relations.get(model, {})
+ if not relations:
+ return None
+ scan_nodes = _scan_scope(loop)
+ if not scan_nodes or _target_reassigned(scan_nodes, target):
+ return None
+ eager_nodes = _eager_candidate_nodes(iterable_expr, fn, loop)
+ access = _find_access(scan_nodes, target, relations, orm, _eager_check(orm, eager_nodes))
+ if access is None:
+ return None
+ node, attr = access
+ relation = relations[attr]
+ subject, fix = _fix_text(model, attr, relation)
+ loop_facts = _loop_facts(loop, scan) if is_for else None
+ return PerfHit(
+ _KIND,
+ node.start_point[0] + 1,
+ fn_name,
+ "db",
+ func_start=fn.start_point[0] + 1,
+ path=(subject, fix),
+ loop=loop_facts,
+ )
+
+
+__all__ = ["collect_lazy_loads"]
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 6a9c47694..6725bfc01 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
@@ -41,6 +41,8 @@ MULTIPLIER_POINTS = {
"goroutine_in_unbounded_loop": 4,
"hot_path_sync_io": 4,
"unbounded_read_reduced_in_memory": 4,
+ # One round trip per iteration, same shape as io_in_loop.
+ "lazy_load_in_loop": 4,
# In-loop CPU or allocation: real, and orders below a round-trip.
"membership_test_against_list_in_loop": 3,
"string_concat_in_loop": 3,
@@ -62,6 +64,14 @@ both the observation order and the opportunity order read it and a marker
missing from here would silently take the floor on both.
"""
+NON_LEADING_MARKERS = frozenset({"lazy_load_in_loop"})
+"""Markers that rank normally but never lead the performance directive.
+
+``lazy_load_in_loop`` measured 81% on held-out Django (47/58, 2026-09-26), inside the
+80-90% tier whose pre-registered rule is "advisory, never leads". Remove a marker once a
+held-out sample puts it at 90% or above.
+"""
+
UNKNOWN_MULTIPLIER_POINTS = 1
"""A detector added without a weight under-ranks rather than jumps the queue."""
diff --git a/packages/core/src/repowise/core/analysis/health/perf/orm_models.py b/packages/core/src/repowise/core/analysis/health/perf/orm_models.py
new file mode 100644
index 000000000..e27da3e40
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/orm_models.py
@@ -0,0 +1,500 @@
+"""Cross-file model index: SQLAlchemy relationships + Django FK/O2O/M2M.
+
+Built once per :func:`..lazy_load.collect_lazy_loads` call from every parsed
+Python file of the repo (not only the changed ones an incremental update
+walks), because a lazy access in file A can only be typed against a model
+declared in file B. Byte-prefiltered so a repo with no ORM pays nothing.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING, Any
+
+from ..complexity.ast_utils import _node_text
+from .reduction_idioms import field_text, ident, walk
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from tree_sitter import Node
+
+ from ..source_reader import SourceReader
+
+# Byte prefilter: only a file mentioning one of these is worth parsing.
+_RELATION_HINTS: tuple[bytes, ...] = (
+ b"relationship(",
+ b"ForeignKey(",
+ b"OneToOneField(",
+ b"ManyToManyField(",
+ b"declared_attr",
+)
+
+# A manager or queryset class that eager-loads is found by these, even with no relation.
+_MANAGER_HINTS: tuple[bytes, ...] = (b"get_queryset",)
+_EAGER_QUERYSET_CALLS = frozenset({"select_related", "prefetch_related"})
+
+_SA_LAZY_TRUE_STRINGS = frozenset({"select", "dynamic"})
+_SA_LAZY_FALSE_STRINGS = frozenset(
+ {"joined", "selectin", "subquery", "immediate", "raise", "raise_on_sql", "noload", "write_only"}
+)
+_MAPPED_LIST_HEADS = frozenset({"list", "List", "set"})
+_DJANGO_FORWARD_KIND = {
+ "ForeignKey": "object",
+ "OneToOneField": "object",
+ "ManyToManyField": "collection",
+}
+_DECLARED_ATTR_HINT = "declared_attr"
+
+
+@dataclass(frozen=True, slots=True)
+class Relation:
+ target: str | None
+ orm: str # "sqlalchemy" | "django"
+ kind: str # "object" | "collection"
+ lazy: bool
+
+
+@dataclass(frozen=True, slots=True)
+class ModelIndex:
+ relations: dict[str, dict[str, Relation]]
+ models: frozenset[str]
+ # Models whose ``objects`` manager (or queryset) class, defined in this repo, has a
+ # ``get_queryset`` that select_related / prefetch_related: the caller's chain hides it.
+ custom_managers: frozenset[str] = frozenset()
+
+
+@dataclass
+class _RawClass:
+ relations: dict[str, Relation] = field(default_factory=dict)
+ bases: list[str] = field(default_factory=list)
+ manager_names: set[str] = field(default_factory=set)
+ eager_queryset: bool = False
+
+
+# -- literal readers -----------------------------------------------------------
+
+
+def _string_content(node: Node | None) -> str | None:
+ if node is None or node.type != "string":
+ return None
+ parts = [c.text.decode("utf-8", "replace") for c in node.children if c.type == "string_content"]
+ return "".join(parts) if parts else None
+
+
+def _is_true(node: Node | None) -> bool:
+ return node is not None and node.type == "true"
+
+
+def _target_name(node: Node | None) -> str | None:
+ """The last dotted segment of a string literal / identifier / attribute."""
+ text = _string_content(node)
+ if text is not None:
+ return text.rsplit(".", 1)[-1] or None
+ if node is not None and node.type in ("identifier", "attribute"):
+ raw = _node_text(node)
+ return raw.rsplit(".", 1)[-1] if raw else None
+ return None
+
+
+def _callee_last_segment(call: Node) -> str | None:
+ fn = call.child_by_field_name("function")
+ if fn is None:
+ return None
+ text = _node_text(fn)
+ return text.rsplit(".", 1)[-1] if text else None
+
+
+def _call_args(call: Node) -> tuple[list[Node], dict[str, Node]]:
+ args = call.child_by_field_name("arguments")
+ positional: list[Node] = []
+ kwargs: dict[str, Node] = {}
+ for a in args.children if args is not None else ():
+ if not a.is_named:
+ continue
+ if a.type == "keyword_argument":
+ name = field_text(a, "name")
+ value = a.child_by_field_name("value")
+ if name and value is not None:
+ kwargs[name] = value
+ else:
+ positional.append(a)
+ return positional, kwargs
+
+
+def _class_bases(node: Node) -> list[str]:
+ args = node.child_by_field_name("superclasses")
+ out: list[str] = []
+ for c in args.children if args is not None else ():
+ if not c.is_named or c.type == "keyword_argument":
+ continue
+ text = _node_text(c)
+ if text:
+ out.append(text.rsplit(".", 1)[-1])
+ return out
+
+
+# -- SQLAlchemy ------------------------------------------------------------------
+
+
+def _sa_lazy_mode(value: Node | None) -> bool | None:
+ """True/False for a recognized ``lazy=`` literal; ``None`` -> skip the relationship."""
+ if value is None:
+ return True
+ if value.type == "true":
+ return True
+ if value.type in ("false", "none"):
+ return False
+ text = _string_content(value)
+ if text is not None:
+ if text in _SA_LAZY_TRUE_STRINGS:
+ return True
+ if text in _SA_LAZY_FALSE_STRINGS:
+ return False
+ return None
+
+
+def _mapped_inner(node: Node | None) -> tuple[str | None, bool]:
+ if node is None:
+ return None, False
+ if node.type == "subscript":
+ value = node.child_by_field_name("value")
+ head = _node_text(value) if value is not None else ""
+ inner = node.child_by_field_name("subscript")
+ if head in _MAPPED_LIST_HEADS:
+ target, _ = _mapped_inner(inner)
+ return target, True
+ if head == "Optional":
+ return _mapped_inner(inner)
+ return None, False
+ return _target_name(node), False
+
+
+def _mapped_info(type_node: Node | None) -> tuple[bool, str | None, bool]:
+ """``(is_mapped, target, is_list)`` for a ``Mapped[...]`` annotation."""
+ if type_node is None or type_node.type != "subscript":
+ return False, None, False
+ value = type_node.child_by_field_name("value")
+ if value is None or _node_text(value) != "Mapped":
+ return False, None, False
+ target, is_list = _mapped_inner(type_node.child_by_field_name("subscript"))
+ return True, target, is_list
+
+
+def _sa_backref(kwargs: dict[str, Node]) -> tuple[str, bool] | None:
+ """``(attr name, lazy)`` from ``backref="x"`` / ``backref=backref("x", lazy=...)``."""
+ value = kwargs.get("backref")
+ if value is None:
+ return None
+ text = _string_content(value)
+ if text is not None:
+ return text, True
+ if value.type == "call" and _callee_last_segment(value) == "backref":
+ positional, bkwargs = _call_args(value)
+ name = _string_content(positional[0]) if positional else None
+ if name is None:
+ return None
+ lazy = _sa_lazy_mode(bkwargs.get("lazy"))
+ return (name, lazy) if lazy is not None else None
+ return None
+
+
+def _sa_relationship_call(
+ call: Node, type_node: Node | None, declaring: str
+) -> tuple[Relation, tuple[str, str, Relation] | None] | None:
+ positional, kwargs = _call_args(call)
+ lazy = _sa_lazy_mode(kwargs.get("lazy"))
+ if lazy is None:
+ return None
+ is_mapped, mapped_target, mapped_is_list = _mapped_info(type_node)
+ target = _target_name(positional[0]) if positional else mapped_target
+ uselist = kwargs.get("uselist")
+ if "secondary" in kwargs or (uselist is not None and _is_true(uselist)) or mapped_is_list:
+ kind = "collection"
+ elif (uselist is not None and not _is_true(uselist)) or (is_mapped and not mapped_is_list):
+ kind = "object"
+ else:
+ kind = "collection"
+ relation = Relation(target=target, orm="sqlalchemy", kind=kind, lazy=lazy)
+ pending = None
+ backref = _sa_backref(kwargs)
+ if backref is not None and target is not None:
+ attr_name, backref_lazy = backref
+ reverse = Relation(target=declaring, orm="sqlalchemy", kind="collection", lazy=backref_lazy)
+ pending = (target, attr_name, reverse)
+ return relation, pending
+
+
+def _sa_relation_from_assignment(
+ stmt: Node, declaring: str
+) -> tuple[str, Relation, tuple[str, str, Relation] | None] | None:
+ attr = ident(stmt.child_by_field_name("left"))
+ right = stmt.child_by_field_name("right")
+ if attr is None or right is None or right.type != "call":
+ return None
+ if _callee_last_segment(right) != "relationship":
+ return None
+ result = _sa_relationship_call(right, stmt.child_by_field_name("type"), declaring)
+ if result is None:
+ return None
+ relation, pending = result
+ return attr, relation, pending
+
+
+def _has_declared_attr_decorator(stmt: Node) -> bool:
+ decorators = [c for c in stmt.children if c.type == "decorator"]
+ return any(_DECLARED_ATTR_HINT in (_node_text(d) or "") for d in decorators)
+
+
+def _relationship_return(
+ body: Node, declaring: str
+) -> tuple[Relation, tuple[str, str, Relation] | None] | None:
+ """The resolved call of the first ``return relationship(...)`` in *body*, if any."""
+ for ret in walk(body):
+ if ret.type != "return_statement":
+ continue
+ value = next((c for c in ret.children if c.is_named), None)
+ if value is None or value.type != "call":
+ continue
+ if _callee_last_segment(value) == "relationship":
+ return _sa_relationship_call(value, None, declaring)
+ return None
+
+
+def _sa_declared_attr(
+ stmt: Node, declaring: str
+) -> tuple[str, Relation, tuple[str, str, Relation] | None] | None:
+ """A ``@declared_attr`` method whose body returns a ``relationship(...)`` call."""
+ if not _has_declared_attr_decorator(stmt):
+ return None
+ fn = stmt.child_by_field_name("definition")
+ if fn is None or fn.type != "function_definition":
+ return None
+ name = field_text(fn, "name")
+ body = fn.child_by_field_name("body")
+ if not name or body is None:
+ return None
+ result = _relationship_return(body, declaring)
+ return (name, *result) if result is not None else None
+
+
+# -- Django ------------------------------------------------------------------------
+
+
+def _django_target(positional: list[Node], kwargs: dict[str, Node], declaring: str) -> str | None:
+ arg = positional[0] if positional else kwargs.get("to")
+ if arg is None:
+ return None
+ text = _string_content(arg)
+ if text is not None:
+ return declaring if text == "self" else text.rsplit(".", 1)[-1]
+ if arg.type in ("identifier", "attribute"):
+ raw = _node_text(arg)
+ return raw.rsplit(".", 1)[-1] if raw else None
+ return None
+
+
+def _django_reverse_name(kwargs: dict[str, Node], declaring: str, ctor: str) -> str | None:
+ value = kwargs.get("related_name")
+ if value is not None:
+ text = _string_content(value)
+ if text is None or "%(" in text or text == "+" or text.endswith("+"):
+ return None
+ return text
+ lower = declaring.lower()
+ return lower if ctor == "OneToOneField" else f"{lower}_set"
+
+
+def _django_relation_from_assignment(
+ stmt: Node, declaring: str, is_django_file: bool
+) -> tuple[str, Relation, tuple[str, str, Relation] | None] | None:
+ if not is_django_file:
+ return None
+ attr = ident(stmt.child_by_field_name("left"))
+ right = stmt.child_by_field_name("right")
+ if attr is None or right is None or right.type != "call":
+ return None
+ ctor = _callee_last_segment(right)
+ if ctor not in _DJANGO_FORWARD_KIND:
+ return None
+ positional, kwargs = _call_args(right)
+ target = _django_target(positional, kwargs, declaring)
+ relation = Relation(target=target, orm="django", kind=_DJANGO_FORWARD_KIND[ctor], lazy=True)
+ pending = None
+ reverse_name = _django_reverse_name(kwargs, declaring, ctor)
+ if target is not None and reverse_name:
+ reverse_kind = "object" if ctor == "OneToOneField" else "collection"
+ reverse = Relation(target=declaring, orm="django", kind=reverse_kind, lazy=True)
+ pending = (target, reverse_name, reverse)
+ return attr, relation, pending
+
+
+# -- per-file scan + cross-file merge ---------------------------------------------
+
+
+def _manager_names(stmt: Node) -> set[str]:
+ """Every name in ``objects = X()`` / ``X.as_manager()`` / ``X.from_queryset(Y)()``."""
+ right = stmt.child_by_field_name("right")
+ if ident(stmt.child_by_field_name("left")) != "objects" or right is None:
+ return set()
+ return {name for n in walk(right) if (name := ident(n))}
+
+
+def _has_eager_get_queryset(node: Node) -> bool:
+ """A ``get_queryset`` in this class body that select_related / prefetch_related."""
+ body = node.child_by_field_name("body")
+ return body is not None and any(
+ fn.type == "function_definition"
+ and field_text(fn, "name") == "get_queryset"
+ and any(
+ c.type == "call" and _callee_last_segment(c) in _EAGER_QUERYSET_CALLS
+ for c in walk(fn)
+ )
+ for fn in walk(body)
+ )
+
+
+def _scan_class_body(node: Node, name: str, is_django_file: bool, pending: list) -> _RawClass:
+ body = node.child_by_field_name("body")
+ rc = _RawClass(bases=_class_bases(node), eager_queryset=_has_eager_get_queryset(node))
+ for raw_stmt in body.children if body is not None else ():
+ if not raw_stmt.is_named:
+ continue
+ stmt = (
+ next((c for c in raw_stmt.children if c.is_named), raw_stmt)
+ if raw_stmt.type == "expression_statement"
+ else raw_stmt
+ )
+ result = None
+ if stmt.type == "assignment" and (names := _manager_names(stmt)):
+ rc.manager_names |= names
+ elif stmt.type == "assignment":
+ result = _sa_relation_from_assignment(stmt, name) or _django_relation_from_assignment(
+ stmt, name, is_django_file
+ )
+ elif stmt.type == "decorated_definition":
+ result = _sa_declared_attr(stmt, name)
+ if result is None:
+ continue
+ attr, relation, added = result
+ rc.relations[attr] = relation
+ if added is not None:
+ pending.append(added)
+ return rc
+
+
+def _scan_file(
+ abs_path: str, language: str, source: bytes, pending: list
+) -> dict[str, _RawClass] | None:
+ from ..dataflow.parsing import parse_source # deferred: dataflow imports perf
+
+ parsed = parse_source(abs_path, language, source)
+ if parsed is None:
+ return None
+ root, _lmap = parsed
+ is_django_file = b"django" in source
+ classes: dict[str, _RawClass] = {}
+ for node in walk(root):
+ if node.type != "class_definition":
+ continue
+ name = field_text(node, "name")
+ if not name:
+ continue
+ rc = _scan_class_body(node, name, is_django_file, pending)
+ existing = classes.get(name)
+ if existing is None:
+ classes[name] = rc
+ else:
+ existing.relations.update(rc.relations)
+ existing.bases.extend(rc.bases)
+ existing.manager_names |= rc.manager_names
+ existing.eager_queryset |= rc.eager_queryset
+ return classes
+
+
+_Merged = dict[str, tuple[dict[str, Relation], list[str]]]
+
+
+def _merge_collisions(raw: dict[str, list[_RawClass]]) -> _Merged:
+ merged: _Merged = {}
+ for name, occurrences in raw.items():
+ bases = [b for rc in occurrences for b in rc.bases]
+ if len(occurrences) == 1:
+ merged[name] = (occurrences[0].relations, bases)
+ continue
+ keys = set(occurrences[0].relations)
+ for rc in occurrences[1:]:
+ keys &= set(rc.relations)
+ relations = {
+ k: occurrences[0].relations[k]
+ for k in keys
+ if all(rc.relations[k] == occurrences[0].relations[k] for rc in occurrences)
+ }
+ merged[name] = (relations, bases)
+ return merged
+
+
+def _resolve_inherited(
+ name: str, merged: _Merged, cache: dict[str, dict[str, Relation]]
+) -> dict[str, Relation]:
+ if name in cache:
+ return cache[name]
+ entry = merged.get(name)
+ if entry is None:
+ return {}
+ relations, bases = entry
+ result = dict(relations)
+ cache[name] = result # registered before recursing: cycle-safe
+ for base in bases:
+ if base == name:
+ continue
+ for k, v in _resolve_inherited(base, merged, cache).items():
+ result.setdefault(k, v)
+ return result
+
+
+def build_model_index(parsed_files: Iterable[Any], read_source: SourceReader) -> ModelIndex:
+ raw: dict[str, list[_RawClass]] = {}
+ pending: list[tuple[str, str, Relation]] = []
+ for pf in parsed_files:
+ info = pf.file_info
+ if info.language != "python":
+ continue
+ source = read_source(info.abs_path)
+ if source is None or not any(h in source for h in _RELATION_HINTS + _MANAGER_HINTS):
+ continue
+ classes = _scan_file(info.abs_path, info.language, source, pending)
+ if classes is None:
+ continue
+ for name, rc in classes.items():
+ raw.setdefault(name, []).append(rc)
+ for target, attr, relation in pending:
+ for rc in raw.get(target, ()):
+ rc.relations.setdefault(attr, relation)
+ merged = _merge_collisions(raw)
+ cache: dict[str, dict[str, Relation]] = {}
+ resolved = {name: _resolve_inherited(name, merged, cache) for name in merged}
+ return ModelIndex(
+ relations=resolved,
+ models=frozenset(merged),
+ custom_managers=_with_custom_manager(raw, merged),
+ )
+
+
+def _with_custom_manager(raw: dict[str, list[_RawClass]], merged: _Merged) -> frozenset[str]:
+ """Models whose ``objects`` class eager-loads in ``get_queryset``, or inherit one."""
+ eager = {name for name, rcs in raw.items() if any(rc.eager_queryset for rc in rcs)}
+ found = {
+ name for name, rcs in raw.items() if any(rc.manager_names & eager for rc in rcs)
+ }
+ grew = True
+ while grew:
+ grew = False
+ for name, (_relations, bases) in merged.items():
+ if name not in found and found.intersection(bases):
+ found.add(name)
+ grew = True
+ return frozenset(found)
+
+
+__all__ = ["ModelIndex", "Relation", "build_model_index"]
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index 4d02874c0..ec86a1504 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -263,6 +263,7 @@ _BIOMARKER_DIMENSIONS: dict[str, set[str]] = {
"lock_in_loop": {"performance"},
"serial_await_in_loop": {"performance"},
"unbounded_read_reduced_in_memory": {"performance"},
+ "lazy_load_in_loop": {"performance"},
"membership_test_against_list_in_loop": {"performance"},
# Phase 7b centrality-gated moat markers - performance-only.
"nested_loop_with_io": {"performance"},
@@ -432,6 +433,8 @@ _PERFORMANCE_WEIGHT_MULTIPLIER: dict[str, float] = {
"sql_cartesian_join": 0.6,
# Advisory pending a corpus precision gate, like every new perf marker.
"unbounded_read_reduced_in_memory": 0.4,
+ # Advisory until the pre-registered precision tiers are measured (2026-09-26).
+ "lazy_load_in_loop": 0.4,
}
# All perf biomarkers share one ``performance`` category, so the single cap
@@ -458,6 +461,7 @@ _PERFORMANCE_CATEGORY: dict[str, str] = {
"goroutine_in_unbounded_loop": "performance",
"sql_cartesian_join": "performance",
"unbounded_read_reduced_in_memory": "performance",
+ "lazy_load_in_loop": "performance",
}
# One bounded performance category cap. 2.0 is a deliberately conservative
@@ -493,6 +497,7 @@ _PERFORMANCE_HOME: frozenset[str] = frozenset(
"goroutine_in_unbounded_loop",
"sql_cartesian_join",
"unbounded_read_reduced_in_memory",
+ "lazy_load_in_loop",
}
)
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 1bc4115a1..595d50585 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py
@@ -137,6 +137,8 @@ def _summary_payload(
plans: dict[str, dict[str, Any]] | None = None,
) -> dict:
"""The compact current headline, written once and read by primary key."""
+ from ....analysis.health.perf.opportunity_rank import NON_LEADING_MARKERS
+
counts: dict[str, int] = {}
contexts: dict[str, int] = {}
boundaries: dict[str, int] = {}
@@ -145,8 +147,16 @@ 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
- # ``expected`` rows rank last and offer nothing to do, so they never lead.
- lead = next((o for o in opportunities if o.actionability_state != "expected"), None)
+ # ``expected`` rows rank last and offer nothing to do, so they never lead; nor does a
+ # marker whose measured precision is below the bar for leading.
+ lead = next(
+ (
+ o
+ for o in opportunities
+ if o.actionability_state != "expected" and o.biomarker_type not in NON_LEADING_MARKERS
+ ),
+ None,
+ )
return {
"actionability": counts,
"context": contexts,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index 6e835db5f..910610102 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -32,7 +32,10 @@ from repowise.core.analysis.health.grading import TARGET_SCORE, band_for
from repowise.core.analysis.health.grading import distribution as health_distribution
from repowise.core.analysis.health.models import primary_finding, split_by_origin
from repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metrics
-from repowise.core.analysis.health.perf.opportunity_rank import observation_rank
+from repowise.core.analysis.health.perf.opportunity_rank import (
+ NON_LEADING_MARKERS,
+ observation_rank,
+)
from repowise.core.analysis.health.ranking import deduction_by_path, sort_metrics_worst_first
from repowise.core.analysis.health.refactoring.recommendations import (
Recommendation,
@@ -2810,8 +2813,13 @@ async def get_health(
}
if {"performance", "refactoring"} <= include_set and wants("recommendation_lede"):
- performance_lead = (
- performance.page.items[0] if performance.page and performance.page.items else None
+ performance_lead = next(
+ (
+ item
+ for item in (performance.page.items if performance.page else [])
+ if item.get("biomarker_type") not in NON_LEADING_MARKERS
+ ),
+ None,
)
recommendation_lead = (
refactoring_recommendations[0] if refactoring_recommendations else None
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index b6d343a4c..eb74f76cb 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -298,6 +298,12 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
description:
"A database read with no limit/range/single bound, run once, whose result a loop then dedups down to one row per key (setdefault, a seen-set, a not-in guard). The table can grow without bound while the code still pays to transfer and decode every row. Move the selection into the query: DISTINCT ON, a window function, or a view.",
},
+ lazy_load_in_loop: {
+ label: "Lazy load in loop",
+ category: "performance",
+ description:
+ "A relationship declared lazy (no selectinload / joinedload, no select_related / prefetch_related) read on every iteration of a loop over its parent rows, one query per row. Load the relationship with the rows instead. Advisory: whether every iteration reaches the access, and whether another layer already loaded it, is not proven.",
+ },
membership_test_against_list_in_loop: {
label: "List membership in loop",
category: "performance",
@@ -436,6 +442,7 @@ export const PERFORMANCE_HOME_BIOMARKERS: ReadonlySet<string> = new Set([
"goroutine_in_unbounded_loop",
"sql_cartesian_join",
"unbounded_read_reduced_in_memory",
+ "lazy_load_in_loop",
]);
/**
diff --git a/tests/unit/health/test_model_version_coupling.py b/tests/unit/health/test_model_version_coupling.py
index da6a3d0c2..5d817b7f2 100644
--- a/tests/unit/health/test_model_version_coupling.py
+++ b/tests/unit/health/test_model_version_coupling.py
@@ -22,7 +22,7 @@ from repowise.core.analysis.health.refactoring.identity import (
# The three stamps as they stand together. Moving either identity model means
# moving the analyzer with it, and updating this tuple in the same commit.
-_STAMPS = (26, 2, 2)
+_STAMPS = (27, 2, 2)
def test_the_identity_models_and_the_analyzer_stamp_are_pinned_together() -> None:
diff --git a/tests/unit/health/test_perf_incremental_parity.py b/tests/unit/health/test_perf_incremental_parity.py
index eee8f561a..a3156fc1e 100644
--- a/tests/unit/health/test_perf_incremental_parity.py
+++ b/tests/unit/health/test_perf_incremental_parity.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import json
+import textwrap
import uuid
from pathlib import Path
@@ -15,8 +16,8 @@ from repowise.core.pipeline.incremental import load_stored_performance_callers
from tests.unit.persistence.helpers import insert_repo
-def _repo(tmp_path: Path):
- files = {
+def _repo(tmp_path: Path, files: dict[str, str] | None = None):
+ files = files or {
"db.py": (
"from sqlalchemy import select\n\n"
"def fetch_one(session, rid):\n"
@@ -124,3 +125,57 @@ async def test_old_side_performance_paths_recover_callers_of_deleted_sink(tmp_pa
assert await load_stored_performance_callers(tmp_path, {"deleted.py"}) == {"caller.py"}
await engine.dispose()
+
+
+
+_UNBOUNDED = textwrap.dedent(
+ """
+ def get_repos(supabase, repo_ids):
+ builds = (
+ supabase.table("builds")
+ .select("*")
+ .in_("repo_id", repo_ids)
+ .eq("status", "ready")
+ .order("completed_at", desc=True)
+ .execute()
+ )
+ latest_by_repo = {}
+ for build in builds.data:
+ rid = build["repo_id"]
+ latest_by_repo.setdefault(rid, build)
+ return latest_by_repo
+ """
+)
+_LAZY_MODELS = textwrap.dedent(
+ """
+ class Incident(Base):
+ owner = relationship("User")
+ """
+)
+_LAZY_LOOP = textwrap.dedent(
+ """
+ def names(session):
+ for i in session.query(Incident).all():
+ print(i.owner.name)
+ """
+)
+
+
+async def test_init_and_update_paths_run_the_same_post_walk_perf_passes(tmp_path: Path):
+ """``analyze_async`` (init) once skipped ``collect_unbounded_reductions`` that
+ ``analyze`` (update) ran; both markers must now come out of both paths."""
+ parsed, graph = _repo(
+ tmp_path, {"repos.py": _UNBOUNDED, "models.py": _LAZY_MODELS, "loop.py": _LAZY_LOOP}
+ )
+ wanted = {"unbounded_read_reduced_in_memory", "lazy_load_in_loop"}
+
+ def _kinds(report):
+ return sorted(f.biomarker_type for f in report.findings if f.biomarker_type in wanted)
+
+ sync_report = HealthAnalyzer(graph, parsed_files=parsed, repo_root=tmp_path).analyze()
+ async_report = await HealthAnalyzer(
+ graph, parsed_files=parsed, repo_root=tmp_path
+ ).analyze_async()
+ assert _kinds(sync_report) == sorted(wanted)
+ assert _kinds(async_report) == sorted(wanted)
diff --git a/tests/unit/health/test_perf_lazy_load.py b/tests/unit/health/test_perf_lazy_load.py
new file mode 100644
index 000000000..709d0a38b
--- /dev/null
+++ b/tests/unit/health/test_perf_lazy_load.py
@@ -0,0 +1,834 @@
+"""Unit tests for ``lazy_load_in_loop``.
+
+Multi-file fixtures: models live in one file, the loop in another, mirroring
+the cross-file model index the detector needs. ``parsed_files`` always lists
+every fixture file; ``walked`` lists only the file being scored (as on an
+incremental update).
+"""
+
+from __future__ import annotations
+
+import textwrap
+from dataclasses import dataclass
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.health.complexity import FileComplexity
+from repowise.core.analysis.health.perf.lazy_load import collect_lazy_loads
+from repowise.core.analysis.health.perf.orm_models import build_model_index
+
+_KIND = "lazy_load_in_loop"
+
+
+def _require_python() -> None:
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ pytest.skip("tree-sitter language pack missing for python")
+ if _get_language("python") is None:
+ pytest.skip("tree-sitter language pack missing for python")
+
+
+@dataclass
+class _FileInfo:
+ path: str
+ abs_path: str
+ language: str
+
+
+@dataclass
+class _ParsedFile:
+ file_info: _FileInfo
+
+
+def _write(tmp_path: Path, name: str, src: str) -> _ParsedFile:
+ p = tmp_path / name
+ p.write_text(textwrap.dedent(src), encoding="utf-8")
+ return _ParsedFile(_FileInfo(path=name, abs_path=str(p), language="python"))
+
+
+def _hits(tmp_path: Path, models_src: str, loop_src: str) -> list:
+ _require_python()
+ models_pf = _write(tmp_path, "models.py", models_src)
+ loop_pf = _write(tmp_path, "loop.py", loop_src)
+ fcx = FileComplexity(functions=[], classes=[])
+ collect_lazy_loads([(loop_pf, fcx)], [models_pf, loop_pf])
+ return [h for h in fcx.perf_hits if h.kind == _KIND]
+
+
+# -- SQLAlchemy positives ---------------------------------------------------
+
+
+def test_sa_query_filter_all(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ import sqlite3
+
+ def f(session):
+ for i in session.query(Incident).filter(Incident.id > 1).all():
+ print(i.owner.name)
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].function == "f"
+ assert hits[0].detail == "db"
+ assert hits[0].path == ("Incident.owner", "selectinload(Incident.owner)")
+ assert hits[0].loop is not None
+ assert hits[0].loop.magnitude == "grows_with_data"
+
+
+def test_sa_flask_query_filter_by(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Users:
+ profile = relationship("Profile")
+ """,
+ """
+ def f():
+ for u in Users.query.filter_by(active=True):
+ print(u.profile.bio)
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Users.profile", "selectinload(Users.profile)")
+
+
+def test_sa_select_via_scalars(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Build:
+ repo = relationship("Repo")
+ """,
+ """
+ def f(session):
+ stmt = select(Build).where(Build.id > 1)
+ for b in session.scalars(stmt):
+ print(b.repo.name)
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Build.repo", "selectinload(Build.repo)")
+
+
+def test_sa_execute_scalars(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Build:
+ repo = relationship("Repo")
+ """,
+ """
+ def f(session):
+ for b in session.execute(select(Build)).scalars():
+ print(b.repo.name)
+ """,
+ )
+ assert len(hits) == 1
+
+
+def test_sa_mapped_relationship(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Team:
+ members: Mapped[list["Member"]] = relationship()
+ """,
+ """
+ def f(session):
+ for t in session.query(Team).all():
+ print(t.members)
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Team.members", "selectinload(Team.members)")
+
+
+def test_sa_declared_attr_on_mixin(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class OwnerMixin:
+ @declared_attr
+ def owner(cls):
+ return relationship("User")
+
+ class Incident(OwnerMixin, Base):
+ pass
+ """,
+ """
+ def f(session):
+ for i in session.query(Incident).all():
+ print(i.owner.name)
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Incident.owner", "selectinload(Incident.owner)")
+
+
+def test_sa_backref(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Parent:
+ children = relationship("Child", backref="parent")
+
+ class Child:
+ pass
+ """,
+ """
+ def f(session):
+ for c in session.query(Child).all():
+ print(c.parent.name)
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Child.parent", "selectinload(Child.parent)")
+
+
+def test_sa_lazy_dynamic(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Team:
+ members = relationship("Member", lazy="dynamic")
+ """,
+ """
+ def f(session):
+ for t in session.query(Team).all():
+ print(t.members)
+ """,
+ )
+ assert len(hits) == 1
+
+
+def test_sa_list_comprehension(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(session):
+ return [i.owner.name for i in session.query(Incident).all()]
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].loop is None
+
+
+def test_sa_enumerate(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(session):
+ for idx, i in enumerate(session.query(Incident).all()):
+ print(idx, i.owner.name)
+ """,
+ )
+ assert len(hits) == 1
+
+
+# -- SQLAlchemy negatives ----------------------------------------------------
+
+
[email protected]("mode", ["joined", "selectin", "raise"])
+def test_sa_eager_lazy_mode_no_hit(tmp_path: Path, mode: str):
+ hits = _hits(
+ tmp_path,
+ f"""
+ class Incident:
+ owner = relationship("User", lazy="{mode}")
+ """,
+ """
+ def f(session):
+ for i in session.query(Incident).all():
+ print(i.owner.name)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_options_joinedload_on_producer(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(session):
+ for i in session.query(Incident).options(joinedload(Incident.owner)).all():
+ print(i.owner.name)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_options_selectinload_on_refinement(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(session):
+ qs = session.query(Incident)
+ qs = qs.options(selectinload("owner"))
+ for i in qs.all():
+ print(i.owner.name)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_options_on_statement_behind_scalars(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(session):
+ stmt = select(Incident).options(joinedload(Incident.owner))
+ rows = session.scalars(stmt).all()
+ for i in rows:
+ print(i.owner.name)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_column_named_like_relationship_elsewhere(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ pass
+
+ class Event:
+ owner = relationship("User")
+ """,
+ """
+ def f(session):
+ for e in session.query(Incident).all():
+ print(e.owner)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_with_entities_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(session):
+ for i in session.query(Incident).with_entities(Incident.id).all():
+ print(i.owner)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_rows_as_parameter_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(rows):
+ for i in rows:
+ print(i.owner.name)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_async_def_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ async def f(session):
+ for i in session.query(Incident).all():
+ print(i.owner.name)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_constant_loop_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(session):
+ incidents = session.query(Incident).all()
+ for i in [incidents]:
+ print(i.owner)
+ """,
+ )
+ assert hits == []
+
+
+def test_sa_write_target_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ """
+ def f(session, x):
+ for i in session.query(Incident).all():
+ i.owner = x
+ """,
+ )
+ assert hits == []
+
+
+def test_model_index_name_collision_intersection(tmp_path: Path):
+ """Two different ``Incident`` classes across files keep only the attrs both
+ define with the same ``lazy`` value."""
+ _require_python()
+ a = _write(
+ tmp_path,
+ "a.py",
+ """
+ class Incident:
+ owner = relationship("User")
+ team = relationship("Team")
+ """,
+ )
+ b = _write(
+ tmp_path,
+ "b.py",
+ """
+ class Incident:
+ owner = relationship("User")
+ team = relationship("Team", lazy="joined")
+ """,
+ )
+ index = build_model_index([a, b], lambda p: Path(p).read_bytes())
+ assert set(index.relations["Incident"]) == {"owner"}
+
+
+# -- Django positives ---------------------------------------------------------
+
+
+def test_django_objects_filter(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project)
+ """,
+ """
+ import sqlite3
+
+ def f():
+ for i in Issue.objects.filter(open=True).all():
+ print(i.project.name)
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Issue.project", 'select_related("project")')
+ assert hits[0].loop.magnitude == "grows_with_data"
+
+
+def test_django_reverse_default_related_name(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project)
+
+ class Project(models.Model):
+ pass
+ """,
+ """
+ import sqlite3
+
+ def f():
+ for p in Project.objects.all():
+ print(p.issue_set.count())
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Project.issue_set", 'prefetch_related("issue_set")')
+
+
+def test_django_related_name(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project, related_name="issues")
+
+ class Project(models.Model):
+ pass
+ """,
+ """
+ def f():
+ for p in Project.objects.all():
+ print(p.issues.count())
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Project.issues", 'prefetch_related("issues")')
+
+
+def test_django_m2m_all(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ tags = models.ManyToManyField(Tag)
+ """,
+ """
+ def f():
+ for i in Issue.objects.all():
+ print(i.tags.all())
+ """,
+ )
+ assert len(hits) == 1
+ assert hits[0].path == ("Issue.tags", 'prefetch_related("tags")')
+
+
+def test_django_refinement(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project)
+ """,
+ """
+ def f():
+ qs = Issue.objects.filter(open=True)
+ qs = qs.filter(assigned=True)
+ for i in qs:
+ print(i.project.name)
+ """,
+ )
+ assert len(hits) == 1
+
+
+# -- Django negatives ----------------------------------------------------------
+
+
+def test_django_select_related_no_args(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project)
+ """,
+ """
+ def f():
+ for i in Issue.objects.select_related().all():
+ print(i.project.name)
+ """,
+ )
+ assert hits == []
+
+
+def test_django_select_related_named(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project)
+ """,
+ """
+ def f():
+ for i in Issue.objects.select_related("project"):
+ print(i.project.name)
+ """,
+ )
+ assert hits == []
+
+
+def test_django_prefetch_related_prefetch_object(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ tags = models.ManyToManyField(Tag)
+ """,
+ """
+ def f():
+ for i in Issue.objects.prefetch_related(Prefetch("tags")):
+ print(i.tags.all())
+ """,
+ )
+ assert hits == []
+
+
+def test_django_values_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project)
+ """,
+ """
+ def f():
+ for i in Issue.objects.values("id"):
+ print(i.project)
+ """,
+ )
+ assert hits == []
+
+
+def test_django_fk_id_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project)
+ """,
+ """
+ def f():
+ for i in Issue.objects.all():
+ print(i.project_id)
+ """,
+ )
+ assert hits == []
+
+
+def test_django_related_name_plus_no_reverse(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ # django
+ class Issue(models.Model):
+ project = models.ForeignKey(Project, related_name="+")
+
+ class Project(models.Model):
+ pass
+ """,
+ """
+ def f():
+ for p in Project.objects.all():
+ print(p.issue_set.count())
+ """,
+ )
+ assert hits == []
+
+
+# -- shape --------------------------------------------------------------------
+
+
+def test_one_hit_per_loop_with_two_lazy_accesses(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Incident:
+ owner = relationship("User")
+ team = relationship("Team")
+ """,
+ """
+ def f(session):
+ for i in session.query(Incident).all():
+ print(i.owner.name, i.team.name)
+ """,
+ )
+ assert len(hits) == 1
+
+
+# -- model index: byte prefilter ----------------------------------------------
+
+
+def test_model_index_only_built_from_prefiltered_files(tmp_path: Path):
+ _require_python()
+ with_orm = _write(
+ tmp_path,
+ "with_orm.py",
+ """
+ class Incident:
+ owner = relationship("User")
+ """,
+ )
+ without_orm = _write(
+ tmp_path,
+ "without_orm.py",
+ """
+ class Plain:
+ name = "x"
+ """,
+ )
+ index = build_model_index([with_orm, without_orm], lambda p: Path(p).read_bytes())
+ assert "Incident" in index.models
+ assert "Plain" not in index.models
+
+
+def test_django_manager_write_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ from django.db import models
+
+ class Tag(models.Model):
+ pass
+
+ class Rule(models.Model):
+ tags = models.ManyToManyField(Tag)
+ """,
+ """
+ def f(tag):
+ for r in Rule.objects.filter(active=True):
+ r.tags.add(tag)
+ for r in Rule.objects.all():
+ r.tags.all().update(name="x")
+ """,
+ )
+ assert hits == []
+
+
+# -- review fixes --------------------------------------------------------------
+
+
+def test_sa_option_from_a_helper_hides_the_load(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Order:
+ items = relationship("Item")
+ """,
+ """
+ def f(session):
+ for o in session.query(Order).options(eager_items()).all():
+ print(o.items)
+ for o in session.query(Order).options(load_only("id")).all():
+ print(o.items)
+ """,
+ )
+ assert [h.line for h in hits] == [6]
+
+
+def test_django_splat_select_related_hides_the_load(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ from django.db import models
+
+ class Order(models.Model):
+ customer = models.ForeignKey("Customer", on_delete=models.CASCADE)
+ """,
+ """
+ def f(fields):
+ for o in Order.objects.select_related(*fields):
+ print(o.customer)
+ """,
+ )
+ assert hits == []
+
+
+def test_django_eager_custom_manager_is_not_typed(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ from django.db import models
+
+ class OrderManager(models.Manager):
+ def get_queryset(self):
+ return super().get_queryset().select_related("customer")
+
+ class Order(models.Model):
+ customer = models.ForeignKey("Customer", on_delete=models.CASCADE)
+ objects = OrderManager()
+
+ class RushOrder(Order):
+ pass
+
+ class Invoice(models.Model):
+ customer = models.ForeignKey("Customer", on_delete=models.CASCADE)
+ objects = PlainQuerySet.as_manager()
+ """,
+ """
+ def f():
+ for o in Order.objects.all():
+ print(o.customer)
+ for o in RushOrder.objects.all():
+ print(o.customer)
+ for i in Invoice.objects.all():
+ print(i.customer)
+ """,
+ )
+ assert [h.path[0] for h in hits] == ["Invoice.customer"]
+
+
+def test_model_index_collision_across_orms_drops_the_attr(tmp_path: Path):
+ _require_python()
+ a = _write(tmp_path, "a.py", 'class Item:\n variants = relationship("Variant")\n')
+ b = _write(
+ tmp_path,
+ "b.py",
+ 'from django.db import models\n\nclass Item(models.Model):\n'
+ ' variants = models.ManyToManyField("Variant")\n',
+ )
+ index = build_model_index([a, b], lambda p: Path(p).read_bytes())
+ assert index.relations["Item"] == {}
+
+
+def test_loop_target_rebound_by_inner_for_no_hit(tmp_path: Path):
+ hits = _hits(
+ tmp_path,
+ """
+ class Order:
+ items = relationship("Item")
+ parts = relationship("Part")
+ """,
+ """
+ def f(session):
+ for o in session.query(Order).all():
+ for o in o.parts:
+ pass
+ print(o.items)
+ """,
+ )
+ assert hits == []
+
+
+def test_fix_is_advisory_and_not_batchable():
+ from repowise.core.analysis.health.perf.actionability import BATCHABLE_MARKERS, assess_fix
+
+ fix = assess_fix(_KIND, (_KIND,), "db", [{}], cross_function=False).fix
+ assert (fix.strategy, fix.safety) == ("eager_load_relationship", "advisory")
+ assert _KIND not in BATCHABLE_MARKERS
diff --git a/tests/unit/persistence/test_performance_materialization.py b/tests/unit/persistence/test_performance_materialization.py
index 774b87df4..76a6482c1 100644
--- a/tests/unit/persistence/test_performance_materialization.py
+++ b/tests/unit/persistence/test_performance_materialization.py
@@ -370,3 +370,22 @@ def test_the_migration_upgrades_and_rolls_back(tmp_path: Path) -> None:
assert not {"performance_opportunities", "performance_summaries"} & _tables(db_path)
assert not {"public_id", "opportunity_id"} & _columns(db_path, "health_findings")
assert "opportunity_id" not in _columns(db_path, "refactoring_suggestions")
+
+
+def test_a_non_leading_marker_never_leads_the_summary():
+ from types import SimpleNamespace
+
+ from repowise.core.persistence.crud.analysis.performance import _summary_payload
+
+ def _opp(oid: str, marker: str):
+ return SimpleNamespace(
+ opportunity_id=oid, actionability_state="advisory", biomarker_type=marker,
+ boundary_kind="db", execution_context="production", intervention_symbol=None,
+ terminal_sink=None, evidence=[{"file_path": "a.py"}], observations_total=1,
+ affected_call_sites_total=1, affected_files_total=1, why_ranked=[],
+ prerequisites=(), actionability_reason="",
+ )
+
+ ranked = [_opp("lazy", "lazy_load_in_loop"), _opp("io", "io_in_loop")]
+ assert _summary_payload(ranked, {})["lead"]["opportunity_id"] == "io"
+ assert _summary_payload(ranked[:1], {})["lead"] is None