: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(visual-review): add a flakiness tab (#88228)
Julian Bez38f8b8ceec15
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex be9cb7dac0b5..e1114efdf549 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8156,6 +8156,18 @@ snapshots:hash: v1.k794b7964.2be1760894da7958ef5f9376996ae6262c5ab191ec957c533ae74ba4c742aead.dQcZiMIpSCQDJxp76ersiDmELB8efODSyJoZQCWpb8wscenes-app-user-research-topics--topics-list--light:hash: v1.k794b7964.f1a2f79a98d9a9104868b551164cd1ff8ee03a892af075c495ef6e41229d098e.bFA04K1QUtLmjYG7rmQcIBruv-GuGqTqFlShoEjNfco+ scenes-app-visual-review-flakiness--could-not-load--dark:+ hash: v1.k794b7964.b43407f2c87f5c266a5f384a6fed543d5c19c0043efbb6ca7ebdac28fc485988.mxKGi-lX3FsEItU0GYVf5o_UU7g7wqPspZ0D4i9hrFU+ scenes-app-visual-review-flakiness--could-not-load--light:+ hash: v1.k794b7964.f773435b48f3623bd8c85edcd3109a75ce6f0348df0b784c5fac6d3a119493c6.TJgijm2sZZLzigFYD76PiIT3vKZn7F3ouJIaEEr_rYc+ scenes-app-visual-review-flakiness--nothing-to-show--dark:+ hash: v1.k794b7964.01ab3c1ddc7ab608b0e59904df01d7ad4b486c9c6964493f09a3d94f83cb7f9b.bA3TJHPeVdZfXaZSB1pOID2-CL9waZpurwH-G4EbmEE+ scenes-app-visual-review-flakiness--nothing-to-show--light:+ hash: v1.k794b7964.f2900a9c11bbaebfc6d4ad47e9ddc1e7d91266a90e9aec1bc3ee19f390cfc612.6pl1ZY85krwytaoXUIqtLgZAMoqA7W3GDL-YTFPoWac+ scenes-app-visual-review-flakiness--unstable--dark:+ hash: v1.k794b7964.e1aeebe2b7ec9a477fddae66cb6d99b81f2a60430b02048da4901a0fae987db5.EyHWaHAIJNLzkHFa4RIs-dnRxp-5vqw0nfj-1OG3fm4+ scenes-app-visual-review-flakiness--unstable--light:+ hash: v1.k794b7964.5cf71c0f96f1e7a0eef245e86ed8775a1da1ca79437ac06ad1d84a47b83f29a7.C8wPpmzroClyIturGgvDPkMz_pug_a0zYBJEig70wuoscenes-app-visual-review-run--ready-to-finalize--dark:hash: v1.k794b7964.f3a36b59f01f60089f80ec544c60c8c396a032af9f233293c2b7a8ef0551ac9d.sbAIU7T7p95O1GkL_UFuwnwKz7-fT7_NgeFLdTGW5rYscenes-app-visual-review-run--ready-to-finalize--light:diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 9a9c52f465d3..576bfd31680d 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -155,6 +155,7 @@ export const productScenes: Record<string, () => Promise<any>> = {import('../../products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene'),VisualReviewSnapshotOverview: () =>import('../../products/visual_review/frontend/scenes/VisualReviewSnapshotOverviewScene'),+ VisualReviewFlakiness: () => import('../../products/visual_review/frontend/scenes/VisualReviewFlakinessScene'),Heatmaps: () => import('../../products/web_analytics/frontend/heatmaps/scenes/heatmaps/HeatmapsScene'),Heatmap: () => import('../../products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapScene'),HeatmapNew: () => import('../../products/web_analytics/frontend/heatmaps/scenes/heatmap/HeatmapNewScene'),diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex faa5f7a16caa..72ac586ae451 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -252,6 +252,7 @@ export const productRoutes: Record<string, [string, string]> = {'/visual_review/runs/:runId': ['VisualReviewRun', 'visualReviewRun'],'/visual_review/repos/:repoId/runs': ['VisualReviewRuns', 'visualReviewRepoRuns'],'/visual_review/repos/:repoId/snapshots': ['VisualReviewSnapshotOverview', 'visualReviewSnapshotOverview'],+ '/visual_review/repos/:repoId/flakiness': ['VisualReviewFlakiness', 'visualReviewFlakiness'],'/visual_review/repos/:repoId/:runType/snapshots/:identifier': ['VisualReviewSnapshotHistory','visualReviewSnapshotHistory',@@ -957,6 +958,7 @@ export const productConfiguration: Record<string, any> = {iconType: 'visual_review',},VisualReviewSnapshotOverview: { name: 'Snapshots', projectBased: true, iconType: 'visual_review' },+ VisualReviewFlakiness: { name: 'Flakiness', projectBased: true, iconType: 'visual_review' },Heatmaps: {name: 'Heatmaps',projectBased: true,@@ -1498,6 +1500,7 @@ export const productUrls = {visualReviewRun: (runId: string): string => `/visual_review/runs/${runId}`,visualReviewRepoRuns: (repoId: string): string => `/visual_review/repos/${repoId}/runs`,visualReviewSnapshotOverview: (repoId: string): string => `/visual_review/repos/${repoId}/snapshots`,+ visualReviewFlakiness: (repoId: string): string => `/visual_review/repos/${repoId}/flakiness`,visualReviewSnapshotHistory: (repoId: string, runType: string, identifier: string): string =>`/visual_review/repos/${repoId}/${encodeURIComponent(runType)}/snapshots/${encodeURIComponent(identifier)}`,webAnalytics: (): string => `/web`,@@ -2603,6 +2606,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['VisualReviewSettings','VisualReviewSnapshotHistory','VisualReviewSnapshotOverview',+ 'VisualReviewFlakiness',],},{diff --git a/products/visual_review/README.md b/products/visual_review/README.mdindex 25c91845c72e..faadb1a0a6bc 100644--- a/products/visual_review/README.md+++ b/products/visual_review/README.md@@ -133,12 +133,21 @@ Developers can also manually tolerate a snapshot from the UI.**Quarantine** — known-flaky identifiers can be quarantined per repo and run type.Quarantined snapshots are still captured and diffed but excluded from gating.+**Flakiness tab** — surfaces the tolerated-hash data, which is otherwise written and never read.+A snapshot is scored on how many alternate hashes the classifier can still match for its current baseline, so the score resets when the baseline moves.+`unstable` means it rendered one of those variants within the last week, `settled` means it carries variants but has not rendered one recently, and `clean` means it has none and is only listed because it is quarantined.+Open quarantines appear in the same list, with extend and lift on the row, and `needs a decision` flags one that has run out, is about to, or now covers a snapshot that stopped producing variants.++Recency comes from the runs that rendered a variant, not from when the variant was first recorded.+A snapshot can keep cycling through variants it already recorded without ever adding a new one, and that case still fails to render the same way twice.+**Known gaps:**- Frontend error toast swallows structured error codes (`sha_mismatch`, `stale_run`) instead of showing tailored messages**Not yet built:**+- Auto-release of a quarantine whose snapshot has gone clean (the flakiness tab flags it, a human still decides)- Retention / cleanup of old runs and artifacts- Server-side thumbnailing for the snapshot strip- Webhook-driven run creation (currently CLI-initiated only)diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex 30a0b6925945..70fb0db417dc 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -16,6 +16,7 @@ Do NOT:"""from dataclasses import replace+from datetime import datetimefrom uuid import UUIDfrom django.contrib.auth import get_user_model@@ -30,6 +31,7 @@ from ..logic import (baseline_overview,baselines,errors,+ flakiness,gating,history,quarantine,@@ -40,7 +42,7 @@ from ..logic import (toleration,)from . import contracts-from .enums import RunPurpose+from .enums import FlakinessState, RunPurposeUser = get_user_model()@@ -255,9 +257,12 @@ def update_repo(input: contracts.UpdateRepoInput, team_id: int) -> contracts.Repreturn _to_repo(repo)-def get_thumbnail_hash_for_identifier(repo_id: UUID, identifier: str) -> str | None:- """Resolve a snapshot identifier to the content hash of its thumbnail, if any."""- return thumbnails.get_thumbnail_hash_for_identifier(repo_id, identifier)+def get_thumbnail_hash_for_identifier(repo_id: UUID, identifier: str, run_type: str | None = None) -> str | None:+ """Resolve a snapshot identifier to the content hash of its thumbnail, if any.++ `run_type` narrows to one, for callers that list several side by side.+ """+ return thumbnails.get_thumbnail_hash_for_identifier(repo_id, identifier, run_type)def read_thumbnail_bytes(repo_id: UUID, content_hash: str) -> bytes | None:@@ -327,6 +332,90 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:)+def get_flakiness_overview(repo_id: UUID) -> contracts.FlakinessOverview:+ """Snapshot identities carrying rendering instability or an open quarantine.++ Backs the flakiness page. See `flakiness.get_flakiness_overview` for the+ scoping rule and query shape.+ """+ raw = flakiness.get_flakiness_overview(repo_id)++ quarantine_user_ids = {+ row.quarantine.created_by_id for row in raw.rows if row.quarantine and row.quarantine.created_by_id+ }+ quarantine_user_infos = _fetch_user_basic_infos(quarantine_user_ids)++ entries: list[contracts.FlakinessEntry] = []+ for row in raw.rows:+ snapshot = raw.snapshots_by_key.get(flakiness.snapshot_key(row))+ artifact = snapshot.current_artifact if snapshot is not None else None+ thumbnail = artifact.thumbnail if artifact is not None else None+ metadata = (snapshot.metadata or {}) if snapshot is not None else {}+ entries.append(+ contracts.FlakinessEntry(+ identifier=row.identifier,+ run_type=row.run_type,+ browser=metadata.get("browser") if isinstance(metadata, dict) else None,+ thumbnail_hash=thumbnail.content_hash if thumbnail is not None else None,+ width=artifact.width if artifact is not None else None,+ height=artifact.height if artifact is not None else None,+ variant_count=row.variant_count,+ last_flaked_at=row.last_flaked_at,+ avg_diff_percentage=row.avg_diff_percentage,+ baseline_age_days=_days_since(row.baseline_moved_at, raw.generated_at),+ daily_variant_counts=row.daily_counts,+ baseline_moved_day_index=_baseline_moved_day_index(row.baseline_moved_at, raw.generated_at),+ flakiness_state=_flakiness_state(row.is_unstable, row.variant_count),+ is_quarantined=row.quarantine is not None,+ needs_decision=row.needs_decision,+ quarantine=(+ _to_baseline_quarantine_summary(row.quarantine, quarantine_user_infos)+ if row.quarantine is not None+ else None+ ),+ )+ )++ totals = contracts.FlakinessTotals(+ listed=len(entries),+ tracked=raw.tracked_total,+ unstable=raw.totals_unstable,+ settled=raw.totals_settled,+ quarantined=raw.totals_quarantined,+ needs_decision=raw.totals_needs_decision,+ by_run_type=raw.by_run_type,+ )++ return contracts.FlakinessOverview(+ entries=entries,+ totals=totals,+ truncated=raw.truncated,+ generated_at=raw.generated_at,+ )+++def _flakiness_state(is_unstable: bool, variant_count: int) -> str:+ if is_unstable:+ return FlakinessState.UNSTABLE+ return FlakinessState.SETTLED if variant_count > 0 else FlakinessState.CLEAN+++def _days_since(moment: datetime | None, now: datetime) -> int | None:+ return None if moment is None else max((now - moment).days, 0)+++def _baseline_moved_day_index(moved_at: datetime | None, now: datetime) -> int | None:+ """Position of the baseline move inside the activity strip.++ None when the baseline moved before the strip window opened, which is the+ common case, so the frontend draws no divider.+ """+ days_ago = _days_since(moved_at, now)+ if days_ago is None or days_ago >= contracts.FLAKINESS_STRIP_DAYS:+ return None+ return contracts.FLAKINESS_STRIP_DAYS - 1 - days_ago++# --- Run API ---diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex 06024cbe41bd..f891f4dbd8f2 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -501,3 +501,97 @@ class BaselineOverview:totals: BaselineTotalstruncated: boolgenerated_at: datetime+++# How recently a snapshot must have rendered a variant to count as unstable+# rather than settled. A Storybook run lands many times a day on an active+# repo, so a week is wide enough that a genuinely flaky snapshot cannot stay+# quiet through it by chance.+FLAKINESS_RECENT_DAYS = 7++# Width of the per-day activity strip on each row. Fixed rather than following+# the baseline era, so every row shares one time axis and rows stay comparable.+FLAKINESS_STRIP_DAYS = 30++# A quarantine this close to running out needs a human to extend it or let it+# lapse, so it counts toward `needs_decision`.+FLAKINESS_EXPIRY_SOON_DAYS = 7++# Safety cap on rows returned by the flakiness endpoint. The population is+# already narrow (only identifiers carrying variants or a quarantine), so this+# is a backstop against a repo whose diff threshold is misconfigured and+# tolerates everything, not an expected limit.+FLAKINESS_MAX_ENTRIES = 2000+++@dataclass(frozen=True)+class FlakinessEntry:+ """How unstable one snapshot identity is, and what is being done about it.++ One row per `(run_type, identifier)`. Only identifiers that carry at least+ one live variant against their current baseline, or an active quarantine,+ get an entry — everything else has nothing to report.+ """++ identifier: str+ run_type: str+ browser: str | None+ thumbnail_hash: str | None+ width: int | None+ height: int | None+ # Distinct alternate hashes the classifier can still match for this+ # snapshot's current baseline. Reads as "how many different images this+ # snapshot is currently allowed to produce".+ variant_count: int+ # Last default-branch run that rendered one of those variants. Not when a+ # variant was first recorded: a snapshot can cycle through variants it+ # already recorded forever without adding a new one, and that is the worst+ # case this page exists to find. None when no run has matched one.+ last_flaked_at: datetime | None+ # Mean pixel-diff fraction across those variants. Separates sub-pixel+ # noise from a small but real rendering change.+ avg_diff_percentage: float | None+ # Days since the first default-branch run that compared against the+ # current baseline, which is when that baseline took effect.+ baseline_age_days: int | None+ # Variants recorded per day over the last `FLAKINESS_STRIP_DAYS`, oldest+ # first. Always that length so the frontend can render a fixed axis.+ daily_variant_counts: list[int]+ # Index into `daily_variant_counts` where the baseline moved. None when it+ # moved before the window opened, which is the common case.+ baseline_moved_day_index: int | None+ # One of `FlakinessState`. Named with a prefix because a field called+ # `state` collides with other products' enums in the OpenAPI schema.+ flakiness_state: str+ is_quarantined: bool+ # True when an active quarantine has run out, is about to, or covers a+ # snapshot that has gone clean. All three mean a human has to choose+ # between extending it and lifting it.+ needs_decision: bool+ quarantine: BaselineQuarantineSummary | None = None+++@dataclass(frozen=True)+class FlakinessTotals:+ """Counts across the full population, independent of any client-side filter."""++ # Identifiers with an entry in `entries`.+ listed: int+ # Identifiers with a current baseline, listed or not. The denominator that+ # tells a reader how much of the repo is quiet.+ tracked: int+ unstable: int+ settled: int+ quarantined: int+ needs_decision: int+ by_run_type: dict[str, int]+++@dataclass(frozen=True)+class FlakinessOverview:+ """Result of the flakiness overview endpoint."""++ entries: list[FlakinessEntry]+ totals: FlakinessTotals+ truncated: bool+ generated_at: datetimediff --git a/products/visual_review/backend/facade/enums.py b/products/visual_review/backend/facade/enums.pyindex 907e8e127f49..7705329f2fbc 100644--- a/products/visual_review/backend/facade/enums.py+++ b/products/visual_review/backend/facade/enums.py@@ -86,6 +86,18 @@ class ChangeKind(StrEnum):STRUCTURAL = "structural" # SSIM caught a perceptual change; pixel diff was below threshold+class FlakinessState(StrEnum):+ """How unstable a snapshot's rendering is against its current baseline.++ Derived, not stored. A snapshot is scored on the alternate hashes the+ classifier can still match, so the score resets when the baseline moves.+ """++ UNSTABLE = "unstable" # Rendered a variant inside the recency window+ SETTLED = "settled" # Has variants against this baseline, but rendered none recently+ CLEAN = "clean" # No live variants against the current baseline++class ActorType(StrEnum):"""Who performed an action — human user, AI agent, or automated system."""diff --git a/products/visual_review/backend/logic/flakiness.py b/products/visual_review/backend/logic/flakiness.pynew file mode 100644index 000000000000..50b7a44dcd1b--- /dev/null+++ b/products/visual_review/backend/logic/flakiness.py@@ -0,0 +1,573 @@+"""The flakiness aggregate that backs the flakiness scene.++Scores each snapshot identity on the alternate hashes the classifier can still+match for it. See `get_flakiness_overview` for why that is scoped to the+current baseline rather than to a rolling time window.+"""++from __future__ import annotations++from collections import Counter, defaultdict+from datetime import UTC, date, datetime, timedelta+from uuid import UUID++from django.db.models import Avg, Count, Max, Q+from django.db.models.functions import TruncDate+from django.utils import timezone++from posthog.dataclasses import frozen++from ..facade.contracts import (+ FLAKINESS_EXPIRY_SOON_DAYS,+ FLAKINESS_MAX_ENTRIES,+ FLAKINESS_RECENT_DAYS,+ FLAKINESS_STRIP_DAYS,+)+from ..facade.enums import ClassificationReason, RunStatus, SnapshotResult, ToleratedReason+from ..models import QuarantinedIdentifier, Run, RunSnapshot, ToleratedHash+from . import run_queries+++@frozen+class _SnapshotKey:+ """One snapshot identity. The same identifier under two run types is two."""++ run_type: str+ identifier: str+++@frozen+class _FlakeKey:+ """One snapshot identity's activity during one baseline, per run type.++ Matching ignores run type, because the classifier looks a tolerated row up+ by identifier and hashes alone. A row on this page does not: a recent+ Storybook flake says nothing about the Playwright row.+ """++ run_type: str+ identifier: str+ baseline_hash: str+++@frozen+class _VariantKey:+ """One snapshot's variants, scoped to the baseline they were recorded against.++ No run type: `ToleratedHash` does not carry one, and the classifier looks+ rows up by identifier and baseline hash alone.+ """++ identifier: str+ baseline_hash: str+++def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:+ """Snapshot identities that carry rendering instability or a quarantine.++ Scope, and why it is not a rolling window:+ A `ToleratedHash` row is stored against a specific `baseline_hash`, and+ the classifier only matches a row whose baseline hash is still the+ baseline (see `SnapshotClassifier.classify_remaining`). So the moment a+ snapshot genuinely changes and its baseline moves, every variant recorded+ before that becomes unreachable forever. Counting those would report+ churn from a version of the snapshot that no longer exists. Scoping to+ the current baseline instead gives a window that resets exactly when the+ snapshot changed, and it is served by the existing `tolerated_lookup`+ index on `(repo, identifier, baseline_hash)` without a new one.++ Baseline scoping alone is not enough. A snapshot that someone made+ deterministic without moving its baseline keeps its variant count, so+ `last_flaked_at` decides `unstable` against `settled`. That timestamp+ comes from the runs that matched a variant, not from when the variant was+ first recorded, because a snapshot can cycle through variants it already+ recorded without ever minting a new row.++ Population:+ Only identifiers with at least one live variant against their current+ baseline, or an active quarantine. Everything else has nothing to show,+ which keeps this an order of magnitude smaller than the baselines+ universe and removes any need to paginate.++ Query shape:+ - 1 query for the universe runs (one row per run_type, indexed)+ - 1 values-only query for the current baseline hash per identifier+ - 1 grouped query for variant count and mean diff+ - 1 grouped query for the per-day strip, bounded to the strip window+ - 1 query for active quarantines+ - 1 grouped query for when each baseline era started and last flaked,+ scanned only for identifiers that can produce a row+ - 1 query to hydrate thumbnails, for listed rows only+ """+ now = timezone.now()+ today = now.date()++ live = Q(expires_at__isnull=True) | Q(expires_at__gt=now)++ # Every active quarantine in the repo, not only the ones whose snapshot has+ # a baseline. Quarantining does not require one, and the empty state+ # promises that quarantining alone puts a snapshot on this page. The set is+ # small by nature, so no identifier filter is needed to bound it.+ #+ # Hydrated so each row can render reason, expiry, who and the source run+ # without a per-row fetch. `Run.metadata` and `Run.error_message` can be+ # large and are not needed for the summary.+ active_quarantines_by_key: dict[_SnapshotKey, QuarantinedIdentifier] = {}+ for active_quarantine in (+ QuarantinedIdentifier.objects.filter(repo_id=repo_id)+ .filter(live)+ .select_related("source_run")+ .defer("source_run__metadata", "source_run__error_message")+ .order_by("-created_at")+ ):+ quarantine_key = _SnapshotKey(run_type=active_quarantine.run_type, identifier=active_quarantine.identifier)+ # Creating a quarantine supersedes the prior active row, so duplicates+ # should not exist. Keep the newest if one ever does.+ if quarantine_key not in active_quarantines_by_key:+ active_quarantines_by_key[quarantine_key] = active_quarantine++ # `status=completed` rather than `superseded_by IS NULL`: a freshly started+ # run on the default branch is un-superseded but has few or no RunSnapshots+ # ingested yet, which would collapse the universe to whatever it has loaded+ # so far. Same reasoning as `baseline_overview.get_baselines_overview`.+ universe_runs = list(+ Run.objects.filter(+ repo_id=repo_id,+ branch__in=run_queries._DEFAULT_BRANCHES,+ status=RunStatus.COMPLETED,+ )+ .order_by("repo_id", "branch", "run_type", "-created_at")+ .distinct("repo_id", "branch", "run_type")+ .only("id", "run_type", "created_at")+ )+ if not universe_runs:+ return _quarantine_only_raw(+ active_quarantines_by_key,+ generated_at=now,+ strip_days=FLAKINESS_STRIP_DAYS,+ max_entries=FLAKINESS_MAX_ENTRIES,+ )++ # `universe_runs` holds one run per branch and run type, so a repo with runs+ # on both master and main has two per run type. The row identity carries no+ # branch, so keep only the newest run per run type. Otherwise whichever+ # branch happened to be read last decided the baseline, and two identical+ # requests could disagree.+ newest_run_by_type: dict[str, Run] = {}+ for run in sorted(universe_runs, key=lambda r: r.created_at, reverse=True):+ newest_run_by_type.setdefault(run.run_type, run)++ run_type_by_run_id = {run.id: run_type for run_type, run in newest_run_by_type.items()}+ universe_run_ids = list(run_type_by_run_id)++ # The baseline hash each identifier would be compared against right now.+ # values_list rather than model hydration: the universe can run to+ # thousands of rows and only the listed ones need thumbnails later.+ baseline_hash_by_key: dict[_SnapshotKey, str] = {}+ for run_id, identifier, baseline_hash in RunSnapshot.objects.filter(run_id__in=universe_run_ids).values_list(+ "run_id", "identifier", "baseline_hash"+ ):+ if baseline_hash:+ baseline_hash_by_key[_SnapshotKey(run_type=run_type_by_run_id[run_id], identifier=identifier)] = (+ baseline_hash+ )++ # One entry per `(run_type, identifier)` that has a baseline to compare+ # against. Not a row count: rows carry snapshots with no baseline yet, and+ # repeat an identity when a repo runs on both master and main.+ tracked_total = len(baseline_hash_by_key)++ universe_identifiers = list({key.identifier for key in baseline_hash_by_key})+ universe_baseline_hashes = list(set(baseline_hash_by_key.values()))++ # Only rows the classifier could still match: auto-minted, and live.+ # Mirrors the `expires_at` filter in `runs.complete_run` so this count+ # equals what a run would actually match.+ auto_tolerations = ToleratedHash.objects.filter(+ repo_id=repo_id,+ reason=ToleratedReason.AUTO_THRESHOLD,+ identifier__in=universe_identifiers,+ baseline_hash__in=universe_baseline_hashes,+ ).filter(live)++ # Both `__in` filters narrow on the `tolerated_lookup` index, but they are+ # independent, so a row could match one identifier's baseline hash under+ # another identifier's name. Content hashes make that vanishingly unlikely,+ # and the exact pair is verified when entries are assembled below.+ variants_by_pair: dict[_VariantKey, _VariantStats] = {}+ for identifier, baseline_hash, variant_count, avg_diff in (+ auto_tolerations.values("identifier", "baseline_hash")+ .annotate(+ variant_count=Count("alternate_hash", distinct=True),+ avg_diff=Avg("diff_percentage"),+ )+ .values_list("identifier", "baseline_hash", "variant_count", "avg_diff")+ ):+ variants_by_pair[_VariantKey(identifier=identifier, baseline_hash=baseline_hash)] = _VariantStats(+ count=variant_count,+ avg_diff_percentage=avg_diff,+ )++ # Per-day counts for the activity strip. `(identifier, baseline_hash,+ # alternate_hash)` is unique, so a row is a distinct variant and a plain+ # count per day needs no DISTINCT.+ strip_start = today - timedelta(days=FLAKINESS_STRIP_DAYS - 1)+ daily_by_pair: dict[_VariantKey, dict[date, int]] = defaultdict(dict)+ for identifier, baseline_hash, day, count in (+ auto_tolerations.filter(created_at__date__gte=strip_start)+ .annotate(day=TruncDate("created_at"))+ .values("identifier", "baseline_hash", "day")+ .annotate(day_count=Count("id"))+ .values_list("identifier", "baseline_hash", "day", "day_count")+ ):+ daily_by_pair[_VariantKey(identifier=identifier, baseline_hash=baseline_hash)][day] = count++ # Only identifiers that can produce a row. Everything else is dropped by the+ # assembly loop below, so scanning it buys nothing.+ reportable_identifiers = list(+ {key.identifier for key in variants_by_pair} | {key.identifier for key in active_quarantines_by_key}+ )+ if not reportable_identifiers:+ return _FlakinessRaw.empty(generated_at=now, tracked_total=tracked_total)++ # When each baseline last moved. A real flip on the default branch leaves a+ # CHANGED or REMOVED row in the run that introduced it, because later runs+ # compare against the new committed baseline and see UNCHANGED. That makes+ # `Max` the most recent flip, which stays right when a baseline is reverted+ # to a hash it held before.+ #+ # CHANGED is not only a flip. A snapshot that keeps rendering differently+ # from an unchanged baseline, with no toleration to match it, records+ # CHANGED on every run. `Max` then reports the latest failure instead of the+ # last real move, so the age reads too new for that snapshot.+ #+ # Grouping the whole history by `baseline_hash` instead would read more+ # precisely, but it admits every historical row rather than the rare event+ # rows, which is the shape `baseline_overview` documents as ~7s and an OOM+ # on the web pod. This uses the `snapshot_run_result` index the same way its+ # neighbour does.+ baseline_moved_at_by_key: dict[_SnapshotKey, datetime] = {}+ for identifier, run_type, moved_at in (+ RunSnapshot.objects.filter(+ run__repo_id=repo_id,+ run__branch__in=run_queries._DEFAULT_BRANCHES,+ run__status=RunStatus.COMPLETED,+ result__in=(SnapshotResult.CHANGED, SnapshotResult.REMOVED),+ identifier__in=reportable_identifiers,+ )+ .values("identifier", "run__run_type")+ .annotate(moved_at=Max("run__created_at"))+ .values_list("identifier", "run__run_type", "moved_at")+ ):+ if moved_at is not None:+ baseline_moved_at_by_key[_SnapshotKey(run_type=run_type, identifier=identifier)] = moved_at++ minted_recently_by_key: dict[_FlakeKey, datetime] = {}+ for run_type, identifier, baseline_hash, minted_at in (+ auto_tolerations.filter(+ source_run__branch__in=run_queries._DEFAULT_BRANCHES,+ source_run__status=RunStatus.COMPLETED,+ )+ .values("source_run__run_type", "identifier", "baseline_hash")+ # The run's timestamp, not the row's. `created_at` is when the toleration+ # was written, which can lag or be retried, and the repeat-match half+ # already reports when the run happened.+ .annotate(minted_at=Max("source_run__created_at"))+ .values_list("source_run__run_type", "identifier", "baseline_hash", "minted_at")+ ):+ if minted_at is not None:+ minted_recently_by_key[_FlakeKey(run_type=run_type, identifier=identifier, baseline_hash=baseline_hash)] = (+ minted_at+ )++ # When each snapshot last rendered one of its variants, from the runs that+ # matched. Bounded to the recency window on purpose: this decides `unstable`+ # against `settled`, and that decision only looks that far back. Beyond the+ # window the mint time below is the answer, and it is older or equal, which+ # keeps the state correct.+ #+ # The mint time alone is not enough, because `diffing.py` mints with+ # `get_or_create` and the classifier only links the matching `RunSnapshot`+ # back to the row. A snapshot cycling through variants it already recorded+ # never refreshes `created_at`, so it would read as settled while it still+ # fails to render the same way twice.+ live_match = Q(tolerated_hash_match__expires_at__isnull=True) | Q(tolerated_hash_match__expires_at__gt=now)+ matched_recently_by_key: dict[_FlakeKey, datetime] = {}+ for run_type, identifier, baseline_hash, matched_at in (+ RunSnapshot.objects.filter(+ run__repo_id=repo_id,+ run__branch__in=run_queries._DEFAULT_BRANCHES,+ run__status=RunStatus.COMPLETED,+ run__created_at__gte=now - timedelta(days=FLAKINESS_RECENT_DAYS),+ identifier__in=reportable_identifiers,+ classification_reason=ClassificationReason.TOLERATED_HASH,+ tolerated_hash_match__reason=ToleratedReason.AUTO_THRESHOLD,+ )+ .filter(live_match)+ .values("run__run_type", "identifier", "baseline_hash")+ .annotate(matched_at=Max("run__created_at"))+ .values_list("run__run_type", "identifier", "baseline_hash", "matched_at")+ ):+ if matched_at is not None:+ matched_recently_by_key[+ _FlakeKey(run_type=run_type, identifier=identifier, baseline_hash=baseline_hash)+ ] = matched_at++ recency_cutoff = now - timedelta(days=FLAKINESS_RECENT_DAYS)+ expiry_soon_cutoff = now + timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS)++ # A quarantine can cover a snapshot that has no current baseline: one added+ # in this run, or one that dropped out of the latest default-branch run.+ # Those keys are absent from `baseline_hash_by_key`, so walk them too rather+ # than hide a quarantine somebody is relying on.+ quarantine_only_keys = active_quarantines_by_key.keys() - baseline_hash_by_key.keys()+ scored_keys: list[tuple[_SnapshotKey, str]] = [+ *baseline_hash_by_key.items(),+ *((key, "") for key in quarantine_only_keys),+ ]++ rows: list[_FlakinessRow] = []+ for key, baseline_hash in scored_keys:+ variant_key = _VariantKey(identifier=key.identifier, baseline_hash=baseline_hash)+ stats = variants_by_pair.get(variant_key) if baseline_hash else None+ quarantine = active_quarantines_by_key.get(key)+ if stats is None and quarantine is None:+ continue++ flake_key = _FlakeKey(run_type=key.run_type, identifier=key.identifier, baseline_hash=baseline_hash)+ variant_count = stats.count if stats is not None else 0+ last_flaked_at = _latest(+ minted_recently_by_key.get(flake_key),+ matched_recently_by_key.get(flake_key),+ )+ is_unstable = last_flaked_at is not None and last_flaked_at >= recency_cutoff+ rows.append(+ _FlakinessRow(+ run_type=key.run_type,+ identifier=key.identifier,+ variant_count=variant_count,+ last_flaked_at=last_flaked_at,+ avg_diff_percentage=stats.avg_diff_percentage if stats is not None else None,+ daily_counts=_daily_series(+ daily_by_pair.get(variant_key, {}),+ strip_start=strip_start,+ length=FLAKINESS_STRIP_DAYS,+ ),+ baseline_moved_at=baseline_moved_at_by_key.get(key),+ is_unstable=is_unstable,+ quarantine=quarantine,+ needs_decision=_needs_decision(+ quarantine=quarantine,+ variant_count=variant_count,+ expiry_soon_cutoff=expiry_soon_cutoff,+ ),+ )+ )++ # Ordering decides what survives the cap, so the rows somebody has to act on+ # come first. Sorting on variant count alone put clean quarantines last,+ # exactly the rows the `quarantined` and `needs a decision` filters exist to+ # surface, and the tiles would still have counted them.+ #+ # Rows that never flaked sort last within their group against an aware+ # epoch, because `last_flaked_at` is aware and mixing it with a naive+ # datetime raises.+ never = datetime.min.replace(tzinfo=UTC)+ rows.sort(+ key=lambda row: (+ row.needs_decision,+ row.quarantine is not None,+ row.variant_count,+ row.last_flaked_at or never,+ ),+ reverse=True,+ )+ listed = rows[:FLAKINESS_MAX_ENTRIES]++ snapshots_by_key = _hydrate_snapshots(+ universe_run_ids=universe_run_ids,+ run_type_by_run_id=run_type_by_run_id,+ keys={_SnapshotKey(run_type=row.run_type, identifier=row.identifier) for row in listed},+ )++ return _FlakinessRaw(+ rows=listed,+ snapshots_by_key=snapshots_by_key,+ tracked_total=tracked_total,+ totals_unstable=sum(1 for row in rows if row.is_unstable),+ totals_settled=sum(1 for row in rows if not row.is_unstable and row.variant_count > 0),+ totals_quarantined=sum(1 for row in rows if row.quarantine is not None),+ totals_needs_decision=sum(1 for row in rows if row.needs_decision),+ by_run_type=dict(Counter(row.run_type for row in rows)),+ truncated=len(listed) < len(rows),+ generated_at=now,+ )+++def _quarantine_only_raw(+ active_quarantines_by_key: dict[_SnapshotKey, QuarantinedIdentifier],+ *,+ generated_at: datetime,+ strip_days: int,+ max_entries: int,+) -> _FlakinessRaw:+ """The page for a repo with no completed default-branch run yet.++ There is no baseline to score against, so `tracked` is 0 and every row is+ clean. The quarantines still have to appear: creating one does not require+ a baseline, and someone is relying on the snapshot being skipped.+ """+ rows = [+ _FlakinessRow(+ run_type=key.run_type,+ identifier=key.identifier,+ variant_count=0,+ last_flaked_at=None,+ avg_diff_percentage=None,+ daily_counts=[0] * strip_days,+ baseline_moved_at=None,+ is_unstable=False,+ quarantine=quarantine,+ needs_decision=True,+ )+ for key, quarantine in active_quarantines_by_key.items()+ ]+ rows.sort(key=lambda row: (row.run_type, row.identifier))+ listed = rows[:max_entries]+ return _FlakinessRaw(+ rows=listed,+ snapshots_by_key={},+ tracked_total=0,+ totals_unstable=0,+ totals_settled=0,+ # Totals count the whole population, as they do on the normal path, so+ # the tiles stay right when the list is capped.+ totals_quarantined=len(rows),+ totals_needs_decision=len(rows),+ by_run_type=dict(Counter(row.run_type for row in rows)),+ truncated=len(listed) < len(rows),+ generated_at=generated_at,+ )+++def _latest(*moments: datetime | None) -> datetime | None:+ """The most recent of several optional timestamps, or None when all are unset."""+ known = [moment for moment in moments if moment is not None]+ return max(known) if known else None+++def snapshot_key(row: _FlakinessRow) -> _SnapshotKey:+ """Key for `_FlakinessRaw.snapshots_by_key`, for the facade to look a row up."""+ return _SnapshotKey(run_type=row.run_type, identifier=row.identifier)+++def _needs_decision(+ *,+ quarantine: QuarantinedIdentifier | None,+ variant_count: int,+ expiry_soon_cutoff: datetime,+) -> bool:+ """Whether an active quarantine has stopped matching what it was opened for.++ Three ways that happens: it already ran out, it is about to, or the+ snapshot it covers no longer produces variants at all. An expired entry is+ not in `quarantine` to begin with, because the caller filters on+ `expires_at`, so only the last two are testable here.+ """+ if quarantine is None:+ return False+ if variant_count == 0:+ return True+ return quarantine.expires_at is not None and quarantine.expires_at <= expiry_soon_cutoff+++def _daily_series(counts_by_day: dict[date, int], *, strip_start: date, length: int) -> list[int]:+ """Dense oldest-first series so the frontend renders a fixed axis."""+ return [counts_by_day.get(strip_start + timedelta(days=offset), 0) for offset in range(length)]+++def _hydrate_snapshots(+ *,+ universe_run_ids: list[UUID],+ run_type_by_run_id: dict[UUID, str],+ keys: set[_SnapshotKey],+) -> dict[_SnapshotKey, RunSnapshot]:+ """Thumbnail and dimension data for the listed rows only."""+ if not keys:+ return {}+ identifiers = list({key.identifier for key in keys})+ hydrated: dict[_SnapshotKey, RunSnapshot] = {}+ for snapshot in (+ RunSnapshot.objects.filter(run_id__in=universe_run_ids, identifier__in=identifiers)+ .select_related("current_artifact__thumbnail")+ .only(+ "identifier",+ "metadata",+ "run_id",+ "current_artifact__width",+ "current_artifact__height",+ "current_artifact__thumbnail__content_hash",+ )+ ):+ key = _SnapshotKey(run_type=run_type_by_run_id[snapshot.run_id], identifier=snapshot.identifier)+ if key in keys:+ hydrated[key] = snapshot+ return hydrated+++@frozen+class _VariantStats:+ """Grouped toleration stats for one `(identifier, baseline_hash)` pair."""++ count: int+ avg_diff_percentage: float | None+++@frozen+class _FlakinessRow:+ """One scored snapshot identity, before thumbnails and users are attached."""++ run_type: str+ identifier: str+ variant_count: int+ last_flaked_at: datetime | None+ avg_diff_percentage: float | None+ daily_counts: list[int]+ baseline_moved_at: datetime | None+ is_unstable: bool+ quarantine: QuarantinedIdentifier | None+ needs_decision: bool+++@frozen+class _FlakinessRaw:+ """Internal raw shape. The facade reshapes this into the public DTOs.++ Private to this package so contract changes do not ripple back in.+ """++ rows: list[_FlakinessRow]+ snapshots_by_key: dict[_SnapshotKey, RunSnapshot]+ tracked_total: int+ totals_unstable: int+ totals_settled: int+ totals_quarantined: int+ totals_needs_decision: int+ by_run_type: dict[str, int]+ truncated: bool+ generated_at: datetime++ @classmethod+ def empty(cls, *, generated_at: datetime, tracked_total: int = 0) -> _FlakinessRaw:+ return cls(+ rows=[],+ snapshots_by_key={},+ tracked_total=tracked_total,+ totals_unstable=0,+ totals_settled=0,+ totals_quarantined=0,+ totals_needs_decision=0,+ by_run_type={},+ truncated=False,+ generated_at=generated_at,+ )diff --git a/products/visual_review/backend/logic/thumbnails.py b/products/visual_review/backend/logic/thumbnails.pyindex 5bf8e813b985..36e08efd8542 100644--- a/products/visual_review/backend/logic/thumbnails.py+++ b/products/visual_review/backend/logic/thumbnails.py@@ -8,22 +8,24 @@ from ..models import RunSnapshotfrom ..storage import ArtifactStorage-def get_thumbnail_hash_for_identifier(repo_id: UUID, identifier: str) -> str | None:+def get_thumbnail_hash_for_identifier(repo_id: UUID, identifier: str, run_type: str | None = None) -> str | None:"""Look up the thumbnail content hash for a snapshot identifier.- Finds the most recent artifact with a thumbnail for this identifier- across all runs. Returns the thumbnail's content_hash or None.+ Finds the most recent artifact with a thumbnail for this identifier.+ Returns the thumbnail's content_hash or None.++ Pass `run_type` when the caller shows more than one of them, because the+ same identifier under two run types is two different images and this would+ otherwise return whichever ran last."""- snapshot = (- RunSnapshot.objects.filter(- run__repo_id=repo_id,- identifier=identifier,- current_artifact__thumbnail__isnull=False,- )- .select_related("current_artifact__thumbnail")- .order_by("-run__created_at")- .first()+ snapshots = RunSnapshot.objects.filter(+ run__repo_id=repo_id,+ identifier=identifier,+ current_artifact__thumbnail__isnull=False,)+ if run_type:+ snapshots = snapshots.filter(run__run_type=run_type)+ snapshot = snapshots.select_related("current_artifact__thumbnail").order_by("-run__created_at").first()if snapshot is None:return Nonediff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.pyindex 39708de438a1..b9dfceb31436 100644--- a/products/visual_review/backend/presentation/serializers.py+++ b/products/visual_review/backend/presentation/serializers.py@@ -8,6 +8,7 @@ from rest_framework import serializersfrom rest_framework_dataclasses.serializers import DataclassSerializerfrom ..facade.contracts import (+ FLAKINESS_STRIP_DAYS,AddSnapshotsInput,AddSnapshotsResult,ApproveRunRequestInput,@@ -24,6 +25,9 @@ from ..facade.contracts import (DiffCluster,FinalizeResult,FinalizeRunRequestInput,+ FlakinessEntry,+ FlakinessOverview,+ FlakinessTotals,QuarantinedIdentifierEntry,QuarantineInput,QuarantineSourceRun,@@ -39,6 +43,7 @@ from ..facade.contracts import (UploadTarget,UserBasicInfo,)+from ..facade.enums import FlakinessState# --- Output Serializers ---@@ -319,3 +324,100 @@ class BaselineOverviewSerializer(DataclassSerializer):class Meta:dataclass = BaselineOverview+++class FlakinessEntrySerializer(DataclassSerializer):+ variant_count = serializers.IntegerField(+ help_text=(+ "Distinct alternate hashes the classifier can still match for this snapshot's current "+ "baseline. Reads as how many different images this snapshot is currently allowed to "+ "produce. Resets when the baseline moves, because tolerations recorded against an old "+ "baseline hash can never match again."+ )+ )+ last_flaked_at = serializers.DateTimeField(+ allow_null=True,+ required=False,+ help_text=(+ "Last default-branch run that rendered one of those variants. This is not when a variant "+ "was first recorded: a snapshot can cycle through variants it already recorded without "+ "adding a new one, and that case still flakes on every run. Null when no run matched one."+ ),+ )+ avg_diff_percentage = serializers.FloatField(+ allow_null=True,+ required=False,+ help_text=(+ "Mean fraction of pixels that differed across those variants. Separates sub-pixel noise "+ "from a small but real rendering change."+ ),+ )+ baseline_age_days = serializers.IntegerField(+ allow_null=True,+ required=False,+ help_text=(+ "Days since the first default-branch run that compared against the current baseline, "+ "which is when that baseline took effect. Context for `variant_count`: the same count "+ "against a four-day-old baseline is far worse than against a six-month-old one."+ ),+ )+ daily_variant_counts = serializers.ListField(+ child=serializers.IntegerField(),+ help_text=(+ f"Variants recorded per day over the last {FLAKINESS_STRIP_DAYS} days, oldest first. "+ "Always that length, so a fixed time axis can be rendered."+ ),+ )+ baseline_moved_day_index = serializers.IntegerField(+ allow_null=True,+ required=False,+ help_text=(+ "Index into `daily_variant_counts` where the baseline moved. Null when it moved before "+ "the window opened, which is the common case."+ ),+ )+ flakiness_state = serializers.ChoiceField(+ choices=[(state.value, state.value) for state in FlakinessState],+ help_text=(+ "`unstable` when a run rendered a variant inside the recency window, new or already "+ "known, `settled` when variants exist against this baseline but none recently, "+ "`clean` when none exist. A `clean` entry is always a quarantined one, because an "+ "unquarantined snapshot with no variants is not listed at all."+ ),+ )+ needs_decision = serializers.BooleanField(+ help_text=(+ "True when an active quarantine has run out, is about to, or covers a snapshot that no "+ "longer produces variants. All three mean a human has to extend it or lift it."+ )+ )+ quarantine = BaselineQuarantineSummarySerializer(+ allow_null=True,+ required=False,+ help_text="Active quarantine details when `is_quarantined` is true. Null otherwise.",+ )++ class Meta:+ dataclass = FlakinessEntry+++class FlakinessTotalsSerializer(DataclassSerializer):+ listed = serializers.IntegerField(help_text="Identifiers with an entry in `entries`.")+ tracked = serializers.IntegerField(+ help_text=(+ "Identifiers with a current baseline, listed or not. The denominator that says how much "+ "of the repo renders consistently."+ )+ )+ by_run_type = serializers.DictField(child=serializers.IntegerField())++ class Meta:+ dataclass = FlakinessTotals+++class FlakinessOverviewSerializer(DataclassSerializer):+ entries = FlakinessEntrySerializer(many=True)+ totals = FlakinessTotalsSerializer()++ class Meta:+ dataclass = FlakinessOverviewdiff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.pyindex a2ac919d9e34..8c67f41aca17 100644--- a/products/visual_review/backend/presentation/views.py+++ b/products/visual_review/backend/presentation/views.py@@ -51,6 +51,7 @@ from .serializers import (CreateRunResultSerializer,FinalizeResultSerializer,FinalizeRunInputSerializer,+ FlakinessOverviewSerializer,MarkToleratedInputSerializer,QuarantinedIdentifierEntrySerializer,QuarantineInputSerializer,@@ -116,6 +117,7 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"list_quarantined","thumbnail","baselines",+ "flakiness",]@extend_schema(responses={200: RepoSerializer(many=True)})@@ -181,6 +183,16 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH),OpenApiParameter("identifier", OpenApiTypes.STR, OpenApiParameter.PATH),+ OpenApiParameter(+ "run_type",+ OpenApiTypes.STR,+ OpenApiParameter.QUERY,+ required=False,+ description=(+ "Narrow the lookup to one run type. The same identifier under two run types is "+ "two different images, so omit this only when the caller shows one run type."+ ),+ ),],responses={200: OpenApiResponse(description="WebP thumbnail image")},)@@ -195,7 +207,9 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):patch_cache_control(resp, no_store=True)return resp- thumb_hash = api.get_thumbnail_hash_for_identifier(repo_id, identifier)+ thumb_hash = api.get_thumbnail_hash_for_identifier(+ repo_id, identifier, request.query_params.get("run_type") or None+ )if thumb_hash is None:resp = HttpResponse(status=404)patch_cache_control(resp, no_store=True)@@ -302,6 +316,30 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):result = api.get_baselines_overview(repo_id)return Response(BaselineOverviewSerializer(instance=result).data)+ @extend_schema(+ parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)],+ responses={200: FlakinessOverviewSerializer},+ description=(+ "Snapshots in a repo whose rendering cannot be trusted: those carrying at least one "+ "live tolerated variant against their current baseline, and those under an active "+ "quarantine. Everything else is omitted, so this is far smaller than the baselines "+ "universe; `totals.tracked` gives the full denominator. Variant counts are scoped to "+ "the current baseline hash, because a toleration recorded against an earlier baseline "+ "can never match again. Capped at "+ f"{contracts.FLAKINESS_MAX_ENTRIES} entries, which sets `truncated`. Filtering, "+ "faceting and search are done client-side; this endpoint takes no filter query params."+ ),+ )+ @action(detail=True, methods=["get"], url_path="flakiness")+ def flakiness(self, request: Request, pk: str, **kwargs) -> Response:+ repo_id = _parse_uuid(pk)+ try:+ api.get_repo(repo_id, team_id=self.team_id)+ except api.RepoNotFoundError:+ return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)+ result = api.get_flakiness_overview(repo_id)+ return Response(FlakinessOverviewSerializer(instance=result).data)+class SnapshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""Snapshot identities under a repo, keyed by (run_type, identifier).diff --git a/products/visual_review/backend/tests/test_flakiness.py b/products/visual_review/backend/tests/test_flakiness.pynew file mode 100644index 000000000000..dec113dd25a7--- /dev/null+++ b/products/visual_review/backend/tests/test_flakiness.py@@ -0,0 +1,553 @@+"""Tests for the flakiness overview.++Coverage:+- Variants are scoped to the current baseline hash, so a baseline move resets the score.+- Only auto-minted, unexpired tolerations count, matching what the classifier can match.+- `unstable` against `settled` turns on recency, not on the count.+- Only identifiers carrying variants or a quarantine are listed.+- `needs_decision` fires on the three ways an open quarantine stops fitting.+- The activity strip is dense and positions the baseline divider.+- Recency comes from runs that matched a variant, not from when it was minted.+- The history scan is bounded to identifiers that can produce a row.+- A variant's first occurrence counts, not just later matches of it.+- A quarantine without a current baseline is still listed.+- Recency is scoped to the default branch and to the row's own run type.+- Recency reports the run's time, not when the toleration row was written.+"""++from datetime import timedelta+from uuid import uuid4++from posthog.test.base import APIBaseTest++from django.db import connections+from django.test.utils import CaptureQueriesContext+from django.utils import timezone++from parameterized import parameterized++from products.visual_review.backend.db import WRITER_DB+from products.visual_review.backend.facade import api as vr_api+from products.visual_review.backend.facade.contracts import (+ FLAKINESS_EXPIRY_SOON_DAYS,+ FLAKINESS_RECENT_DAYS,+ FLAKINESS_STRIP_DAYS,+)+from products.visual_review.backend.facade.enums import (+ ClassificationReason,+ FlakinessState,+ RunStatus,+ RunType,+ SnapshotResult,+ ToleratedReason,+)+from products.visual_review.backend.models import QuarantinedIdentifier, Repo, Run, RunSnapshot, ToleratedHash+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixin++CURRENT_BASELINE = "baseline-current"+++def _mk_run(+ repo: Repo,+ *,+ branch: str = "master",+ run_type: str = RunType.STORYBOOK,+ superseded_by: Run | None = None,+) -> Run:+ return Run.objects.create(+ team_id=repo.team_id,+ repo=repo,+ run_type=run_type,+ branch=branch,+ commit_sha=uuid4().hex[:12],+ status=RunStatus.COMPLETED,+ completed_at=timezone.now(),+ superseded_by=superseded_by,+ )+++def _mk_snapshot(+ run: Run,+ *,+ identifier: str,+ baseline_hash: str = CURRENT_BASELINE,+ result: str = SnapshotResult.UNCHANGED,+ tolerated_hash_match: ToleratedHash | None = None,+) -> RunSnapshot:+ return RunSnapshot.objects.create(+ run=run,+ team_id=run.team_id,+ identifier=identifier,+ baseline_hash=baseline_hash,+ result=result,+ tolerated_hash_match=tolerated_hash_match,+ classification_reason=ClassificationReason.TOLERATED_HASH if tolerated_hash_match else "",+ )+++class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):+ databases = PRODUCT_DATABASES++ def setUp(self):+ super().setUp()+ self.repo = Repo.objects.create(+ team_id=self.team.id,+ repo_external_id=4242,+ repo_full_name="PostHog/flaky",+ )+ self.master_run = _mk_run(self.repo)++ def _mk_variant(+ self,+ *,+ identifier: str,+ alternate_hash: str,+ baseline_hash: str = CURRENT_BASELINE,+ reason: str = ToleratedReason.AUTO_THRESHOLD,+ age: timedelta = timedelta(days=1),+ expires_at=None,+ diff_percentage: float | None = None,+ source_run: Run | None = None,+ ) -> ToleratedHash:+ # `diffing.py` always records the run that minted a variant, and the+ # aggregate reads recency through it, so a fixture without one does not+ # model anything real.+ minting_run = source_run+ if minting_run is None:+ minting_run = self._mk_default_branch_run(age=age)+ # The minting run rendered this snapshot, which is why it produced a+ # variant. Without the row the run can win the universe query while+ # carrying no snapshots, which no real run does.+ _mk_snapshot(minting_run, identifier=identifier, baseline_hash=baseline_hash)+ row = ToleratedHash.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier=identifier,+ baseline_hash=baseline_hash,+ alternate_hash=alternate_hash,+ reason=reason,+ expires_at=expires_at,+ diff_percentage=diff_percentage,+ source_run=minting_run,+ )+ ToleratedHash.objects.filter(id=row.id).update(created_at=timezone.now() - age)+ row.refresh_from_db()+ return row++ def _mk_default_branch_run(self, *, age: timedelta) -> Run:+ """A completed master run aged into the past.++ Superseded, because `unique_latest_run_per_group` allows one current run+ per group and the test's own master run holds that slot.+ """+ run = _mk_run(self.repo, superseded_by=self.master_run)+ Run.objects.filter(id=run.id).update(created_at=timezone.now() - age)+ run.refresh_from_db()+ return run++ def _mk_match(self, tolerated: ToleratedHash, *, age: timedelta) -> Run:+ """A run that rendered `tolerated` again and matched it.++ Repeat matches are the only evidence a snapshot still flakes once every+ variant it produces is already recorded.+ """+ run = self._mk_default_branch_run(age=age)+ _mk_snapshot(+ run,+ identifier=tolerated.identifier,+ baseline_hash=tolerated.baseline_hash,+ tolerated_hash_match=tolerated,+ )+ return run++ def _entry(self, identifier: str):+ result = vr_api.get_flakiness_overview(self.repo.id)+ return next((e for e in result.entries if e.identifier == identifier), None)++ def test_variants_against_a_superseded_baseline_are_not_counted(self):+ _mk_snapshot(self.master_run, identifier="redesigned")+ for index in range(5):+ self._mk_variant(identifier="redesigned", alternate_hash=f"old-{index}", baseline_hash="baseline-previous")+ self._mk_variant(identifier="redesigned", alternate_hash="new-0")++ entry = self._entry("redesigned")++ assert entry is not None+ assert entry.variant_count == 1++ def test_a_snapshot_whose_only_variants_predate_the_baseline_move_is_not_listed(self):+ _mk_snapshot(self.master_run, identifier="redesigned")+ for index in range(5):+ self._mk_variant(identifier="redesigned", alternate_hash=f"old-{index}", baseline_hash="baseline-previous")++ assert self._entry("redesigned") is None++ @parameterized.expand(+ [+ ("human_tolerations", ToleratedReason.HUMAN),+ ("agent_tolerations", ToleratedReason.AGENT),+ ]+ )+ def test_deliberate_tolerations_are_not_counted_as_flakiness(self, _name: str, reason: str):+ _mk_snapshot(self.master_run, identifier="accepted")+ self._mk_variant(identifier="accepted", alternate_hash="a", reason=reason)++ assert self._entry("accepted") is None++ def test_expired_variants_are_not_counted(self):+ _mk_snapshot(self.master_run, identifier="lapsed")+ self._mk_variant(identifier="lapsed", alternate_hash="live")+ self._mk_variant(+ identifier="lapsed",+ alternate_hash="dead",+ expires_at=timezone.now() - timedelta(days=1),+ )++ entry = self._entry("lapsed")++ assert entry is not None+ assert entry.variant_count == 1++ @parameterized.expand(+ [+ ("just_inside_the_window", timedelta(days=FLAKINESS_RECENT_DAYS - 1), FlakinessState.UNSTABLE),+ ("just_outside_the_window", timedelta(days=FLAKINESS_RECENT_DAYS + 1), FlakinessState.SETTLED),+ ]+ )+ def test_state_turns_on_recency_not_on_count(self, _name: str, age: timedelta, expected: str):+ _mk_snapshot(self.master_run, identifier="noisy")+ for index in range(20):+ self._mk_variant(identifier="noisy", alternate_hash=f"a-{index}", age=age)++ entry = self._entry("noisy")++ assert entry is not None+ assert entry.variant_count == 20+ assert entry.flakiness_state == expected++ def test_a_snapshot_cycling_through_known_variants_stays_unstable(self):+ # The mint site uses get_or_create, so a repeat match never refreshes+ # ToleratedHash.created_at. Scoring recency off that timestamp would+ # call this snapshot settled while it still fails to render the same+ # way twice, which is the worst case this page exists to find.+ _mk_snapshot(self.master_run, identifier="cycling")+ old = timedelta(days=FLAKINESS_RECENT_DAYS + 20)+ for index in range(3):+ variant = self._mk_variant(identifier="cycling", alternate_hash=f"a-{index}", age=old)+ self._mk_match(variant, age=timedelta(hours=6))+ assert all(t.created_at < timezone.now() - old + timedelta(hours=1) for t in ToleratedHash.objects.all())++ entry = self._entry("cycling")++ assert entry is not None+ assert entry.variant_count == 3+ assert entry.flakiness_state == FlakinessState.UNSTABLE++ def test_the_history_scan_skips_identifiers_that_cannot_produce_a_row(self):+ # The era query reaches over the repo's whole default-branch history,+ # so the identifier list is the only thing bounding it. Widening it back+ # to the universe would scan every quiet snapshot to throw the result+ # away, which is most of them on a healthy repo.+ _mk_snapshot(self.master_run, identifier="quiet")+ _mk_snapshot(self.master_run, identifier="flaky")+ self._mk_variant(identifier="flaky", alternate_hash="a")++ with CaptureQueriesContext(connections[WRITER_DB]) as captured:+ vr_api.get_flakiness_overview(self.repo.id)++ # The history queries are the ones that join RunSnapshot to Run and+ # aggregate over run timestamps.+ history_queries = [+ q["sql"]+ for q in captured.captured_queries+ if "visual_review_run" in q["sql"]+ and "MAX(" in q["sql"].upper()+ and "visual_review_runsnapshot" in q["sql"]+ ]+ assert history_queries+ for sql in history_queries:+ assert "flaky" in sql+ assert "quiet" not in sql++ def test_a_first_time_variant_counts_as_a_flake(self):+ # The run that mints a variant is classified BELOW_THRESHOLD and never+ # linked to the row it created, so run matches alone miss every first+ # occurrence. That would report a snapshot that started flaking today+ # as settled, which is the opposite of what the tile promises.+ _mk_snapshot(self.master_run, identifier="just-started")+ row = self._mk_variant(identifier="just-started", alternate_hash="first")+ assert not RunSnapshot.objects.filter(tolerated_hash_match=row).exists()++ entry = self._entry("just-started")++ assert entry is not None+ assert entry.variant_count == 1+ assert entry.flakiness_state == FlakinessState.UNSTABLE++ def test_a_quarantine_on_a_snapshot_without_a_baseline_is_still_listed(self):+ # Quarantining does not require a baseline, and the empty state promises+ # that quarantining alone puts a snapshot on this page.+ _mk_snapshot(self.master_run, identifier="brand-new", baseline_hash="")+ QuarantinedIdentifier.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier="brand-new",+ run_type=RunType.STORYBOOK,+ reason="Flaky from the first run",+ )++ result = vr_api.get_flakiness_overview(self.repo.id)++ assert [e.identifier for e in result.entries] == ["brand-new"]+ assert result.totals.quarantined == 1++ def test_the_baseline_for_a_run_type_does_not_depend_on_branch_order(self):+ # One run per branch and run type means a repo on both master and main+ # has two, and the row identity carries no branch. Without picking the+ # newest, two identical requests could report different baselines.+ main_run = _mk_run(self.repo, branch="main")+ Run.objects.filter(id=main_run.id).update(created_at=timezone.now() - timedelta(days=3))+ _mk_snapshot(main_run, identifier="shared", baseline_hash="baseline-stale")+ _mk_snapshot(self.master_run, identifier="shared")+ self._mk_variant(identifier="shared", alternate_hash="a")++ entry = self._entry("shared")++ assert entry is not None+ assert entry.variant_count == 1++ def test_a_variant_minted_on_a_pr_branch_does_not_count_as_recent(self):+ # diffing.py mints from PR runs too. A PR rendering a variant is a+ # property of that branch, not evidence the default branch is unstable.+ _mk_snapshot(self.master_run, identifier="pr-only")+ pr_run = _mk_run(self.repo, branch="feat/something", superseded_by=self.master_run)+ self._mk_variant(identifier="pr-only", alternate_hash="from-pr", source_run=pr_run)++ entry = self._entry("pr-only")++ assert entry is not None+ assert entry.variant_count == 1+ assert entry.last_flaked_at is None+ assert entry.flakiness_state == FlakinessState.SETTLED++ def test_recency_does_not_leak_between_run_types(self):+ # Matching ignores run type, but a row does not. A recent storybook+ # flake says nothing about the playwright row for the same identifier.+ playwright_run = _mk_run(self.repo, run_type=RunType.PLAYWRIGHT)+ _mk_snapshot(playwright_run, identifier="shared")+ _mk_snapshot(self.master_run, identifier="shared")+ self._mk_variant(identifier="shared", alternate_hash="a", age=timedelta(hours=2))++ result = vr_api.get_flakiness_overview(self.repo.id)+ by_type = {e.run_type: e for e in result.entries if e.identifier == "shared"}++ # Both rows exist and both count the variant, because the classifier+ # would match it either way. Only the run type that actually rendered it+ # recently is unstable.+ assert by_type[RunType.STORYBOOK].flakiness_state == FlakinessState.UNSTABLE+ assert by_type[RunType.PLAYWRIGHT].variant_count == 1+ assert by_type[RunType.PLAYWRIGHT].last_flaked_at is None+ assert by_type[RunType.PLAYWRIGHT].flakiness_state == FlakinessState.SETTLED++ def test_a_quarantine_survives_a_repo_with_no_completed_default_run(self):+ # Quarantining does not wait for a first master run, and somebody is+ # relying on the snapshot being skipped meanwhile.+ Run.objects.filter(repo=self.repo).update(status=RunStatus.PENDING)+ QuarantinedIdentifier.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier="muted-early",+ run_type=RunType.STORYBOOK,+ reason="Flaky since the first run",+ )++ result = vr_api.get_flakiness_overview(self.repo.id)++ assert [e.identifier for e in result.entries] == ["muted-early"]+ assert result.totals.tracked == 0+ assert result.totals.quarantined == 1++ def test_recency_reports_when_the_run_happened_not_when_the_row_was_written(self):+ # ToleratedHash.created_at is when the row was written, which can lag or+ # be retried. Reporting that would call an old capture newly unstable.+ _mk_snapshot(self.master_run, identifier="delayed")+ stale_run = self._mk_default_branch_run(age=timedelta(days=FLAKINESS_RECENT_DAYS + 5))+ _mk_snapshot(stale_run, identifier="delayed")+ row = self._mk_variant(identifier="delayed", alternate_hash="a", source_run=stale_run)+ ToleratedHash.objects.filter(id=row.id).update(created_at=timezone.now())++ entry = self._entry("delayed")++ assert entry is not None+ assert entry.flakiness_state == FlakinessState.SETTLED++ def test_rows_needing_a_decision_survive_the_entry_cap(self):+ # The cap slices the sorted list, so ordering decides what a client can+ # still act on. A clean quarantine has no variants and would sort last+ # under a count-only order, while the tiles kept counting it.+ _mk_snapshot(self.master_run, identifier="muted")+ QuarantinedIdentifier.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier="muted",+ run_type=RunType.STORYBOOK,+ reason="Known flaky",+ )+ _mk_snapshot(self.master_run, identifier="noisy")+ for index in range(5):+ self._mk_variant(identifier="noisy", alternate_hash=f"a-{index}")++ result = vr_api.get_flakiness_overview(self.repo.id)++ assert [e.identifier for e in result.entries] == ["muted", "noisy"]++ def test_snapshots_with_nothing_to_report_are_not_listed(self):+ _mk_snapshot(self.master_run, identifier="stable")+ _mk_snapshot(self.master_run, identifier="flaky")+ self._mk_variant(identifier="flaky", alternate_hash="a")++ result = vr_api.get_flakiness_overview(self.repo.id)++ assert [e.identifier for e in result.entries] == ["flaky"]+ assert result.totals.listed == 1+ assert result.totals.tracked == 2++ def test_the_denominator_counts_only_snapshots_with_a_baseline(self):+ _mk_snapshot(self.master_run, identifier="compared")+ _mk_snapshot(self.master_run, identifier="brand-new", baseline_hash="")++ result = vr_api.get_flakiness_overview(self.repo.id)++ assert result.totals.tracked == 1++ def test_a_quarantined_snapshot_with_no_variants_is_listed_as_clean(self):+ _mk_snapshot(self.master_run, identifier="muted")+ QuarantinedIdentifier.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier="muted",+ run_type=RunType.STORYBOOK,+ reason="Async content loading race condition",+ )++ entry = self._entry("muted")++ assert entry is not None+ assert entry.variant_count == 0+ assert entry.flakiness_state == FlakinessState.CLEAN+ assert entry.is_quarantined is True++ @parameterized.expand(+ [+ ("expiring_soon", timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS - 1), 3, True),+ ("expiring_later", timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS + 5), 3, False),+ ("open_ended_but_still_flaking", None, 3, False),+ ]+ )+ def test_needs_decision_flags_a_quarantine_that_stopped_fitting(+ self, _name: str, expires_in: timedelta | None, variant_count: int, expected: bool+ ):+ _mk_snapshot(self.master_run, identifier="muted")+ for index in range(variant_count):+ self._mk_variant(identifier="muted", alternate_hash=f"a-{index}")+ QuarantinedIdentifier.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier="muted",+ run_type=RunType.STORYBOOK,+ reason="Known flaky",+ expires_at=timezone.now() + expires_in if expires_in is not None else None,+ )++ entry = self._entry("muted")++ assert entry is not None+ assert entry.needs_decision is expected++ def test_an_open_ended_quarantine_over_a_clean_snapshot_needs_a_decision(self):+ _mk_snapshot(self.master_run, identifier="muted")+ QuarantinedIdentifier.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier="muted",+ run_type=RunType.STORYBOOK,+ reason="Known flaky",+ )++ entry = self._entry("muted")++ assert entry is not None+ assert entry.needs_decision is True++ def test_the_activity_strip_is_dense_and_places_recent_variants_last(self):+ _mk_snapshot(self.master_run, identifier="flaky")+ self._mk_variant(identifier="flaky", alternate_hash="today", age=timedelta(0))+ self._mk_variant(identifier="flaky", alternate_hash="old", age=timedelta(days=FLAKINESS_STRIP_DAYS + 10))++ entry = self._entry("flaky")++ assert entry is not None+ assert len(entry.daily_variant_counts) == FLAKINESS_STRIP_DAYS+ assert entry.daily_variant_counts[-1] == 1+ assert sum(entry.daily_variant_counts) == 1++ def test_the_baseline_divider_is_absent_when_the_baseline_moved_before_the_window(self):+ older_run = _mk_run(self.repo, superseded_by=self.master_run)+ _mk_snapshot(older_run, identifier="flaky", result=SnapshotResult.CHANGED)+ Run.objects.filter(id=older_run.id).update(+ created_at=timezone.now() - timedelta(days=FLAKINESS_STRIP_DAYS + 10)+ )+ _mk_snapshot(self.master_run, identifier="flaky")+ self._mk_variant(identifier="flaky", alternate_hash="a")++ entry = self._entry("flaky")++ assert entry is not None+ assert entry.baseline_moved_day_index is None+ assert entry.baseline_age_days is not None+ assert entry.baseline_age_days >= FLAKINESS_STRIP_DAYS++ def test_totals_count_the_whole_population(self):+ _mk_snapshot(self.master_run, identifier="hot")+ _mk_snapshot(self.master_run, identifier="cold")+ _mk_snapshot(self.master_run, identifier="stable")+ self._mk_variant(identifier="hot", alternate_hash="a", age=timedelta(days=1))+ self._mk_variant(identifier="cold", alternate_hash="b", age=timedelta(days=FLAKINESS_RECENT_DAYS + 5))+ QuarantinedIdentifier.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier="hot",+ run_type=RunType.STORYBOOK,+ reason="Known flaky",+ )++ totals = vr_api.get_flakiness_overview(self.repo.id).totals++ assert totals.tracked == 3+ assert totals.listed == 2+ assert totals.unstable == 1+ assert totals.settled == 1+ assert totals.quarantined == 1+ assert totals.by_run_type == {RunType.STORYBOOK: 2}++ def test_endpoint_serializes_the_overview(self):+ _mk_snapshot(self.master_run, identifier="flaky")+ self._mk_variant(identifier="flaky", alternate_hash="a", diff_percentage=0.04)++ url = f"/api/projects/{self.team.id}/visual_review/repos/{self.repo.id}/flakiness/"+ response = self.client.get(url)++ assert response.status_code == 200+ data = response.json()+ assert [entry["identifier"] for entry in data["entries"]] == ["flaky"]+ entry = data["entries"][0]+ assert entry["variant_count"] == 1+ assert entry["flakiness_state"] == FlakinessState.UNSTABLE+ assert len(entry["daily_variant_counts"]) == FLAKINESS_STRIP_DAYS+ assert data["totals"]["tracked"] == 1++ def test_endpoint_404_for_unknown_repo(self):+ url = f"/api/projects/{self.team.id}/visual_review/repos/{uuid4()}/flakiness/"+ response = self.client.get(url)++ assert response.status_code == 404diff --git a/products/visual_review/frontend/components/FlakinessQuarantineCell.tsx b/products/visual_review/frontend/components/FlakinessQuarantineCell.tsxnew file mode 100644index 000000000000..5ab79dac0bc7--- /dev/null+++ b/products/visual_review/frontend/components/FlakinessQuarantineCell.tsx@@ -0,0 +1,31 @@+import { dayjs } from 'lib/dayjs'++import type { FlakinessEntryApi } from '../generated/api.schemas'++function formatExpiry(expiresAt: string | null | undefined): { label: string; isOverdue: boolean } {+ if (!expiresAt) {+ return { label: 'no expiry', isOverdue: false }+ }+ const expiry = dayjs(expiresAt)+ if (expiry.isBefore(dayjs())) {+ return { label: `ran out ${dayjs().diff(expiry, 'day')}d ago`, isOverdue: true }+ }+ return { label: `runs out in ${expiry.diff(dayjs(), 'day')}d`, isOverdue: false }+}++export function QuarantineCell({ entry }: { entry: FlakinessEntryApi }): JSX.Element {+ if (!entry.quarantine) {+ return <span className="text-muted">—</span>+ }+ const expiry = formatExpiry(entry.quarantine.expires_at)+ const author = entry.quarantine.created_by+ return (+ <div className="text-xs max-w-48">+ <div>{entry.quarantine.reason || 'No reason given'}</div>+ <div className="text-[11px] text-muted mt-0.5">+ {author ? `${author.first_name || author.email} · ` : ''}+ <span className={expiry.isOverdue ? 'text-danger font-semibold' : 'font-semibold'}>{expiry.label}</span>+ </div>+ </div>+ )+}diff --git a/products/visual_review/frontend/components/FlakinessStatRow.tsx b/products/visual_review/frontend/components/FlakinessStatRow.tsxnew file mode 100644index 000000000000..d927079606c6--- /dev/null+++ b/products/visual_review/frontend/components/FlakinessStatRow.tsx@@ -0,0 +1,83 @@+export type FlakinessPreset = 'unstable' | 'settled' | 'quarantined' | 'needs_decision'++// Mirrors `FLAKINESS_RECENT_DAYS` in+// `products/visual_review/backend/facade/contracts.py`. Keep in sync, because+// the backend value decides `flakiness_state` and this constant drives the copy.+export const RECENT_VARIANT_WINDOW_DAYS = 7++const COLOR_BY_PRESET: Record<FlakinessPreset, string> = {+ unstable: 'var(--danger)',+ settled: 'var(--warning-dark)',+ quarantined: 'var(--warning)',+ needs_decision: 'var(--primary-3000)',+}++const STATS: Array<{ value: FlakinessPreset; label: string; description: string }> = [+ {+ value: 'unstable',+ label: 'Unstable',+ description: `Rendered a variant in the last ${RECENT_VARIANT_WINDOW_DAYS} days`,+ },+ {+ value: 'settled',+ label: 'Settled',+ description: 'Carries variants, but has been quiet for longer than that',+ },+ {+ value: 'quarantined',+ label: 'Quarantined',+ description: 'Skipped when a run decides pass or fail',+ },+ {+ value: 'needs_decision',+ label: 'Needs a decision',+ description: 'Quarantine ran out, or has been quiet long enough to lift',+ },+]++interface FlakinessStatRowProps {+ counts: Record<FlakinessPreset, number>+ preset: FlakinessPreset+ onChange: (next: FlakinessPreset) => void+}++/**+ * The four populations this scene can show. Every tile is a filter that lands on+ * a workable list, so there is deliberately no "all snapshots" tile: it would+ * repeat the Snapshots tab and open thousands of rows with nothing to act on.+ */+export function FlakinessStatRow({ counts, preset, onChange }: FlakinessStatRowProps): JSX.Element {+ return (+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2">+ {STATS.map((stat) => {+ const active = preset === stat.value+ return (+ <button+ key={stat.value}+ type="button"+ aria-pressed={active}+ data-attr={`visual-review-flakiness-preset-${stat.value}`}+ onClick={() => onChange(stat.value)}+ className={`text-left border rounded p-3 transition-colors flex flex-col gap-1 ${+ active+ ? 'border-primary-3000 bg-primary-3000-button-bg'+ : 'border-border bg-bg-light hover:border-primary-3000-hover'+ }`}+ >+ <div className="text-2xl font-semibold leading-none tabular-nums">+ {counts[stat.value].toLocaleString()}+ </div>+ <div className="flex items-center gap-1.5 text-xs font-semibold mt-1">+ <span+ className="w-2 h-2 rounded-full shrink-0"+ style={{ backgroundColor: COLOR_BY_PRESET[stat.value] }}+ />+ <span className="truncate">{stat.label}</span>+ </div>+ <div className="text-[11px] text-muted leading-tight">{stat.description}</div>+ </button>+ )+ })}+ </div>+ )+}diff --git a/products/visual_review/frontend/components/FlakinessStateCell.tsx b/products/visual_review/frontend/components/FlakinessStateCell.tsxnew file mode 100644index 000000000000..17c3cb650046--- /dev/null+++ b/products/visual_review/frontend/components/FlakinessStateCell.tsx@@ -0,0 +1,24 @@+import { IconWarning } from '@posthog/icons'+import { LemonTag } from '@posthog/lemon-ui'++import type { FlakinessEntryApi } from '../generated/api.schemas'++const STATE_TAG: Record<string, { label: string; type: 'danger' | 'warning' | 'success' }> = {+ unstable: { label: 'Unstable', type: 'danger' },+ settled: { label: 'Settled', type: 'warning' },+ clean: { label: 'Clean', type: 'success' },+}++export function StateCell({ entry }: { entry: FlakinessEntryApi }): JSX.Element {+ const tag = STATE_TAG[entry.flakiness_state] ?? STATE_TAG.clean+ return (+ <div className="flex flex-col gap-1 items-start">+ <LemonTag type={tag.type}>{tag.label}</LemonTag>+ {entry.is_quarantined && (+ <LemonTag type="warning" icon={<IconWarning />}>+ Quarantined+ </LemonTag>+ )}+ </div>+ )+}diff --git a/products/visual_review/frontend/components/FlakinessVariantsCell.tsx b/products/visual_review/frontend/components/FlakinessVariantsCell.tsxnew file mode 100644index 000000000000..4a83a3f41f5a--- /dev/null+++ b/products/visual_review/frontend/components/FlakinessVariantsCell.tsx@@ -0,0 +1,43 @@+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import type { FlakinessEntryApi } from '../generated/api.schemas'+import { VariantStrip } from './VariantStrip'++// Sub-pixel jitter and a small real change both round to tiny percentages, so+// two decimals is the smallest precision that keeps them apart.+function formatJitter(avgDiffPercentage: number | null | undefined): string | null {+ if (avgDiffPercentage === null || avgDiffPercentage === undefined) {+ return null+ }+ return `${avgDiffPercentage.toFixed(2)}% avg`+}++function formatBaselineAge(baselineAgeDays: number | null | undefined): string {+ if (baselineAgeDays === null || baselineAgeDays === undefined) {+ return 'baseline never moved'+ }+ return `baseline ${baselineAgeDays}d old`+}++export function VariantsCell({ entry }: { entry: FlakinessEntryApi }): JSX.Element {+ const jitter = formatJitter(entry.avg_diff_percentage)+ return (+ <div className="flex flex-col gap-1 items-end">+ <Tooltip+ title={`This snapshot is currently allowed to produce ${entry.variant_count} different ${+ entry.variant_count === 1 ? 'image' : 'images'+ } and still pass`}+ >+ <span className="font-mono font-semibold tabular-nums">{entry.variant_count.toLocaleString()}</span>+ </Tooltip>+ <VariantStrip+ dailyCounts={entry.daily_variant_counts}+ baselineMovedDayIndex={entry.baseline_moved_day_index ?? null}+ />+ <span className="text-[11px] text-muted font-mono">+ {jitter ? `${jitter} · ` : ''}+ {formatBaselineAge(entry.baseline_age_days)}+ </span>+ </div>+ )+}diff --git a/products/visual_review/frontend/components/QuarantineAction.tsx b/products/visual_review/frontend/components/QuarantineAction.tsxindex 97ba05afc308..ec8b779f885f 100644--- a/products/visual_review/frontend/components/QuarantineAction.tsx+++ b/products/visual_review/frontend/components/QuarantineAction.tsx@@ -88,6 +88,13 @@ interface QuarantineActionProps {* Forwarded to the parent via `onQuarantine` so the backend can store it.*/sourceRunId?: string | null+ /**+ * Set while a quarantine write for this identifier is in flight. The create+ * endpoint supersedes the prior active row, so a second submit writes a+ * second record. Blocks the trigger rather than the modal's submit, because+ * the modal closes as soon as the parent takes over.+ */+ pendingReason?: string | null}/**@@ -103,6 +110,7 @@ export function QuarantineAction({initialReason,initialExpiresAt,sourceRunId,+ pendingReason,}: QuarantineActionProps): JSX.Element {const isExtend = mode === 'extend'const copy = COPY[mode]@@ -142,7 +150,14 @@ export function QuarantineAction({return (<div>- <LemonButton type="secondary" size="small" onClick={() => setIsOpen(true)} data-attr={copy.dataAttrOpen}>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setIsOpen(true)}+ data-attr={copy.dataAttrOpen}+ loading={!!pendingReason}+ disabledReason={pendingReason ?? undefined}+ >{triggerLabel ?? copy.triggerLabel}</LemonButton><LemonModaldiff --git a/products/visual_review/frontend/components/RepoSwitcher.tsx b/products/visual_review/frontend/components/RepoSwitcher.tsxindex 3dc62b60de57..f2364ba0890a 100644--- a/products/visual_review/frontend/components/RepoSwitcher.tsx+++ b/products/visual_review/frontend/components/RepoSwitcher.tsx@@ -19,6 +19,7 @@ interface RepoSwitcherProps {const TAB_TO_PATH: Record<VisualReviewTabKey, (repoId: string) => string> = {runs: (repoId) => `/visual_review/repos/${repoId}/runs`,snapshots: (repoId) => `/visual_review/repos/${repoId}/snapshots`,+ flakiness: (repoId) => `/visual_review/repos/${repoId}/flakiness`,}export function RepoSwitcher({ repoId, activeTab }: RepoSwitcherProps): JSX.Element | null {diff --git a/products/visual_review/frontend/components/VariantStrip.tsx b/products/visual_review/frontend/components/VariantStrip.tsxnew file mode 100644index 000000000000..9008d863dac5--- /dev/null+++ b/products/visual_review/frontend/components/VariantStrip.tsx@@ -0,0 +1,65 @@+import { dayjs } from 'lib/dayjs'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++interface VariantStripProps {+ /** Variants recorded per day, oldest first. The backend always sends a dense series. */+ dailyCounts: number[]+ /**+ * Position of the baseline move inside the series, or null when it moved before the+ * window opened. Days before it are drawn faint: their variants were recorded against+ * the old baseline hash and can never match again.+ */+ baselineMovedDayIndex: number | null+}++// Every day that recorded a variant gets the same full-strength tick. A tick is+// 3px wide, so dimming single-variant days to encode magnitude made the most+// common case the hardest to see. Magnitude is already in the count beside the+// strip; the strip only has to answer when.+function tickClassName(count: number, isBeforeBaselineMove: boolean): string {+ if (isBeforeBaselineMove) {+ return count > 0 ? 'bg-border-bold' : 'bg-border-light'+ }+ return count > 0 ? 'bg-danger' : 'bg-border'+}++/**+ * Day-by-day view of when a snapshot recorded new allowed variants.+ *+ * Exists because a bare count cannot separate a burst from a chronic flake: a+ * story that produced twenty variants in one week and then stopped is a change+ * that settled, and one that produces two a day forever is not.+ */+export function VariantStrip({ dailyCounts, baselineMovedDayIndex }: VariantStripProps): JSX.Element {+ const total = dailyCounts.reduce((sum, count) => sum + count, 0)+ const windowStart = dayjs().subtract(dailyCounts.length - 1, 'day')+ const summary =+ total === 0+ ? `No new variants in the last ${dailyCounts.length} days`+ : `${total} ${total === 1 ? 'variant' : 'variants'} in the last ${dailyCounts.length} days, since ${windowStart.format('MMM D')}`++ return (+ <Tooltip+ title={+ <>+ <div>{summary}</div>+ {baselineMovedDayIndex !== null && (+ <div>Faint days are from before the baseline moved, so they no longer count</div>+ )}+ </>+ }+ >+ <div className="flex gap-px items-stretch h-3" aria-label={summary}>+ {dailyCounts.map((count, index) => (+ <div+ key={index}+ className={`w-[3px] ${tickClassName(+ count,+ baselineMovedDayIndex !== null && index < baselineMovedDayIndex+ )}`}+ />+ ))}+ </div>+ </Tooltip>+ )+}diff --git a/products/visual_review/frontend/components/VisualReviewTabs.tsx b/products/visual_review/frontend/components/VisualReviewTabs.tsxindex e24d28d8ba29..17ed46ae605a 100644--- a/products/visual_review/frontend/components/VisualReviewTabs.tsx+++ b/products/visual_review/frontend/components/VisualReviewTabs.tsx@@ -1,7 +1,7 @@import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { urls } from 'scenes/urls'-export type VisualReviewTabKey = 'runs' | 'snapshots'+export type VisualReviewTabKey = 'runs' | 'snapshots' | 'flakiness'// Top-level tab strip for a repo workspace. Both tabs are repo-scoped and// share the same `:repoId` segment, so this component is purely@@ -30,6 +30,11 @@ export function VisualReviewTabs({label: 'Snapshots',link: urls.visualReviewSnapshotOverview(repoId),},+ {+ key: 'flakiness' satisfies VisualReviewTabKey,+ label: 'Flakiness',+ link: urls.visualReviewFlakiness(repoId),+ },]}/>)diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.tsindex f5f76b68c68c..01a065f4a1fc 100644--- a/products/visual_review/frontend/generated/api.schemas.ts+++ b/products/visual_review/frontend/generated/api.schemas.ts@@ -110,6 +110,88 @@ export interface BaselineOverviewApi {generated_at: string}+/**+ * * `unstable` - unstable+ * * `settled` - settled+ * * `clean` - clean+ */+export type FlakinessStateEnumApi = (typeof FlakinessStateEnumApi)[keyof typeof FlakinessStateEnumApi]++export const FlakinessStateEnumApi = {+ Unstable: 'unstable',+ Settled: 'settled',+ Clean: 'clean',+} as const++export interface FlakinessEntryApi {+ /** Distinct alternate hashes the classifier can still match for this snapshot's current baseline. Reads as how many different images this snapshot is currently allowed to produce. Resets when the baseline moves, because tolerations recorded against an old baseline hash can never match again. */+ variant_count: number+ /**+ * Last default-branch run that rendered one of those variants. This is not when a variant was first recorded: a snapshot can cycle through variants it already recorded without adding a new one, and that case still flakes on every run. Null when no run matched one.+ * @nullable+ */+ last_flaked_at?: string | null+ /**+ * Mean fraction of pixels that differed across those variants. Separates sub-pixel noise from a small but real rendering change.+ * @nullable+ */+ avg_diff_percentage?: number | null+ /**+ * Days since the first default-branch run that compared against the current baseline, which is when that baseline took effect. Context for `variant_count`: the same count against a four-day-old baseline is far worse than against a six-month-old one.+ * @nullable+ */+ baseline_age_days?: number | null+ /** Variants recorded per day over the last 30 days, oldest first. Always that length, so a fixed time axis can be rendered. */+ daily_variant_counts: number[]+ /**+ * Index into `daily_variant_counts` where the baseline moved. Null when it moved before the window opened, which is the common case.+ * @nullable+ */+ baseline_moved_day_index?: number | null+ /** `unstable` when a run rendered a variant inside the recency window, new or already known, `settled` when variants exist against this baseline but none recently, `clean` when none exist. A `clean` entry is always a quarantined one, because an unquarantined snapshot with no variants is not listed at all.+ *+ * * `unstable` - unstable+ * * `settled` - settled+ * * `clean` - clean */+ flakiness_state: FlakinessStateEnumApi+ /** True when an active quarantine has run out, is about to, or covers a snapshot that no longer produces variants. All three mean a human has to extend it or lift it. */+ needs_decision: boolean+ /** Active quarantine details when `is_quarantined` is true. Null otherwise. */+ quarantine?: BaselineQuarantineSummaryApi | null+ identifier: string+ run_type: string+ /** @nullable */+ browser: string | null+ /** @nullable */+ thumbnail_hash: string | null+ /** @nullable */+ width: number | null+ /** @nullable */+ height: number | null+ is_quarantined: boolean+}++export type FlakinessTotalsApiByRunType = { [key: string]: number }++export interface FlakinessTotalsApi {+ /** Identifiers with an entry in `entries`. */+ listed: number+ /** Identifiers with a current baseline, listed or not. The denominator that says how much of the repo renders consistently. */+ tracked: number+ by_run_type: FlakinessTotalsApiByRunType+ unstable: number+ settled: number+ quarantined: number+ needs_decision: number+}++export interface FlakinessOverviewApi {+ entries: FlakinessEntryApi[]+ totals: FlakinessTotalsApi+ truncated: boolean+ generated_at: string+}+export interface QuarantinedIdentifierEntryApi {created_by?: UserBasicInfoApi | null/** Run whose failing snapshot prompted this quarantine. Null when quarantine was created without run context. */@@ -463,6 +545,13 @@ export type VisualReviewReposQuarantineListParams = {run_type?: string}+export type VisualReviewReposThumbnailsRetrieveParams = {+ /**+ * Narrow the lookup to one run type. The same identifier under two run types is two different images, so omit this only when the caller shows one run type.+ */+ run_type?: string+}+export type VisualReviewReposRunsListParams = {/*** Number of results to return per page.diff --git a/products/visual_review/frontend/generated/api.ts b/products/visual_review/frontend/generated/api.tsindex aec3bed0c147..36866b8679e0 100644--- a/products/visual_review/frontend/generated/api.ts+++ b/products/visual_review/frontend/generated/api.ts@@ -18,6 +18,7 @@ import type {CreateRunResultApi,FinalizeResultApi,FinalizeRunRequestInputApi,+ FlakinessOverviewApi,MarkToleratedInputApi,PaginatedQuarantinedIdentifierEntryListApi,PaginatedRepoListApi,@@ -37,6 +38,7 @@ import type {VisualReviewReposQuarantineListParams,VisualReviewReposRunsListParams,VisualReviewReposSnapshotsListParams,+ VisualReviewReposThumbnailsRetrieveParams,VisualReviewRunsListParams,VisualReviewRunsSnapshotHistoryListParams,VisualReviewRunsSnapshotsListParams,@@ -150,6 +152,24 @@ export const visualReviewReposBaselinesRetrieve = async (})}+export const getVisualReviewReposFlakinessRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/visual_review/repos/${id}/flakiness/`+}++/**+ * Snapshots in a repo whose rendering cannot be trusted: those carrying at least one live tolerated variant against their current baseline, and those under an active quarantine. Everything else is omitted, so this is far smaller than the baselines universe; `totals.tracked` gives the full denominator. Variant counts are scoped to the current baseline hash, because a toleration recorded against an earlier baseline can never match again. Capped at 2000 entries, which sets `truncated`. Filtering, faceting and search are done client-side; this endpoint takes no filter query params.+ */+export const visualReviewReposFlakinessRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<FlakinessOverviewApi> => {+ return apiMutator<FlakinessOverviewApi>(getVisualReviewReposFlakinessRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}+export const getVisualReviewReposQuarantineListUrl = (projectId: string,id: string,@@ -232,8 +252,25 @@ export const visualReviewReposQuarantineExpireCreate = async (})}-export const getVisualReviewReposThumbnailsRetrieveUrl = (projectId: string, id: string, identifier: string) => {- return `/api/projects/${projectId}/visual_review/repos/${id}/thumbnails/${identifier}/`+export const getVisualReviewReposThumbnailsRetrieveUrl = (+ projectId: string,+ id: string,+ identifier: string,+ params?: VisualReviewReposThumbnailsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/visual_review/repos/${id}/thumbnails/${identifier}/?${stringifiedParams}`+ : `/api/projects/${projectId}/visual_review/repos/${id}/thumbnails/${identifier}/`}/**@@ -243,9 +280,10 @@ export const visualReviewReposThumbnailsRetrieve = async (projectId: string,id: string,identifier: string,+ params?: VisualReviewReposThumbnailsRetrieveParams,options?: RequestInit): Promise<void> => {- return apiMutator<void>(getVisualReviewReposThumbnailsRetrieveUrl(projectId, id, identifier), {+ return apiMutator<void>(getVisualReviewReposThumbnailsRetrieveUrl(projectId, id, identifier, params), {...options,method: 'GET',})diff --git a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsxnew file mode 100644index 000000000000..5579732a97dd--- /dev/null+++ b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx@@ -0,0 +1,170 @@+import type { Meta, StoryObj } from '@storybook/react'++import { App } from 'scenes/App'++import { mswDecorator } from '~/mocks/browser'++import type { FlakinessEntryApi, FlakinessOverviewApi, RepoApi } from '../generated/api.schemas'++const REPO_ID = '00000000-0000-0000-0000-0000000000bb'++const repo: RepoApi = {+ id: REPO_ID,+ team_id: 1,+ repo_external_id: 99999,+ repo_full_name: 'PostHog/posthog',+ baseline_file_paths: {},+ enable_pr_comments: true,+ created_at: '2026-06-10T00:00:00Z',+}++// Dense, sparse and silent 30-day series, so the strip renders all three shapes.+function series(pattern: 'chronic' | 'burst' | 'silent'): number[] {+ return Array.from({ length: 30 }, (_, day) => {+ if (pattern === 'silent') {+ return 0+ }+ if (pattern === 'burst') {+ // Two variants after the baseline moved on day 25, nothing before it.+ return day === 27 || day === 29 ? 1 : 0+ }+ return day % 3 === 0 ? 2 : day % 3 === 1 ? 1 : 0+ })+}++const entry = (overrides: Partial<FlakinessEntryApi>): FlakinessEntryApi => ({+ identifier: 'components-hogcharts-piechart--donut--dark',+ run_type: 'storybook',+ browser: null,+ thumbnail_hash: null,+ width: 320,+ height: 200,+ variant_count: 41,+ last_flaked_at: '2026-06-10T09:00:00Z',+ avg_diff_percentage: 0.041,+ baseline_age_days: 34,+ daily_variant_counts: series('chronic'),+ baseline_moved_day_index: null,+ flakiness_state: 'unstable',+ is_quarantined: false,+ needs_decision: false,+ quarantine: null,+ ...overrides,+})++const overview: FlakinessOverviewApi = {+ entries: [+ entry({}),+ entry({+ identifier: 'components-playerinspector-itemevent--default--dark',+ variant_count: 33,+ avg_diff_percentage: 0.112,+ baseline_age_days: 61,+ is_quarantined: true,+ needs_decision: true,+ quarantine: {+ id: '00000000-0000-0000-0000-0000000000c1',+ reason: 'Non-deterministic rendering (animations, timestamps)',+ expires_at: '2026-06-07T00:00:00Z',+ created_at: '2026-05-08T00:00:00Z',+ created_by: { id: 1, first_name: 'Julian', email: '[email protected]' },+ source_run: null,+ },+ }),+ entry({+ identifier: 'charts-heatmap--linear-color-scale--light',+ variant_count: 2,+ avg_diff_percentage: 0.021,+ baseline_age_days: 4,+ daily_variant_counts: series('burst'),+ baseline_moved_day_index: 25,+ last_flaked_at: '2026-06-09T09:00:00Z',+ }),+ ],+ totals: {+ listed: 3,+ tracked: 4494,+ unstable: 231,+ settled: 604,+ quarantined: 47,+ needs_decision: 12,+ by_run_type: { storybook: 3 },+ },+ truncated: false,+ generated_at: '2026-06-10T10:00:00Z',+}++const emptyOverview: FlakinessOverviewApi = {+ entries: [],+ totals: {+ listed: 0,+ tracked: 4494,+ unstable: 0,+ settled: 0,+ quarantined: 0,+ needs_decision: 0,+ by_run_type: {},+ },+ truncated: false,+ generated_at: '2026-06-10T10:00:00Z',+}++const emptyList = { count: 0, next: null, previous: null, results: [] }++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Visual review/Flakiness',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2026-06-10',+ pageUrl: `/visual_review/repos/${REPO_ID}/flakiness`,+ testOptions: { waitForSelector: '[data-attr="visual-review-flakiness-preset-unstable"]' },+ },+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/visual_review/repos/${REPO_ID}/`]: repo,+ [`/api/projects/:team_id/visual_review/repos/${REPO_ID}/flakiness/`]: overview,+ [`/api/projects/:team_id/visual_review/repos/${REPO_ID}/quarantine/`]: emptyList,+ '/api/projects/:team_id/visual_review/repos/': { ...emptyList, count: 1, results: [repo] },+ },+ }),+ ],+}+export default meta++// Chronic drip, a quarantine that has run out while the snapshot still flakes,+// and a burst against a four-day-old baseline.+export const Unstable: StoryObj = {}++// A repo whose snapshots all render deterministically. Two of the three repos in+// this project land here, so it is worth holding to the same standard.+export const NothingToShow: StoryObj = {+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/visual_review/repos/${REPO_ID}/flakiness/`]: emptyOverview,+ },+ }),+ ],+}++// A failed load has to look different from an empty repo. Both leave the scene+// with no overview, and rendering NothingToShow here would claim every snapshot+// is stable on the strength of a request that never answered.+export const CouldNotLoad: StoryObj = {+ // The stat tiles are hidden on this screen, so the meta-level selector never+ // appears and the snapshot would wait for it forever.+ parameters: { testOptions: { waitForSelector: '[data-attr="visual-review-flakiness-retry"]' } },+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/visual_review/repos/${REPO_ID}/flakiness/`]: [+ 500,+ { detail: 'Upstream timed out' },+ ],+ },+ }),+ ],+}diff --git a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsxnew file mode 100644index 000000000000..1d2e277cc42d--- /dev/null+++ b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx@@ -0,0 +1,342 @@+import { useActions, useValues } from 'kea'++import { IconGear } from '@posthog/icons'+import {+ LemonBanner,+ LemonButton,+ LemonInput,+ LemonSegmentedButton,+ LemonSkeleton,+ LemonTable,+ Link,+} from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { QuarantineCell } from '../components/FlakinessQuarantineCell'+import { StateCell } from '../components/FlakinessStateCell'+import { FlakinessStatRow } from '../components/FlakinessStatRow'+import { VariantsCell } from '../components/FlakinessVariantsCell'+import { QuarantineAction } from '../components/QuarantineAction'+import { RepoSwitcher } from '../components/RepoSwitcher'+import { SnapshotFacetSidebar } from '../components/SnapshotFacetSidebar'+import { VisualReviewTabs } from '../components/VisualReviewTabs'+import type { FlakinessEntryApi } from '../generated/api.schemas'+import {+ DecoratedEntry,+ VisualReviewFlakinessSceneLogicProps,+ visualReviewFlakinessSceneLogic,+} from './visualReviewFlakinessSceneLogic'++export const scene: SceneExport = {+ component: VisualReviewFlakinessScene,+ logic: visualReviewFlakinessSceneLogic,+ paramsToProps: ({ params: { repoId } }): VisualReviewFlakinessSceneLogicProps => ({+ repoId: repoId || '',+ }),+}++function formatLastSeen(lastFlakedAt: string | null | undefined): string {+ if (!lastFlakedAt) {+ return 'never'+ }+ const days = dayjs().diff(dayjs(lastFlakedAt), 'day')+ return days === 0 ? 'today' : `${days}d ago`+}++export function VisualReviewFlakinessScene(): JSX.Element {+ const {+ overview,+ overviewLoading,+ repo,+ repoId,+ filteredEntries,+ statCounts,+ facetGroups,+ facetSelection,+ filters,+ thumbnailBasePath,+ loadError,+ pendingQuarantineKeys,+ } = useValues(visualReviewFlakinessSceneLogic)+ const {+ loadOverview,+ setPreset,+ toggleType,+ toggleArea,+ setSearch,+ setSort,+ clearAllFilters,+ quarantineIdentifier,+ unquarantineIdentifier,+ } = useActions(visualReviewFlakinessSceneLogic)++ const isFiltered = filters.typeKeys.length > 0 || filters.areas.length > 0 || filters.search.length > 0+ const hasPopulation = (overview?.entries.length ?? 0) > 0++ const confirmLift = (entry: FlakinessEntryApi): void => {+ LemonDialog.open({+ title: 'Lift this quarantine?',+ description: 'Runs will gate on this snapshot again, so a rendering difference will fail them.',+ primaryButton: {+ children: 'Lift quarantine',+ status: 'danger',+ onClick: () => unquarantineIdentifier(entry.identifier, entry.run_type),+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ return (+ <SceneContent>+ <SceneTitleSection+ name={repo?.repo_full_name ?? 'Visual review'}+ resourceType={{ type: 'visual_review' }}+ actions={+ <div className="flex gap-2 items-center">+ <RepoSwitcher repoId={repoId} activeTab="flakiness" />+ <LemonButton size="small" type="secondary" icon={<IconGear />} to={urls.visualReviewSettings()}>+ Settings+ </LemonButton>+ </div>+ }+ />+ <VisualReviewTabs activeKey="flakiness" repoId={repoId} />++ <LemonBanner type="info">+ When a snapshot renders differently but stays under the diff threshold, the run accepts it and remembers+ the new image as an allowed variant. Variants are counted against the current baseline only. When a+ snapshot changes for real, its baseline moves and the count starts over.+ </LemonBanner>++ {!loadError && <FlakinessStatRow counts={statCounts} preset={filters.preset} onChange={setPreset} />}++ {overview && (+ <div className="text-xs text-muted">+ <span className="font-semibold text-default">+ {overview.totals.listed.toLocaleString()} snapshots+ </span>{' '}+ have something to show here, out of {overview.totals.tracked.toLocaleString()} with a current+ baseline. The rest have no variants against their baseline and no quarantine.+ </div>+ )}++ {overview?.truncated && (+ <LemonBanner type="info">+ Showing the {overview.entries.length.toLocaleString()} snapshots with the most variants. This repo+ has more than the page can list, so filtering here only searches the ones above.+ </LemonBanner>+ )}++ {hasPopulation && (+ <div className="flex items-center gap-2 flex-wrap">+ <LemonInput+ type="search"+ placeholder="Filter by name…"+ value={filters.search}+ onChange={(value) => setSearch(value)}+ className="flex-1 min-w-60"+ />+ <span className="text-xs text-muted">Sort</span>+ <LemonSegmentedButton+ size="small"+ value={filters.sort}+ onChange={(value) => setSort(value as 'variants' | 'recent')}+ options={[+ { value: 'variants', label: 'Most variants' },+ { value: 'recent', label: 'Most recent' },+ ]}+ />+ {isFiltered && (+ <button+ type="button"+ className="text-xs text-muted hover:text-default"+ onClick={clearAllFilters}+ >+ Clear all+ </button>+ )}+ </div>+ )}++ {overviewLoading && !overview ? (+ <div className="flex flex-col gap-2">+ {Array.from({ length: 8 }).map((_, index) => (+ <LemonSkeleton key={index} className="h-12 w-full" />+ ))}+ </div>+ ) : loadError ? (+ <LemonBanner+ type="error"+ action={{+ children: 'Try again',+ onClick: () => loadOverview(),+ 'data-attr': 'visual-review-flakiness-retry',+ }}+ >+ Could not load flakiness for this repo. {loadError}+ </LemonBanner>+ ) : !hasPopulation ? (+ <div className="flex flex-col items-center justify-center py-20 gap-2 text-center">+ <p className="m-0 font-semibold">Every snapshot renders the same way every time</p>+ <p className="m-0 text-xs text-muted max-w-md">+ Snapshots show up here once a run accepts a variant of one, or once someone quarantines one.+ Nothing in this repo has done either.+ </p>+ </div>+ ) : (+ <div className="flex flex-col sm:flex-row gap-6 items-start">+ <SnapshotFacetSidebar+ groups={facetGroups}+ selection={facetSelection}+ onToggle={(group, value) => {+ if (group === 'type') {+ toggleType(value)+ } else if (group === 'area') {+ toggleArea(value)+ }+ }}+ />++ <div className="flex-1 min-w-0">+ <LemonTable+ dataSource={filteredEntries}+ rowKey={(entry: DecoratedEntry) => `${entry.run_type}::${entry.identifier}`}+ emptyState="No snapshots match these filters."+ columns={[+ {+ title: 'Snapshot',+ key: 'identifier',+ render: (_, entry: DecoratedEntry) => (+ <div className="flex gap-2 items-start min-w-0">+ {entry.thumbnail_hash && thumbnailBasePath && (+ <img+ src={`${thumbnailBasePath}/${encodeURIComponent(+ entry.identifier+ )}/?run_type=${encodeURIComponent(entry.run_type)}`}+ alt=""+ loading="lazy"+ className="w-10 h-7 object-cover rounded border border-border shrink-0"+ />+ )}+ <div className="min-w-0">+ <Link+ to={urls.visualReviewSnapshotHistory(+ repoId,+ entry.run_type,+ entry.identifier+ )}+ className="font-mono text-xs break-all"+ >+ {entry.identifier}+ </Link>+ <div className="text-[11px] text-muted mt-0.5">+ {entry.run_type} · {entry._area}+ </div>+ </div>+ </div>+ ),+ },+ {+ title: 'State',+ key: 'state',+ width: 108,+ render: (_, entry: DecoratedEntry) => <StateCell entry={entry} />,+ },+ {+ title: 'Allowed variants',+ key: 'variants',+ align: 'right',+ width: 190,+ render: (_, entry: DecoratedEntry) => <VariantsCell entry={entry} />,+ },+ {+ title: 'Last seen',+ key: 'last_seen',+ align: 'right',+ width: 100,+ render: (_, entry: DecoratedEntry) => (+ // Highlight follows the server's verdict. Deriving it from+ // the day count here drifts at the window edge, because+ // dayjs truncates to whole days and the server compares+ // exact timestamps.+ <span+ className={`font-mono text-xs ${+ entry.flakiness_state === 'unstable'+ ? 'text-danger font-semibold'+ : 'text-muted'+ }`}+ >+ {formatLastSeen(entry.last_flaked_at)}+ </span>+ ),+ },+ {+ title: 'Quarantine',+ key: 'quarantine',+ render: (_, entry: DecoratedEntry) => <QuarantineCell entry={entry} />,+ },+ {+ title: '',+ key: 'actions',+ width: 150,+ render: (_, entry: DecoratedEntry) => {+ const pending = pendingQuarantineKeys.includes(+ `${entry.run_type}::${entry.identifier}`+ )+ ? 'Saving…'+ : null+ return (+ <div className="flex gap-1 justify-end">+ <QuarantineAction+ pendingReason={pending}+ identifier={entry.identifier}+ mode={entry.is_quarantined ? 'extend' : 'create'}+ triggerLabel={entry.is_quarantined ? 'Extend' : 'Quarantine'}+ initialReason={entry.quarantine?.reason}+ initialExpiresAt={entry.quarantine?.expires_at}+ sourceRunId={entry.quarantine?.source_run?.id ?? null}+ onQuarantine={(reason, identifiers, expiresAt, sourceRunId) => {+ identifiers.forEach((identifier) =>+ quarantineIdentifier(+ identifier,+ entry.run_type,+ reason,+ expiresAt,+ sourceRunId+ )+ )+ }}+ />+ {entry.is_quarantined && (+ <LemonButton+ size="xsmall"+ type="secondary"+ data-attr="visual-review-flakiness-lift"+ onClick={() => confirmLift(entry)}+ loading={!!pending}+ disabledReason={pending ?? undefined}+ >+ Lift+ </LemonButton>+ )}+ </div>+ )+ },+ },+ ]}+ />+ </div>+ </div>+ )}+ </SceneContent>+ )+}++export default VisualReviewFlakinessScenediff --git a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.tsnew file mode 100644index 000000000000..db5f8fc01653--- /dev/null+++ b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts@@ -0,0 +1,123 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { FlakinessOverviewApi } from '../generated/api.schemas'+import { visualReviewFlakinessSceneLogic } from './visualReviewFlakinessSceneLogic'++const REPO_ID = '00000000-0000-0000-0000-0000000000bb'+const FLAKINESS_URL = `/api/projects/:team_id/visual_review/repos/${REPO_ID}/flakiness/`++const overview: FlakinessOverviewApi = {+ entries: [],+ totals: {+ listed: 0,+ tracked: 4494,+ unstable: 231,+ settled: 604,+ quarantined: 47,+ needs_decision: 12,+ by_run_type: {},+ },+ truncated: false,+ generated_at: '2026-06-10T10:00:00Z',+}++describe('visualReviewFlakinessSceneLogic', () => {+ let logic: ReturnType<typeof visualReviewFlakinessSceneLogic.build>+ let overviewRequests = 0++ afterEach(() => {+ logic?.unmount()+ })++ describe('when the overview loads', () => {+ beforeEach(() => {+ initKeaTests()+ useMocks({ get: { [FLAKINESS_URL]: overview } })+ logic = visualReviewFlakinessSceneLogic({ repoId: REPO_ID })+ logic.mount()+ })++ it('reports no error', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.loadError).toBeNull()+ expect(logic.values.overview).toEqual(overview)+ })++ // Server totals, not counts over the returned entries, so the tiles stay+ // right when the payload is capped.+ it('takes the stat counts from server totals rather than the listed entries', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.statCounts).toEqual({+ unstable: 231,+ settled: 604,+ quarantined: 47,+ needs_decision: 12,+ })+ })+ })++ describe('while quarantine writes are in flight', () => {+ beforeEach(() => {+ initKeaTests()+ overviewRequests = 0+ useMocks({+ get: {+ [FLAKINESS_URL]: () => {+ overviewRequests += 1+ return overview+ },+ },+ post: { '/api/projects/:team_id/visual_review/repos/:id/quarantine/:runType/': { ok: true } },+ })+ logic = visualReviewFlakinessSceneLogic({ repoId: REPO_ID })+ logic.mount()+ })++ // The sibling checkbox submits the light and dark identifiers together,+ // so one row can have two writes running. Tracking a single key let the+ // first response re-enable a row whose own write was still going.+ it('keeps a row pending until every one of its writes settles', async () => {+ logic.actions.quarantineIdentifier('story--dark', 'storybook', 'flaky', null, null)+ logic.actions.quarantineIdentifier('story--dark', 'storybook', 'flaky', null, null)+ expect(logic.values.pendingQuarantineKeys).toEqual(['storybook::story--dark', 'storybook::story--dark'])++ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.pendingQuarantineKeys).toEqual([])+ })++ // Each write used to reload on its own success, so the earlier reload+ // could read before the sibling committed and land last, replacing the+ // fresh response with a half-applied one.+ it('reloads once, after the last write settles', async () => {+ overviewRequests = 0+ await expectLogic(logic, () => {+ logic.actions.quarantineIdentifier('story--dark', 'storybook', 'flaky', null, null)+ logic.actions.quarantineIdentifier('story--light', 'storybook', 'flaky', null, null)+ }).toFinishAllListeners()++ expect(logic.values.pendingQuarantineKeys).toEqual([])+ expect(overviewRequests).toBe(1)+ })+ })++ describe('when the overview fails to load', () => {+ beforeEach(() => {+ initKeaTests()+ useMocks({ get: { [FLAKINESS_URL]: () => [500, { detail: 'Upstream timed out' }] } })+ logic = visualReviewFlakinessSceneLogic({ repoId: REPO_ID })+ logic.mount()+ })++ // A failed load leaves `overview` null, which is what an empty repo also+ // looks like. Without `loadError` the scene renders "every snapshot+ // renders the same way every time" over a request that never answered.+ it('records the error so the scene can tell it from an empty repo', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.loadError).not.toBeNull()+ expect(logic.values.overview).toBeNull()+ })+ })+})diff --git a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.tsnew file mode 100644index 000000000000..e2d134334fc0--- /dev/null+++ b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts@@ -0,0 +1,519 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { actionToUrl, urlToAction } from 'kea-router'++import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { teamLogic } from 'scenes/teamLogic'++import { Breadcrumb } from '~/types'++import type { FlakinessPreset } from '../components/FlakinessStatRow'+import type { FacetBucket, FacetGroups, FacetSelection } from '../components/SnapshotFacetSidebar'+import {+ visualReviewReposFlakinessRetrieve,+ visualReviewReposQuarantineCreate,+ visualReviewReposQuarantineExpireCreate,+} from '../generated/api'+import type { FlakinessEntryApi, FlakinessOverviewApi, RepoApi } from '../generated/api.schemas'+import { parseArea, runTypeLabel } from '../lib/parseIdentifier'+import { visualReviewRepoLogic } from './visualReviewRepoLogic'++export interface VisualReviewFlakinessSceneLogicProps {+ repoId: string+}++// "Most variants" ranks by severity, "most recent" by urgency. A snapshot with+// forty variants last seen three weeks ago and one with eight seen today are+// both worth attention, and neither order answers for the other.+export type FlakinessSort = 'variants' | 'recent'++export type Filters = {+ preset: FlakinessPreset+ typeKeys: string[]+ areas: string[]+ search: string+ sort: FlakinessSort+}++// Unstable is the landing slice: it is the only one that means something is+// wrong right now.+const EMPTY_FILTERS: Filters = {+ preset: 'unstable',+ typeKeys: [],+ areas: [],+ search: '',+ sort: 'variants',+}++// Collapses run_type + browser into one facet key, matching how the snapshots+// overview buckets the same two seed conventions: `run_type=playwright` with+// the browser in metadata, or `run_type=playwright-<browser>` in the column.+function typeKeyOf(entry: FlakinessEntryApi): string {+ const runType = entry.run_type.toLowerCase()+ if (runType === 'playwright' && entry.browser) {+ return `playwright::${entry.browser}`+ }+ if (runType.startsWith('playwright-')) {+ return `playwright::${runType.slice('playwright-'.length)}`+ }+ return entry.run_type+}++function typeLabelOf(key: string): string {+ if (key.startsWith('playwright::')) {+ return runTypeLabel('playwright', key.slice('playwright::'.length))+ }+ return key+}++function matchesPreset(entry: DecoratedEntry, preset: FlakinessPreset): boolean {+ switch (preset) {+ case 'unstable':+ return entry.flakiness_state === 'unstable'+ case 'settled':+ return entry.flakiness_state === 'settled'+ case 'quarantined':+ return entry.is_quarantined+ case 'needs_decision':+ return entry.needs_decision+ }+}++function bucketize(values: string[], labelOf: (value: string) => string = (value) => value): FacetBucket[] {+ const counts = new Map<string, number>()+ for (const value of values) {+ counts.set(value, (counts.get(value) ?? 0) + 1)+ }+ return [...counts.entries()]+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))+ .map(([value, count]) => ({ value, count, label: labelOf(value) }))+}++// Area and type key are parsed once per entry so filtering does not re-derive+// them on every keystroke. Exported so kea-typegen can resolve the shape.+export type DecoratedEntry = FlakinessEntryApi & {+ _area: string+ _typeKey: string+}++type FilterDimension = keyof Filters++// One place for the filter rules. `filteredEntries` calls it with nothing+// excluded; `facetGroups` calls it once per dimension with that dimension+// excluded, so a facet's own rows do not zero each other out.+function applyFilters(+ entries: readonly DecoratedEntry[],+ filters: Filters,+ exclude?: FilterDimension+): DecoratedEntry[] {+ const search = filters.search.trim().toLowerCase()+ return entries.filter((entry) => {+ if (exclude !== 'preset' && !matchesPreset(entry, filters.preset)) {+ return false+ }+ if (exclude !== 'typeKeys' && filters.typeKeys.length && !filters.typeKeys.includes(entry._typeKey)) {+ return false+ }+ if (exclude !== 'areas' && filters.areas.length && !filters.areas.includes(entry._area)) {+ return false+ }+ if (exclude !== 'search' && search && !entry.identifier.toLowerCase().includes(search)) {+ return false+ }+ return true+ })+}++function recencyOf(entry: DecoratedEntry): number {+ return entry.last_flaked_at ? new Date(entry.last_flaked_at).getTime() : 0+}++function variantCountOf(entry: DecoratedEntry): number {+ return entry.variant_count+}++// The multi-select filters only expose a toggle, so restoring one from the URL+// means toggling the symmetric difference against what is selected now.+function syncToggles(next: string[], current: string[], toggle: (value: string) => void): void {+ for (const value of next) {+ if (!current.includes(value)) {+ toggle(value)+ }+ }+ for (const value of current) {+ if (!next.includes(value)) {+ toggle(value)+ }+ }+}++// Both orders fall back to the other measure, then to the name, so the list is+// stable and a tie never reshuffles between renders.+function sortEntries(entries: DecoratedEntry[], sort: FlakinessSort): DecoratedEntry[] {+ const primary = sort === 'recent' ? recencyOf : variantCountOf+ const secondary = sort === 'recent' ? variantCountOf : recencyOf+ return [...entries].sort(+ (a, b) => primary(b) - primary(a) || secondary(b) - secondary(a) || a.identifier.localeCompare(b.identifier)+ )+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface visualReviewFlakinessSceneLogicValues {+ currentProjectId: number | string // teamLogic+ repo: RepoApi | null // visualReviewRepoLogic+ breadcrumbs: Breadcrumb[]+ decoratedEntries: DecoratedEntry[]+ entries: FlakinessEntryApi[]+ facetGroups: FacetGroups+ facetSelection: FacetSelection+ filteredEntries: DecoratedEntry[]+ filters: Filters+ loadError: string | null+ overview: FlakinessOverviewApi | null+ overviewLoading: boolean+ pendingQuarantineKeys: string[]+ repoId: string+ statCounts: Record<FlakinessPreset, number>+ thumbnailBasePath: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface visualReviewFlakinessSceneLogicActions {+ clearAllFilters: () => {+ value: true+ }+ loadOverview: () => any+ loadOverviewFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOverviewSuccess: (+ overview: FlakinessOverviewApi,+ payload?: any+ ) => {+ overview: FlakinessOverviewApi+ payload?: any+ }+ quarantineIdentifier: (+ identifier: string,+ runType: string,+ reason: string,+ expiresAt: string | null,+ sourceRunId: string | null+ ) => {+ expiresAt: string | null+ identifier: string+ reason: string+ runType: string+ sourceRunId: string | null+ }+ quarantineSettled: (+ identifier: string,+ runType: string+ ) => {+ identifier: string+ runType: string+ }+ setPreset: (preset: FlakinessPreset) => {+ preset: FlakinessPreset+ }+ setSearch: (search: string) => {+ search: string+ }+ setSort: (sort: FlakinessSort) => {+ sort: FlakinessSort+ }+ toggleArea: (value: string) => {+ value: string+ }+ toggleType: (value: string) => {+ value: string+ }+ unquarantineIdentifier: (+ identifier: string,+ runType: string+ ) => {+ identifier: string+ runType: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface visualReviewFlakinessSceneLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ repoId: (arg: any) => string+ entries: (overview: FlakinessOverviewApi | null) => FlakinessEntryApi[]+ decoratedEntries: (entries: FlakinessEntryApi[]) => DecoratedEntry[]+ filteredEntries: (decoratedEntries: DecoratedEntry[], filters: Filters) => DecoratedEntry[]+ statCounts: (overview: FlakinessOverviewApi | null) => Record<FlakinessPreset, number>+ facetGroups: (decoratedEntries: DecoratedEntry[], filters: Filters) => FacetGroups+ facetSelection: (filters: Filters) => FacetSelection+ thumbnailBasePath: (currentProjectId: number | string, arg: any) => string | null+ breadcrumbs: (repo: RepoApi | null) => Breadcrumb[]+ }+}++export type visualReviewFlakinessSceneLogicType = MakeLogicType<+ visualReviewFlakinessSceneLogicValues,+ visualReviewFlakinessSceneLogicActions,+ VisualReviewFlakinessSceneLogicProps,+ visualReviewFlakinessSceneLogicMeta+>++export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLogicType>([+ path(['products', 'visual_review', 'frontend', 'scenes', 'visualReviewFlakinessSceneLogic']),+ props({} as VisualReviewFlakinessSceneLogicProps),+ key((props) => props.repoId),+ connect((props: VisualReviewFlakinessSceneLogicProps) => ({+ values: [teamLogic, ['currentProjectId'], visualReviewRepoLogic({ repoId: props.repoId }), ['repo']],+ })),+ actions({+ setPreset: (preset: FlakinessPreset) => ({ preset }),+ toggleType: (value: string) => ({ value }),+ toggleArea: (value: string) => ({ value }),+ setSearch: (search: string) => ({ search }),+ setSort: (sort: FlakinessSort) => ({ sort }),+ clearAllFilters: true,+ quarantineIdentifier: (+ identifier: string,+ runType: string,+ reason: string,+ expiresAt: string | null,+ sourceRunId: string | null+ ) => ({+ identifier,+ runType,+ reason,+ expiresAt,+ sourceRunId,+ }),+ unquarantineIdentifier: (identifier: string, runType: string) => ({ identifier, runType }),+ quarantineSettled: (identifier: string, runType: string) => ({ identifier, runType }),+ }),+ reducers({+ // The loader resets `overview` to null on failure, which is+ // indistinguishable from an empty repo. Hold the error so the scene can+ // tell "nothing to show" from "we could not look".+ loadError: [+ null as string | null,+ {+ loadOverview: () => null,+ loadOverviewSuccess: () => null,+ loadOverviewFailure: (_state: string | null, { error }: { error: string }) => error || 'Unknown error',+ },+ ],+ pendingQuarantineKeys: [+ [] as string[],+ {+ quarantineIdentifier: (state, { identifier, runType }) => [...state, `${runType}::${identifier}`],+ unquarantineIdentifier: (state, { identifier, runType }) => [...state, `${runType}::${identifier}`],+ // Drop one occurrence, not every match, because the same row can+ // legitimately be in flight twice.+ quarantineSettled: (state, { identifier, runType }) => {+ const index = state.indexOf(`${runType}::${identifier}`)+ return index === -1 ? state : [...state.slice(0, index), ...state.slice(index + 1)]+ },+ },+ ],+ filters: [+ EMPTY_FILTERS,+ {+ setPreset: (state, { preset }) => ({ ...state, preset }),+ toggleType: (state, { value }) => ({+ ...state,+ typeKeys: state.typeKeys.includes(value)+ ? state.typeKeys.filter((key) => key !== value)+ : [...state.typeKeys, value],+ }),+ toggleArea: (state, { value }) => ({+ ...state,+ areas: state.areas.includes(value)+ ? state.areas.filter((area) => area !== value)+ : [...state.areas, value],+ }),+ setSearch: (state, { search }) => ({ ...state, search }),+ setSort: (state, { sort }) => ({ ...state, sort }),+ clearAllFilters: () => EMPTY_FILTERS,+ },+ ],+ }),+ loaders(({ props, values }) => ({+ overview: [+ null as FlakinessOverviewApi | null,+ {+ loadOverview: async () =>+ visualReviewReposFlakinessRetrieve(String(values.currentProjectId), props.repoId),+ },+ ],+ })),+ selectors({+ repoId: [() => [(_, p) => p.repoId], (repoId: string): string => repoId],+ entries: [+ (s) => [s.overview],+ (overview: FlakinessOverviewApi | null): FlakinessEntryApi[] => overview?.entries ?? [],+ ],+ decoratedEntries: [+ (s) => [s.entries],+ (entries: FlakinessEntryApi[]): DecoratedEntry[] =>+ entries.map((entry) => ({+ ...entry,+ _area: parseArea(entry.identifier),+ _typeKey: typeKeyOf(entry),+ })),+ ],+ filteredEntries: [+ (s) => [s.decoratedEntries, s.filters],+ (entries: DecoratedEntry[], filters: Filters): DecoratedEntry[] =>+ sortEntries(applyFilters(entries, filters), filters.sort),+ ],+ // Server totals, not counts over `entries`: totals cover the whole+ // population, so the tiles stay right when the payload is capped.+ statCounts: [+ (s) => [s.overview],+ (overview: FlakinessOverviewApi | null): Record<FlakinessPreset, number> => ({+ unstable: overview?.totals.unstable ?? 0,+ settled: overview?.totals.settled ?? 0,+ quarantined: overview?.totals.quarantined ?? 0,+ needs_decision: overview?.totals.needs_decision ?? 0,+ }),+ ],+ facetGroups: [+ (s) => [s.decoratedEntries, s.filters],+ (entries: DecoratedEntry[], filters: Filters): FacetGroups => ({+ type: bucketize(+ applyFilters(entries, filters, 'typeKeys').map((entry) => entry._typeKey),+ typeLabelOf+ ),+ area: bucketize(applyFilters(entries, filters, 'areas').map((entry) => entry._area)),+ stability: [],+ }),+ ],+ facetSelection: [+ (s) => [s.filters],+ (filters: Filters): FacetSelection => ({+ type: new Set(filters.typeKeys),+ area: new Set(filters.areas),+ stability: new Set<string>(),+ }),+ ],+ thumbnailBasePath: [+ (s) => [s.currentProjectId, (_, p) => p.repoId],+ (projectId: number | string, repoId: string): string | null =>+ projectId ? `/api/projects/${projectId}/visual_review/repos/${repoId}/thumbnails` : null,+ ],+ // Single scene crumb, matching the runs and snapshots scenes.+ breadcrumbs: [+ (s) => [s.repo],+ (repo: RepoApi | null): Breadcrumb[] => [+ {+ key: ['visual_review_repo', repo?.id ?? 'unknown'],+ name: repo?.repo_full_name ?? 'Visual review',+ },+ ],+ ],+ }),+ listeners(({ actions, values, props }) => ({+ quarantineIdentifier: async ({ identifier, runType, reason, expiresAt, sourceRunId }) => {+ try {+ await visualReviewReposQuarantineCreate(String(values.currentProjectId), props.repoId, runType, {+ identifier,+ reason,+ expires_at: expiresAt,+ // Forward the prior source when extending. The endpoint expires the+ // old row and creates a replacement, so dropping this loses the link+ // to the run that prompted the quarantine.+ source_run_id: sourceRunId,+ })+ lemonToast.success('Quarantined. Runs stop gating on this snapshot.')+ } catch (e: any) {+ lemonToast.error(e?.detail || e?.message || 'Could not quarantine that snapshot. Try again.')+ } finally {+ actions.quarantineSettled(identifier, runType)+ if (!values.pendingQuarantineKeys.length) {+ actions.loadOverview()+ }+ }+ },+ unquarantineIdentifier: async ({ identifier, runType }) => {+ try {+ await visualReviewReposQuarantineExpireCreate(String(values.currentProjectId), props.repoId, runType, {+ identifier,+ reason: '',+ })+ lemonToast.success('Quarantine lifted. Runs gate on this snapshot again.')+ } catch (e: any) {+ lemonToast.error(e?.detail || e?.message || 'Could not lift that quarantine. Try again.')+ } finally {+ actions.quarantineSettled(identifier, runType)+ if (!values.pendingQuarantineKeys.length) {+ actions.loadOverview()+ }+ }+ },+ })),+ actionToUrl(({ values, props }) => {+ const buildHash = (): Record<string, string> => {+ const filters: Filters = values.filters+ const hash: Record<string, string> = {}+ if (filters.preset !== EMPTY_FILTERS.preset) {+ hash.preset = filters.preset+ }+ if (filters.typeKeys.length) {+ hash.types = filters.typeKeys.join(',')+ }+ if (filters.areas.length) {+ hash.areas = filters.areas.join(',')+ }+ if (filters.search) {+ hash.q = filters.search+ }+ if (filters.sort !== EMPTY_FILTERS.sort) {+ hash.sort = filters.sort+ }+ return hash+ }+ const path = `/visual_review/repos/${props.repoId}/flakiness`+ const toUrl = (): [string, Record<string, string>, Record<string, string>] => [path, {}, buildHash()]+ return {+ setPreset: toUrl,+ toggleType: toUrl,+ toggleArea: toUrl,+ setSearch: toUrl,+ setSort: toUrl,+ clearAllFilters: () => [path, {}, {}],+ }+ }),+ urlToAction(({ actions, values, props }) => ({+ '/visual_review/repos/:repoId/flakiness': (params, _searchParams, hash) => {+ if (params.repoId !== props.repoId) {+ return+ }+ const current: Filters = values.filters+ const next: Filters = {+ preset: (hash.preset as FlakinessPreset) ?? EMPTY_FILTERS.preset,+ typeKeys: hash.types ? hash.types.split(',') : [],+ areas: hash.areas ? hash.areas.split(',') : [],+ search: hash.q ?? '',+ sort: hash.sort === 'recent' ? 'recent' : 'variants',+ }+ if (next.preset !== current.preset) {+ actions.setPreset(next.preset)+ }+ if (next.search !== current.search) {+ actions.setSearch(next.search)+ }+ if (next.sort !== current.sort) {+ actions.setSort(next.sort)+ }+ syncToggles(next.typeKeys, current.typeKeys, actions.toggleType)+ syncToggles(next.areas, current.areas, actions.toggleArea)+ },+ })),+ afterMount(({ actions }) => {+ actions.loadOverview()+ }),+])diff --git a/products/visual_review/manifest.tsx b/products/visual_review/manifest.tsxindex ff4891a8e7eb..0eeeb70cb360 100644--- a/products/visual_review/manifest.tsx+++ b/products/visual_review/manifest.tsx@@ -52,6 +52,12 @@ export const manifest: ProductManifest = {import: () => import('./frontend/scenes/VisualReviewSnapshotOverviewScene'),iconType: 'visual_review',},+ VisualReviewFlakiness: {+ name: 'Flakiness',+ projectBased: true,+ import: () => import('./frontend/scenes/VisualReviewFlakinessScene'),+ iconType: 'visual_review',+ },},routes: {'/visual_review': ['VisualReviewIndex', 'visualReviewIndex'],@@ -59,6 +65,7 @@ export const manifest: ProductManifest = {'/visual_review/runs/:runId': ['VisualReviewRun', 'visualReviewRun'],'/visual_review/repos/:repoId/runs': ['VisualReviewRuns', 'visualReviewRepoRuns'],'/visual_review/repos/:repoId/snapshots': ['VisualReviewSnapshotOverview', 'visualReviewSnapshotOverview'],+ '/visual_review/repos/:repoId/flakiness': ['VisualReviewFlakiness', 'visualReviewFlakiness'],'/visual_review/repos/:repoId/:runType/snapshots/:identifier': ['VisualReviewSnapshotHistory','visualReviewSnapshotHistory',@@ -73,6 +80,7 @@ export const manifest: ProductManifest = {visualReviewRun: (runId: string): string => `/visual_review/runs/${runId}`,visualReviewRepoRuns: (repoId: string): string => `/visual_review/repos/${repoId}/runs`,visualReviewSnapshotOverview: (repoId: string): string => `/visual_review/repos/${repoId}/snapshots`,+ visualReviewFlakiness: (repoId: string): string => `/visual_review/repos/${repoId}/flakiness`,visualReviewSnapshotHistory: (repoId: string, runType: string, identifier: string): string =>`/visual_review/repos/${repoId}/${encodeURIComponent(runType)}/snapshots/${encodeURIComponent(identifier)}`,},diff --git a/products/visual_review/mcp/tools.yaml b/products/visual_review/mcp/tools.yamlindex d00a4470f14c..3cbbfdf043cb 100644--- a/products/visual_review/mcp/tools.yaml+++ b/products/visual_review/mcp/tools.yaml@@ -19,6 +19,9 @@ tools:visual-review-repos-create:operation: visual_review_repos_createenabled: false+ visual-review-repos-flakiness-retrieve:+ operation: visual_review_repos_flakiness_retrieve+ enabled: falsevisual-review-repos-list:operation: visual_review_repos_listenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex a16c7dacd63f..c784fb698586 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -39070,6 +39070,89 @@ export namespace Schemas {Cancelled: 'cancelled',} as const;+ /**+ * * `unstable` - unstable+ * * `settled` - settled+ * * `clean` - clean+ */+ export type FlakinessStateEnum = typeof FlakinessStateEnum[keyof typeof FlakinessStateEnum];+++ export const FlakinessStateEnum = {+ Unstable: 'unstable',+ Settled: 'settled',+ Clean: 'clean',+ } as const;++ export interface FlakinessEntry {+ /** Distinct alternate hashes the classifier can still match for this snapshot's current baseline. Reads as how many different images this snapshot is currently allowed to produce. Resets when the baseline moves, because tolerations recorded against an old baseline hash can never match again. */+ variant_count: number;+ /**+ * Last default-branch run that rendered one of those variants. This is not when a variant was first recorded: a snapshot can cycle through variants it already recorded without adding a new one, and that case still flakes on every run. Null when no run matched one.+ * @nullable+ */+ last_flaked_at?: string | null;+ /**+ * Mean fraction of pixels that differed across those variants. Separates sub-pixel noise from a small but real rendering change.+ * @nullable+ */+ avg_diff_percentage?: number | null;+ /**+ * Days since the first default-branch run that compared against the current baseline, which is when that baseline took effect. Context for `variant_count`: the same count against a four-day-old baseline is far worse than against a six-month-old one.+ * @nullable+ */+ baseline_age_days?: number | null;+ /** Variants recorded per day over the last 30 days, oldest first. Always that length, so a fixed time axis can be rendered. */+ daily_variant_counts: number[];+ /**+ * Index into `daily_variant_counts` where the baseline moved. Null when it moved before the window opened, which is the common case.+ * @nullable+ */+ baseline_moved_day_index?: number | null;+ /** `unstable` when a run rendered a variant inside the recency window, new or already known, `settled` when variants exist against this baseline but none recently, `clean` when none exist. A `clean` entry is always a quarantined one, because an unquarantined snapshot with no variants is not listed at all.+ *+ * * `unstable` - unstable+ * * `settled` - settled+ * * `clean` - clean */+ flakiness_state: FlakinessStateEnum;+ /** True when an active quarantine has run out, is about to, or covers a snapshot that no longer produces variants. All three mean a human has to extend it or lift it. */+ needs_decision: boolean;+ /** Active quarantine details when `is_quarantined` is true. Null otherwise. */+ quarantine?: BaselineQuarantineSummary | null;+ identifier: string;+ run_type: string;+ /** @nullable */+ browser: string | null;+ /** @nullable */+ thumbnail_hash: string | null;+ /** @nullable */+ width: number | null;+ /** @nullable */+ height: number | null;+ is_quarantined: boolean;+ }++ export type FlakinessTotalsByRunType = {[key: string]: number};++ export interface FlakinessTotals {+ /** Identifiers with an entry in `entries`. */+ listed: number;+ /** Identifiers with a current baseline, listed or not. The denominator that says how much of the repo renders consistently. */+ tracked: number;+ by_run_type: FlakinessTotalsByRunType;+ unstable: number;+ settled: number;+ quarantined: number;+ needs_decision: number;+ }++ export interface FlakinessOverview {+ entries: FlakinessEntry[];+ totals: FlakinessTotals;+ truncated: boolean;+ generated_at: string;+ }+/*** * `confirmed_flake` - CONFIRMED_FLAKE* * `suspected_regression` - SUSPECTED_REGRESSION@@ -96286,6 +96369,13 @@ export namespace Schemas {run_type?: string;};+ export type VisualReviewReposThumbnailsRetrieveParams = {+ /**+ * Narrow the lookup to one run type. The same identifier under two run types is two different images, so omit this only when the caller shows one run type.+ */+ run_type?: string;+ };+export type VisualReviewReposRunsListParams = {/*** Number of results to return per page.diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex 8cfbfdb92405..ce826ed403f7 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -1634,6 +1634,11 @@"params": [],"scope": "project"},+ "visualReviewFlakiness": {+ "template": "/visual_review/repos/{repoId}/flakiness",+ "params": ["repoId"],+ "scope": "project"+ },"visualReviewRepoRuns": {"template": "/visual_review/repos/{repoId}/runs","params": ["repoId"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex c45cb7b6a143..a2e1f4dfe878 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/scouts/findings\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/actions/{actionId}\n/replay-vision/actions/{actionId}/edit\n/replay-vision/actions/{actionId}/runs/{runId}\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay-vision/{scannerId}/actions/new\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/scouts/findings\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/actions/{actionId}\n/replay-vision/actions/{actionId}/edit\n/replay-vision/actions/{actionId}/runs/{runId}\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay-vision/{scannerId}/actions/new\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},