Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(visual-review): stop loading every snapshot to read a run (#104445)

Julian Bezb4e22ad5e680
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index d410eb42abf9..de79fec78ef2 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -222,7 +222,9 @@ def _compute_unresolved(run) -> int:
return 0
-def _to_run(run, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = None) -> contracts.Run:
+def _to_run(
+ run, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = None, unresolved: int | None = None
+) -> contracts.Run:
approved_by = (user_basic_infos or {}).get(run.approved_by_id) if run.approved_by_id else None
return contracts.Run(
id=run.id,
@@ -240,7 +242,7 @@ def _to_run(run, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = N
new=run.new_count,
removed=run.removed_count,
unchanged=run.total_snapshots - run.changed_count - run.new_count - run.removed_count,
- unresolved=_compute_unresolved(run),
+ unresolved=_compute_unresolved(run) if unresolved is None else unresolved,
tolerated_matched=run.tolerated_match_count,
),
error_message=run.error_message or None,
@@ -393,14 +395,11 @@ def get_toleration_pileups(
min_intentional=min_tolerations,
min_automatic=min_automatic_tolerations,
)
- matching = sorted(
- (
- (key, counts)
- for key, counts in pileups.items()
- if (include_quarantined or key not in quarantined_keys) and (run_type is None or key.run_type == run_type)
- ),
- key=lambda item: (-item[1].intentional, -item[1].automatic, item[0].run_type, item[0].identifier),
- )
+ matching = [
+ (key, counts)
+ for key, counts in pileups
+ if (include_quarantined or key not in quarantined_keys) and (run_type is None or key.run_type == run_type)
+ ]
return contracts.TolerationPileups(
entries=[
contracts.TolerationPileupEntry(
@@ -595,10 +594,16 @@ def add_snapshots(input: contracts.AddSnapshotsInput, run_id: UUID, team_id: int
def get_run(run_id: UUID, team_id: int | None = None) -> contracts.Run:
- run = run_queries.get_run_with_snapshots(run_id, team_id=team_id)
+ run = run_queries.get_run(run_id, team_id=team_id)
user_ids = {run.approved_by_id} if run.approved_by_id else set()
user_basic_infos = _fetch_user_basic_infos(user_ids)
- return _to_run(run, user_basic_infos)
+ return _to_run(run, user_basic_infos, unresolved=gating.count_unresolved(run))
+
+
+def get_run_scope(run_id: UUID, team_id: int) -> contracts.RunScope:
+ """The repo and run type a run belongs to, for endpoints that only need to know where to look."""
+ run = run_queries.get_run(run_id, team_id=team_id)
+ return contracts.RunScope(repo_id=run.repo_id, run_type=run.run_type)
def get_run_snapshots(
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index b1e0709a23b2..04d4d054f1b3 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -511,8 +511,9 @@ class Repo:
# Hard cap on entries returned by the baselines overview endpoint. Above this,
# truncate (newest by run completion) and surface `truncated: True` so the UI
# can flag it. The whole flow is sized for this — the FE filters/sorts client-
-# side and ships ~600 KB gzipped at the cap.
-BASELINE_OVERVIEW_MAX_ENTRIES = 5000
+# side and ships ~900 KB gzipped at the cap. Sized above the largest repo's
+# universe, so the cap is a backstop rather than a filter that hides stories.
+BASELINE_OVERVIEW_MAX_ENTRIES = 7500
# Number of most-recent default-branch completed runs that feed the
# `recent_drift_avg` smoothing window. Bounded by run count rather than time
@@ -760,6 +761,14 @@ class FlakinessOverview:
generated_at: datetime
+@dataclass(frozen=True)
+class RunScope:
+ """Where a run's snapshots live: its repo and run type."""
+
+ repo_id: UUID
+ run_type: str
+
+
@dataclass(frozen=True)
class TolerationPileupEntry:
"""One snapshot identity that keeps getting tolerated."""
diff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.py
index c1ccedf0c8ff..edbac7879aa8 100644
--- a/products/visual_review/backend/logic/debt_digest.py
+++ b/products/visual_review/backend/logic/debt_digest.py
@@ -424,9 +424,7 @@ def collect_debt(repo: Repo, now: datetime) -> RepoDebt:
quarantined_keys = quarantine.active_quarantine_keys(repo.id, now=now)
piled_up = {
key: counts.intentional
- for key, counts in toleration.list_toleration_pileups(
- repo.id, now=now, newest_run_by_type=newest_run_by_type
- ).items()
+ for key, counts in toleration.list_toleration_pileups(repo.id, now=now, newest_run_by_type=newest_run_by_type)
# Any live quarantine, expiring or not, already says somebody knows the snapshot is
# unreliable, so asking them about the tolerations underneath it is a second reminder about
# one problem.
@@ -456,10 +454,8 @@ def collect_debt(repo: Repo, now: datetime) -> RepoDebt:
line=_pileup_line(repo, key.run_type, key.identifier, count),
facts=_pileup_facts(count),
)
- # Biggest pile first, then by identity so a tie reads the same way every morning.
- for key, count in sorted(
- piled_up.items(), key=lambda item: (-item[1], item[0].run_type, item[0].identifier)
- )
+ # Already in pile order: `list_toleration_pileups` sorts, and the dict keeps it.
+ for key, count in piled_up.items()
],
)
diff --git a/products/visual_review/backend/logic/gating.py b/products/visual_review/backend/logic/gating.py
index b09af384e87c..b4b92c374057 100644
--- a/products/visual_review/backend/logic/gating.py
+++ b/products/visual_review/backend/logic/gating.py
@@ -44,6 +44,25 @@ def _is_unresolved(s: RunSnapshot) -> bool:
return True
+def count_unresolved(run: Run) -> int:
+ """How many of a run's snapshots `_is_unresolved` flags, counted in SQL.
+
+ The run detail read needs only this number, and loading every snapshot to count a handful
+ costs seconds on a large run. Observe runs are never approvable, so nothing in them is
+ unresolved. The predicate must stay identical to `_is_unresolved`; a test pins the two
+ together.
+ """
+ if run.purpose == RunPurpose.OBSERVE:
+ return 0
+ return (
+ RunSnapshot.objects.filter(run_id=run.id)
+ .exclude(result=SnapshotResult.UNCHANGED)
+ .exclude(is_quarantined=True)
+ .exclude(review_state__in=(ReviewState.TOLERATED, ReviewState.APPROVED))
+ .count()
+ )
+
+
def _changes_summary(run: Run) -> str:
"""Change summary from the run's denormalized (quarantine-excluded) counts."""
return comment_markdown._format_change_counts(run.changed_count, run.new_count, run.removed_count)
diff --git a/products/visual_review/backend/logic/toleration.py b/products/visual_review/backend/logic/toleration.py
index bcd5db5f4c37..07fd3b29ebe8 100644
--- a/products/visual_review/backend/logic/toleration.py
+++ b/products/visual_review/backend/logic/toleration.py
@@ -199,21 +199,27 @@ def list_toleration_pileups(
min_intentional: int = VARIANT_PILEUP_MIN,
min_automatic: int | None = None,
newest_run_by_type: Mapping[str, Run] | None = None,
-) -> dict[SnapshotKey, TolerationCounts]:
- """Snapshot identities that keep getting tolerated, whether quarantined or not.
+) -> list[tuple[SnapshotKey, TolerationCounts]]:
+ """Snapshot identities that keep getting tolerated, whether quarantined or not, biggest manual
+ pile first, then by identity so a tie reads the same way every time.
An identity qualifies with `min_intentional` or more tolerations by a person or agent in the
window, or, when `min_automatic` is set, with that many automatic ones. The defaults are the
debt digest's rule, and the digest and the pile-ups endpoint share this function so the
reminder and what an agent reads cannot drift apart.
"""
- return {
- key: counts
- for key, counts in count_recent_tolerations(
- repo_id, since=now - timedelta(days=window_days), newest_run_by_type=newest_run_by_type
- ).items()
- if counts.intentional >= min_intentional or (min_automatic is not None and counts.automatic >= min_automatic)
- }
+ counts_by_key = count_recent_tolerations(
+ repo_id, since=now - timedelta(days=window_days), newest_run_by_type=newest_run_by_type
+ )
+ return sorted(
+ (
+ (key, counts)
+ for key, counts in counts_by_key.items()
+ if counts.intentional >= min_intentional
+ or (min_automatic is not None and counts.automatic >= min_automatic)
+ ),
+ key=lambda item: (-item[1].intentional, -item[1].automatic, item[0].run_type, item[0].identifier),
+ )
def _current_baseline_hashes(
diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.py
index 4ab227d7489b..65f7fd19d9e3 100644
--- a/products/visual_review/backend/presentation/views.py
+++ b/products/visual_review/backend/presentation/views.py
@@ -679,10 +679,10 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
if not identifier:
return Response({"detail": _MISSING_IDENTIFIER_DETAIL}, status=status.HTTP_400_BAD_REQUEST)
try:
- run = api.get_run(_parse_uuid(pk), team_id=self.team_id)
+ scope = api.get_run_scope(_parse_uuid(pk), team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
- entries = api.get_tolerated_hashes(run.repo_id, identifier)
+ entries = api.get_tolerated_hashes(scope.repo_id, identifier)
page = self.paginate_queryset(entries)
if page is not None:
return self.get_paginated_response(ToleratedHashEntrySerializer(instance=page, many=True).data)
@@ -720,11 +720,11 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response({"detail": _MISSING_IDENTIFIER_DETAIL}, status=status.HTTP_400_BAD_REQUEST)
try:
- run = api.get_run(_parse_uuid(pk), team_id=self.team_id)
+ scope = api.get_run_scope(_parse_uuid(pk), team_id=self.team_id)
except api.RunNotFoundError:
return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)
- history = api.get_snapshot_history(run.repo_id, identifier, run.run_type)
+ history = api.get_snapshot_history(scope.repo_id, identifier, scope.run_type)
page = self.paginate_queryset(history)
if page is not None:
return self.get_paginated_response(SnapshotHistoryEntrySerializer(instance=page, many=True).data)
diff --git a/products/visual_review/backend/tests/test_baselines.py b/products/visual_review/backend/tests/test_baselines.py
index 340223164372..e23d19a591f5 100644
--- a/products/visual_review/backend/tests/test_baselines.py
+++ b/products/visual_review/backend/tests/test_baselines.py
@@ -555,5 +555,5 @@ class TestBaselinesOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
def test_truncation_constant_is_a_safe_default(self):
# Sanity guard — if someone bumps the cap without updating clients, this
- # test reminds them. ~5000 fits the FE budget (≈600 KB gzipped).
+ # test reminds them. ~7500 fits the FE budget (≈900 KB gzipped).
assert 1000 <= BASELINE_OVERVIEW_MAX_ENTRIES <= 10000
diff --git a/products/visual_review/backend/tests/test_gating.py b/products/visual_review/backend/tests/test_gating.py
index 4da68fcea246..38ccda4ec7f0 100644
--- a/products/visual_review/backend/tests/test_gating.py
+++ b/products/visual_review/backend/tests/test_gating.py
@@ -139,6 +139,8 @@ class TestGatingInvariants:
recompute_result = runs.recompute_run(run.id, team_id=self.team.id)
gate_passes = recompute_result["unresolved"] == 0
assert gate_passes is expected_gate_passes
+ # The detail read counts in SQL; recompute applies `_is_unresolved` in Python.
+ assert api.get_run(run.id, team_id=self.team.id).summary.unresolved == recompute_result["unresolved"]
@parameterized.expand(GATE_CASES)
def test_raw_counts_reflect_classifier_truth(self, _name, result, action, _expected_gate, expected_changed_count):
diff --git a/products/visual_review/frontend/generated/api.ts b/products/visual_review/frontend/generated/api.ts
index 7a4bfa4e97b8..100208c21c29 100644
--- a/products/visual_review/frontend/generated/api.ts
+++ b/products/visual_review/frontend/generated/api.ts
@@ -142,7 +142,7 @@ export const getVisualReviewReposBaselinesRetrieveUrl = (projectId: string, id:
}
/**
- * Snapshots overview for a repo: every identifier with a current baseline (latest non-superseded master/main run per run_type), plus tolerate counts, active quarantine state, and a 30-day stability sparkline. Capped at 5000 entries — sets `truncated` and returns the most recently active when exceeded. Filtering / faceting / search are all done client-side; this endpoint takes no filter query params.
+ * Snapshots overview for a repo: every identifier with a current baseline (latest non-superseded master/main run per run_type), plus tolerate counts, active quarantine state, and a 30-day stability sparkline. Capped at 7500 entries — sets `truncated` and returns the most recently active when exceeded. Filtering / faceting / search are all done client-side; this endpoint takes no filter query params.
*/
export const visualReviewReposBaselinesRetrieve = async (
projectId: string,