: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
fix(visual-review): score flakiness on failure rate, not on tolerated variants (#89224)
Julian Bez383019b7cdc2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a5ca94ae4f56..b947a2764791 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8217,17 +8217,17 @@ snapshots:scenes-app-user-research-topics--topics-list--light:hash: v1.k794b7964.f1a2f79a98d9a9104868b551164cd1ff8ee03a892af075c495ef6e41229d098e.bFA04K1QUtLmjYG7rmQcIBruv-GuGqTqFlShoEjNfcoscenes-app-visual-review-flakiness--could-not-load--dark:- hash: v1.k794b7964.b43407f2c87f5c266a5f384a6fed543d5c19c0043efbb6ca7ebdac28fc485988.mxKGi-lX3FsEItU0GYVf5o_UU7g7wqPspZ0D4i9hrFU+ hash: v1.k794b7964.a885efc43e772acd3c4f772793c1ea66d68aff8db840742efeda0db8d4e0bc81.uOVreOtzrZybXYI515GtfVCcoYT5R1N_lRbvw_qsJ4Yscenes-app-visual-review-flakiness--could-not-load--light:- hash: v1.k794b7964.f773435b48f3623bd8c85edcd3109a75ce6f0348df0b784c5fac6d3a119493c6.TJgijm2sZZLzigFYD76PiIT3vKZn7F3ouJIaEEr_rYc+ hash: v1.k794b7964.5119397214de62b75921741010980f978628fe51001f93fb553577f696a639b6.UMrYhyQ1Nv8Z0JH1XJWFPl6nHdkAqtMWq8hk3ypDmfoscenes-app-visual-review-flakiness--nothing-to-show--dark:- hash: v1.k794b7964.01ab3c1ddc7ab608b0e59904df01d7ad4b486c9c6964493f09a3d94f83cb7f9b.bA3TJHPeVdZfXaZSB1pOID2-CL9waZpurwH-G4EbmEE+ hash: v1.k794b7964.f7fd2f2c682f53cda60735fe414da42f4b901a8aec28626d6707b82139d72038.zGQ9RsZZ8hz6OVZinYDscHO99oJ_aUc_74PL-94z9P4scenes-app-visual-review-flakiness--nothing-to-show--light:- hash: v1.k794b7964.f2900a9c11bbaebfc6d4ad47e9ddc1e7d91266a90e9aec1bc3ee19f390cfc612.6pl1ZY85krwytaoXUIqtLgZAMoqA7W3GDL-YTFPoWac+ hash: v1.k794b7964.099f7cf91596a9cb775d2936404ce36f55ff670df7b02e336fa9e68dbcbc3f64.SEL1SJqeSDSHYy8DECMu7cK3hXN73TQe6QquscuJIFQscenes-app-visual-review-flakiness--unstable--dark:- hash: v1.k794b7964.e1aeebe2b7ec9a477fddae66cb6d99b81f2a60430b02048da4901a0fae987db5.EyHWaHAIJNLzkHFa4RIs-dnRxp-5vqw0nfj-1OG3fm4+ hash: v1.k794b7964.279785cef1cdca7baf63fce81ff85ec35e30399a062c78c376d79e6f1e3e4148.29947X3E4KxIBVIIESxhsPeQzbaESc41kwWzIkDEY3Escenes-app-visual-review-flakiness--unstable--light:- hash: v1.k794b7964.5cf71c0f96f1e7a0eef245e86ed8775a1da1ca79437ac06ad1d84a47b83f29a7.C8wPpmzroClyIturGgvDPkMz_pug_a0zYBJEig70wuo+ hash: v1.k794b7964.b7ed7d1fd134416708818961f5d8c2c4ac1cfaa6d9337fc9798015cff0ff446c.ArB6eVT85c9Vwx5S4ZE5MvBPfo9KZ3VKqWYLUNLInMsscenes-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/products/visual_review/README.md b/products/visual_review/README.mdindex c86b5d25699d..1dad15a67b56 100644--- a/products/visual_review/README.md+++ b/products/visual_review/README.md@@ -138,13 +138,36 @@ A quarantined snapshot is not committed to the baseline, with one exception: a qThis is the way to give a story a baseline entry when it has none and the quarantine must stay, because every run without the entry classifies the story `new`, and lifting the quarantine first fails every run until the entry lands.The procedure is: open a PR that renders the story, approve the `new` snapshot on that run by identifier (the API or the `visual-review-runs-approve-create` MCP tool; "Approve all" skips quarantined snapshots), finalize the run so the entry is committed to the PR branch, merge the PR, then lift the quarantine.-**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.+**Flakiness tab** — scores each snapshot identity on the share of the last 7 days of default-branch runs that rendered it differently from its baseline.+The share is split in two, because the two cost different things: a `hard` run failed the gate and blocked whoever was merging, and a `soft` run was absorbed by a toleration and blocked nobody.+`hard` counts every result that is not `unchanged`, matching what `gating._is_unresolved` blocks on: a diff over a threshold, a baseline that was never committed or was dropped from the file, and a baseline whose story no longer renders.-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.+Rows are read over 30 days but rated over 7.+The rate has to lapse before the history does, so a quarantine over a snapshot that stopped failing last week becomes liftable while the activity strip still shows what it used to do.++The states are an urgency ladder, and each rung asks for a different fix:++| State | Meaning | Fix |+| ---------- | -------------------------------------------------------------- | ------------------------------------------- |+| `broken` | Fails nearly every run | Correct the baseline; a quarantine hides it |+| `unstable` | Fails some runs and not others | Stabilize the story, or quarantine it |+| `at_risk` | Never fails, but its worst absorbed diff is near the threshold | Fix it before it starts failing |+| `noisy` | Renders variants, absorbed with room to spare | Nothing |+| `clean` | Nothing failing or absorbed inside the rate span | Nothing |++The page groups `noisy` and `clean` under one "Quiet" tile, so every listed entry is reachable from some tile.+A row can be listed for history the rate span no longer counts, and it would otherwise sit in the totals with no way to display it.++`at_risk` exists because always being absorbed is not a safety property.+A snapshot passes only while it stays under both diff thresholds, so one absorbed at 0.01% will never cross and one absorbed just under the line is a hard failure waiting for the next unrelated restyle.+`headroom` is what the worst absorbed run leaves free, measured against the pixel threshold: a `tolerated_hash` match copies the diff recorded when the variant was minted, and the image is byte-identical to that mint, so the number is exact rather than a re-measurement.++Open quarantines appear in the same list, with extend and lift on the row.+`needs a decision` flags one that has run out, is about to, or covers a snapshot that stopped failing the gate.+It turns on hard failures rather than on variants: a snapshot only fails the gate when its diff is over a threshold, which is the one case that records no variant at all, so scoring on variants reported every quarantine still doing its job as covering a snapshot that had gone clean.++`variant_count` stays scoped to the current baseline, because a `ToleratedHash` row is stored against a `baseline_hash` and the classifier only matches a row whose hash is still the baseline.+Variants recorded against a superseded baseline can never match again.**Known gaps:**diff --git a/products/visual_review/backend/diffing.py b/products/visual_review/backend/diffing.pyindex 858747109074..862c7ef03bb4 100644--- a/products/visual_review/backend/diffing.py+++ b/products/visual_review/backend/diffing.py@@ -18,23 +18,12 @@ from pixelhog import thumbnail as pixelhog_thumbnailfrom .db import WRITER_DBfrom .diff import THUMB_HEIGHT, THUMB_WIDTH, CompareResult, compare_imagesfrom .diff_metadata import DiffMetadata+from .facade.contracts import PIXEL_DIFF_THRESHOLD_PERCENT, SSIM_DISSIMILARITY_THRESHOLDfrom .facade.enums import ChangeKind, ClassificationReason, SnapshotResult, ToleratedReasonfrom .models import RunSnapshot, ToleratedHashlogger = structlog.get_logger(__name__)-# Two-tier classification thresholds:-#-# 1. Pixel diff ratio — fast path for obvious changes. Snapshots above-# this are immediately classified as CHANGED.-# 2. SSIM perceptual threshold — safety net for tall-page dilution. A real UI-# change at the bottom of a long screenshot affects few pixels but produces-# a measurable structural shift that SSIM catches.-#-# Only when both are below threshold is the snapshot reclassified as UNCHANGED.-PIXEL_DIFF_THRESHOLD_PERCENT = 2.5-SSIM_DISSIMILARITY_THRESHOLD = 0.01 # 1% structural difference-def classify_compare_result(result: CompareResult) -> ChangeKind | None:"""Classify a compare result into a ChangeKind, or None for unchanged.diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex 70fb0db417dc..bdbe3266036f 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -42,7 +42,7 @@ from ..logic import (toleration,)from . import contracts-from .enums import FlakinessState, RunPurpose+from .enums import RunPurposeUser = get_user_model()@@ -360,12 +360,20 @@ def get_flakiness_overview(repo_id: UUID) -> contracts.FlakinessOverview: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,+ hard_count=row.hard_count,+ soft_count=row.soft_count,+ window_runs=row.window_runs,+ hard_rate=row.hard_rate,+ soft_rate=row.soft_rate,last_flaked_at=row.last_flaked_at,avg_diff_percentage=row.avg_diff_percentage,+ worst_soft_diff_percentage=row.worst_soft_diff_percentage,+ headroom=row.headroom,baseline_age_days=_days_since(row.baseline_moved_at, raw.generated_at),- daily_variant_counts=row.daily_counts,+ daily_hard_counts=row.daily_hard_counts,+ daily_soft_counts=row.daily_soft_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),+ flakiness_state=row.state,is_quarantined=row.quarantine is not None,needs_decision=row.needs_decision,quarantine=(@@ -379,8 +387,11 @@ def get_flakiness_overview(repo_id: UUID) -> contracts.FlakinessOverview:totals = contracts.FlakinessTotals(listed=len(entries),tracked=raw.tracked_total,+ broken=raw.totals_broken,unstable=raw.totals_unstable,- settled=raw.totals_settled,+ at_risk=raw.totals_at_risk,+ noisy=raw.totals_noisy,+ clean=raw.totals_clean,quarantined=raw.totals_quarantined,needs_decision=raw.totals_needs_decision,by_run_type=raw.by_run_type,@@ -394,12 +405,6 @@ def get_flakiness_overview(repo_id: UUID) -> contracts.FlakinessOverview:)-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)@@ -411,9 +416,9 @@ def _baseline_moved_day_index(moved_at: datetime | None, now: datetime) -> int |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:+ if days_ago is None or days_ago >= contracts.FLAKINESS_WINDOW_DAYS:return None- return contracts.FLAKINESS_STRIP_DAYS - 1 - days_ago+ return contracts.FLAKINESS_WINDOW_DAYS - 1 - days_ago# --- Run API ---diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex f891f4dbd8f2..58c61ab1e61a 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -20,6 +20,23 @@ from uuid import UUIDfrom pydantic.dataclasses import dataclass+# Two-tier classification thresholds, applied by `diffing.classify_compare_result`:+#+# 1. Pixel diff ratio — fast path for obvious changes. Snapshots above+# this are immediately classified as CHANGED.+# 2. SSIM perceptual threshold — safety net for tall-page dilution. A real UI+# change at the bottom of a long screenshot affects few pixels but produces+# a measurable structural shift that SSIM catches.+#+# Only when both are below threshold is the snapshot reclassified as UNCHANGED.+#+# They live here rather than next to the classifier because they are also what+# `FlakinessEntry.headroom` is measured against, so a consumer reading that+# field needs them. Importing the classifier instead would pull the image+# libraries onto the web request path.+PIXEL_DIFF_THRESHOLD_PERCENT = 2.5+SSIM_DISSIMILARITY_THRESHOLD = 0.01 # 1% structural difference+# --- Input DTOs ---@@ -503,15 +520,37 @@ class BaselineOverview:generated_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+# How far back the page reads. Sets the width of the per-day activity strip and+# the span `headroom` looks over, where more days mean better evidence of the+# worst case a snapshot can produce.+FLAKINESS_WINDOW_DAYS = 30++# How far back the rates count, inside that window. Shorter on purpose, and+# shorter than the strip: the rates decide whether a snapshot is failing *now*,+# and a quarantine over one that stopped failing three weeks ago has to become+# liftable rather than keep reporting the failures it used to have.+#+# The default branch lands a run every few minutes on an active repo, so a week+# is hundreds of runs. That is far more than a rate needs, and widening it only+# blunts the signal.+FLAKINESS_RATE_DAYS = 7++# Hard-failure rate at or above which a snapshot is broken rather than flaky.+# The two need different actions: a flaky snapshot wants a quarantine or a+# stabilized story, a broken one wants its baseline fixed, and quarantining it+# only hides that.+FLAKINESS_BROKEN_RATE = 0.9++# Below this many runs in the window, a rate is not worth reporting as one:+# one failure out of two runs is 50% and means nothing. Rows under it still+# list, they just cannot reach `broken`.+FLAKINESS_MIN_WINDOW_RUNS = 5++# Fraction of the pixel threshold a snapshot must keep free to count as having+# headroom. Below it, the snapshot passes only because its diff has stayed on+# the safe side of a line it is already touching, and the next unrelated+# rendering change pushes it over.+FLAKINESS_MIN_HEADROOM = 0.2# A quarantine this close to running out needs a human to extend it or let it# lapse, so it counts toward `needs_decision`.@@ -543,29 +582,49 @@ class FlakinessEntry:# 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.+ # Default-branch runs in the window that rendered this snapshot differently+ # from its baseline, split by what that cost. `hard` failed the gate.+ # `soft` was absorbed by a toleration and blocked nobody.+ hard_count: int+ soft_count: int+ # Completed default-branch runs of this run type in the window. The rate+ # denominator, reported so a reader can tell 2 failures out of 3 runs from+ # 2 out of 300.+ window_runs: int+ # `hard_count` and `soft_count` over `window_runs`, clamped to 1.0. The+ # denominator counts every run of this run type, so a snapshot that only+ # started rendering partway through the window reads lower than it is.+ hard_rate: float+ soft_rate: float+ # Last default-branch run in the window that rendered a difference of+ # either kind. None when every run in the window matched the baseline.last_flaked_at: datetime | None- # Mean pixel-diff fraction across those variants. Separates sub-pixel+ # Mean pixel-diff fraction across the live variants. Separates sub-pixel# noise from a small but real rendering change.avg_diff_percentage: float | None+ # Worst pixel diff any absorbed run in the window produced, and what+ # fraction of the pixel threshold that leaves free. A snapshot always+ # tolerated at 0.01% is safe; one always tolerated just under the+ # threshold passes on luck, and the next unrelated change turns it red.+ # None when nothing was absorbed in the window.+ worst_soft_diff_percentage: float | None+ headroom: 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.+ # Hard and soft runs per day over the window, oldest first. Always+ # `FLAKINESS_WINDOW_DAYS` long so the frontend can render a fixed axis.+ daily_hard_counts: list[int]+ daily_soft_counts: list[int]+ # Index into the daily series 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: stris_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+ # snapshot that has stopped failing. All three mean a human has to choose# between extending it and lifting it.needs_decision: boolquarantine: BaselineQuarantineSummary | None = None@@ -580,8 +639,14 @@ class FlakinessTotals:# Identifiers with a current baseline, listed or not. The denominator that# tells a reader how much of the repo is quiet.tracked: int+ broken: intunstable: int- settled: int+ at_risk: int+ noisy: int+ # Listed, but nothing failing or absorbed inside the rate span. A row+ # reaches this state by carrying live variants, or history further back in+ # the read window, so it is reported rather than silently unreachable.+ clean: intquarantined: intneeds_decision: intby_run_type: dict[str, int]diff --git a/products/visual_review/backend/facade/enums.py b/products/visual_review/backend/facade/enums.pyindex 7705329f2fbc..6f486e102b25 100644--- a/products/visual_review/backend/facade/enums.py+++ b/products/visual_review/backend/facade/enums.py@@ -87,15 +87,19 @@ class ChangeKind(StrEnum):class FlakinessState(StrEnum):- """How unstable a snapshot's rendering is against its current baseline.+ """How unstable a snapshot's rendering is, and what to do about it.- Derived, not stored. A snapshot is scored on the alternate hashes the- classifier can still match, so the score resets when the baseline moves.+ Derived, not stored. Scored on how often default-branch runs in the window+ rendered the snapshot differently from its baseline, and on how much of the+ diff threshold the absorbed ones leave free. The ladder is ordered by+ urgency, and each rung asks for a different fix."""- 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+ BROKEN = "broken" # Fails nearly every run: the baseline is wrong, not the story+ UNSTABLE = "unstable" # Fails some runs and not others: the classic flake+ AT_RISK = "at_risk" # Never fails, but its diff is already touching the threshold+ NOISY = "noisy" # Renders variants, absorbed with room to spare+ CLEAN = "clean" # Matched its baseline on every run in the windowclass ActorType(StrEnum):diff --git a/products/visual_review/backend/logic/flakiness.py b/products/visual_review/backend/logic/flakiness.pyindex 50b7a44dcd1b..7e35ae9353ef 100644--- a/products/visual_review/backend/logic/flakiness.py+++ b/products/visual_review/backend/logic/flakiness.py@@ -1,8 +1,9 @@"""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.+Scores each snapshot identity on how often the default branch rendered it+differently from its baseline, and on how much of the diff threshold the+absorbed renders leave free. See `get_flakiness_overview` for the scoping rule+and the query shape."""from __future__ import annotations@@ -18,15 +19,59 @@ from django.utils import timezonefrom posthog.dataclasses import frozenfrom ..facade.contracts import (+ FLAKINESS_BROKEN_RATE,FLAKINESS_EXPIRY_SOON_DAYS,FLAKINESS_MAX_ENTRIES,- FLAKINESS_RECENT_DAYS,- FLAKINESS_STRIP_DAYS,+ FLAKINESS_MIN_HEADROOM,+ FLAKINESS_MIN_WINDOW_RUNS,+ FLAKINESS_RATE_DAYS,+ FLAKINESS_WINDOW_DAYS,+ PIXEL_DIFF_THRESHOLD_PERCENT,)-from ..facade.enums import ClassificationReason, RunStatus, SnapshotResult, ToleratedReason+from ..facade.enums import ClassificationReason, FlakinessState, ReviewState, RunStatus, SnapshotResult, ToleratedReasonfrom ..models import QuarantinedIdentifier, Run, RunSnapshot, ToleratedHashfrom . import run_queries+# Rows a run recorded as a difference from the baseline, split by what that+# difference cost. `_HARD` failed the gate and blocked whoever was merging.+# `_SOFT` was absorbed: either it matched a toleration, or it was diffed this+# run and came in under both thresholds.+#+# The split matters because only one of them is a promise. A snapshot that is+# always absorbed is not stable, it is under a line, and it stays under only+# while its diff does. `headroom` below measures how much of that line is left.+#+# `_HARD` is every result that is not UNCHANGED, which is what `gating.+# _is_unresolved` gates on. CHANGED alone would miss the two quieter ways a+# snapshot fails: NEW, when its baseline was never committed or was dropped+# from the file, and REMOVED, when the baseline outlived the story. Both fail+# every run until somebody acts, and a quarantine hides them exactly as it+# hides a CHANGED one.+#+# Mirrors `gating._is_unresolved`: a result other than `unchanged` that nobody+# has signed off. PostHog's own default-branch runs are `RunPurpose.OBSERVE` and+# so can never carry an approval, but `purpose` defaults to `REVIEW`, and a repo+# whose CI omits the flag can land an approved or tolerated snapshot on the+# default branch. Counting that as a failure would hold a quarantine open over a+# change somebody already accepted.+_HARD = Q(result__in=(SnapshotResult.CHANGED, SnapshotResult.NEW, SnapshotResult.REMOVED)) & ~Q(+ review_state__in=(ReviewState.APPROVED, ReviewState.TOLERATED)+)+#+# The matched half is restricted to auto-minted rows. A human or agent+# toleration can deliberately accept a diff well over the threshold, and the+# classifier copies that percentage onto every later match, so counting those+# would drive `headroom` to zero and label a snapshot somebody already signed+# off on as `at_risk`. `BELOW_THRESHOLD` needs no such filter: only the+# threshold path writes it.+_SOFT = Q(result=SnapshotResult.UNCHANGED) & (+ Q(classification_reason=ClassificationReason.BELOW_THRESHOLD)+ | Q(+ classification_reason=ClassificationReason.TOLERATED_HASH,+ tolerated_hash_match__reason=ToleratedReason.AUTO_THRESHOLD,+ )+)+@frozenclass _SnapshotKey:@@ -36,20 +81,6 @@ class _SnapshotKey: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--@frozenclass _VariantKey:"""One snapshot's variants, scoped to the baseline they were recorded against.@@ -63,40 +94,71 @@ class _VariantKey: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.+ """Snapshot identities that render unreliably, or carry a quarantine.++ Scoring, and why it is a rate:+ A count cannot separate one bad afternoon from a chronic flake, and a+ "did anything happen recently" flag scores one failure in a week the same+ as five hundred. So each identity is scored on the share of runs that+ rendered it differently from its baseline, split into the runs that+ failed the gate and the runs a toleration absorbed.++ Rates cover `FLAKINESS_RATE_DAYS`, which is shorter than the window the+ rows are read over. They answer whether a snapshot is failing now, and a+ quarantine over one that stopped failing weeks ago has to become liftable+ rather than keep scoring on failures it no longer produces. The daily+ series still spans the whole window, so a run of failures that predates+ the rate span is visible in the strip.++ The denominator is every completed default-branch run of that run type in+ the rate span, not the runs that rendered this identity. Counting the+ latter needs a scan of every snapshot row in the window, which is the+ shape `baseline_overview` records as too slow to serve per request. The+ approximation only understates, and only for an identity that appeared+ partway through the span.++ Rates ignore which baseline a run compared against. On the default branch+ a legitimate change does not produce a `CHANGED` row at all: the code and+ its baseline land in the same merge, so the next run already compares+ against the new hash. A `CHANGED` row there means the two fell out of+ sync or the render is not deterministic, and both count.++ `variant_count` stays baseline-scoped, because a `ToleratedHash` row is+ stored against a `baseline_hash` and the classifier only matches a row+ whose hash is still the baseline (see `classify_remaining`). Variants+ recorded against a superseded baseline can never match again, so counting+ them would report churn from a snapshot that no longer exists.++ Headroom, and why a soft rate is not enough:+ A snapshot is absorbed only while it stays under both diff thresholds. A+ snapshot always absorbed at 0.01% will not cross; one always absorbed+ just under the line crosses the next time anything nearby is restyled,+ and is a hard failure waiting to happen rather than a stable snapshot.+ `headroom` is what the worst absorbed run in the window leaves free.++ Measured against the pixel threshold only. A `tolerated_hash` row copies+ the diff recorded when the variant was minted, and the image is+ byte-identical to that mint, so the number is exact rather than a+ re-measurement. `ssim_score` is not carried onto matched rows, so the+ structural tier has no equivalent per-run history to read.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.+ Identifiers with a live variant against their current baseline, a hard+ failure in the window, 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 active quarantines- 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 the rate span's run count per run type+ - 1 grouped query for hard activity per identity and day, which the+ `snapshot_run_result` index serves because non-unchanged rows are rare- 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 grouped query for soft activity per identity and day, bounded to the+ identifiers that can produce a row+ - 1 grouped query for when each baseline last moved, same bound- 1 query to hydrate thumbnails, for listed rows only"""now = timezone.now()@@ -144,7 +206,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:return _quarantine_only_raw(active_quarantines_by_key,generated_at=now,- strip_days=FLAKINESS_STRIP_DAYS,+ strip_days=FLAKINESS_WINDOW_DAYS,max_entries=FLAKINESS_MAX_ENTRIES,)@@ -180,6 +242,47 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:universe_identifiers = list({key.identifier for key in baseline_hash_by_key})universe_baseline_hashes = list(set(baseline_hash_by_key.values()))+ # The window every rate, timestamp and strip tick is measured over. Joined+ # on the run rather than passed as a list of run ids: an active repo lands+ # hundreds of default-branch runs in a month, and the same predicate+ # already serves the neighbouring queries here.+ strip_start = today - timedelta(days=FLAKINESS_WINDOW_DAYS - 1)+ rate_start = today - timedelta(days=FLAKINESS_RATE_DAYS - 1)+ in_window = Q(+ run__repo_id=repo_id,+ run__branch__in=run_queries._DEFAULT_BRANCHES,+ run__status=RunStatus.COMPLETED,+ # Calendar days, matching the strip. A timestamp cutoff would reach into+ # the day before the first tick, so `last_flaked_at` could name a day the+ # strip does not draw.+ run__created_at__date__gte=strip_start,+ )++ # The rate denominator, per run type, over the same calendar days the+ # numerators are summed over. A timestamp cutoff here instead would cover+ # part of one more day than `_count_since` reads, so the oldest partial+ # day's runs would sit in the denominator while their failures did not+ # reach the numerator. That deflates every rate, and late in the day it can+ # drop a snapshot failing every run below the `broken` band and mark a+ # quarantine decision-ready while its last failure is still inside the span.+ rate_runs_by_type: dict[str, int] = dict(+ Run.objects.filter(+ repo_id=repo_id,+ branch__in=run_queries._DEFAULT_BRANCHES,+ status=RunStatus.COMPLETED,+ created_at__date__gte=rate_start,+ )+ .values("run_type")+ .annotate(run_count=Count("id"))+ .values_list("run_type", "run_count")+ )++ # Unbounded by identifier on purpose: a snapshot can fail every run without+ # ever recording a variant, and that snapshot is the reason this page+ # exists. It is also the case a quarantine is opened for, so leaving it out+ # would hide every quarantine that is still doing its job.+ hard_activity = _read_activity(in_window=in_window, match=_HARD)+# 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.@@ -208,28 +311,23 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw: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}+ {key.identifier for key in variants_by_pair}+ | {key.identifier for key in hard_activity}+ | {key.identifier for key in active_quarantines_by_key})if not reportable_identifiers:return _FlakinessRaw.empty(generated_at=now, tracked_total=tracked_total)+ # Bounded by identifier, unlike the hard read above. Absorbed rows are the+ # common case rather than the rare one, so this would otherwise scan most+ # of the window. Nothing is lost: an absorbed row means the classifier+ # matched a live variant or minted one, and either way the identifier is+ # already in the list.+ soft_activity = _read_activity(in_window=in_window, match=_SOFT, identifiers=reportable_identifiers)+# 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@@ -239,7 +337,8 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:# 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.+ # last real move, so the age reads too new for that snapshot. `hard_rate`+ # now names that case directly, so a reader can tell the two apart.## Grouping the whole history by `baseline_hash` instead would read more# precisely, but it admits every historical row rather than the rare event@@ -262,68 +361,17 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw: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()+ # An identity can carry something to report and still have no current+ # baseline: a quarantine opened before the first run, or a snapshot that+ # failed inside the window and then dropped out of the latest+ # default-branch run. Those keys are absent from `baseline_hash_by_key`, so+ # walk them too rather than silently drop what they recorded.+ baseline_less_keys = (active_quarantines_by_key.keys() | hard_activity.keys()) - baseline_hash_by_key.keys()scored_keys: list[tuple[_SnapshotKey, str]] = [*baseline_hash_by_key.items(),- *((key, "") for key in quarantine_only_keys),+ *((key, "") for key in baseline_less_keys),]rows: list[_FlakinessRow] = []@@ -331,43 +379,72 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:variant_key = _VariantKey(identifier=key.identifier, baseline_hash=baseline_hash)stats = variants_by_pair.get(variant_key) if baseline_hash else Nonequarantine = active_quarantines_by_key.get(key)- if stats is None and quarantine is None:+ hard = hard_activity.get(key)+ soft = soft_activity.get(key)+ if stats is None and quarantine is None and hard 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+ # Counts and rates describe the rate window; the daily series below+ # covers the whole read window, so the strip can show a run of failures+ # that started before the rates would notice it.+ hard_count = _count_since(hard, rate_start)+ soft_count = _count_since(soft, rate_start)+ # Never below what was actually observed, so a rate cannot exceed 1.0+ # when an identity outlived its run type's run count.+ window_runs = max(rate_runs_by_type.get(key.run_type, 0), hard_count + soft_count)+ # Headroom reads the whole window rather than the rate span: it asks+ # for the worst case a snapshot can produce, and more days are better+ # evidence of that.+ worst_soft_diff = soft.worst_diff_percentage if soft is not None else None+ hard_rate = _rate(hard_count, window_runs)+ headroom = _headroom(worst_soft_diff)rows.append(_FlakinessRow(run_type=key.run_type,identifier=key.identifier,- variant_count=variant_count,- last_flaked_at=last_flaked_at,+ variant_count=stats.count if stats is not None else 0,+ hard_count=hard_count,+ soft_count=soft_count,+ window_runs=window_runs,+ hard_rate=hard_rate,+ soft_rate=_rate(soft_count, window_runs),+ last_flaked_at=_latest(+ hard.last_at if hard is not None else None,+ soft.last_at if soft is not None else None,+ ),avg_diff_percentage=stats.avg_diff_percentage if stats is not None else None,- daily_counts=_daily_series(- daily_by_pair.get(variant_key, {}),+ worst_soft_diff_percentage=worst_soft_diff,+ headroom=headroom,+ daily_hard_counts=_daily_series(+ hard.daily if hard is not None else {},+ strip_start=strip_start,+ length=FLAKINESS_WINDOW_DAYS,+ ),+ daily_soft_counts=_daily_series(+ soft.daily if soft is not None else {},strip_start=strip_start,- length=FLAKINESS_STRIP_DAYS,+ length=FLAKINESS_WINDOW_DAYS,),baseline_moved_at=baseline_moved_at_by_key.get(key),- is_unstable=is_unstable,+ state=_state(+ hard_rate=hard_rate,+ soft_count=soft_count,+ headroom=headroom,+ window_runs=window_runs,+ ),quarantine=quarantine,needs_decision=_needs_decision(quarantine=quarantine,- variant_count=variant_count,+ hard_count=hard_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.+ # come first: a decision waiting on a human, then the state ladder, then a+ # quarantine, so that among equally urgent rows the ones somebody is+ # already relying on are the last to be cut.## 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@@ -376,8 +453,10 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:rows.sort(key=lambda row: (row.needs_decision,+ _STATE_URGENCY[row.state],row.quarantine is not None,- row.variant_count,+ row.hard_rate,+ row.soft_rate,row.last_flaked_at or never,),reverse=True,@@ -394,8 +473,11 @@ def get_flakiness_overview(repo_id: UUID) -> _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_broken=sum(1 for row in rows if row.state == FlakinessState.BROKEN),+ totals_unstable=sum(1 for row in rows if row.state == FlakinessState.UNSTABLE),+ totals_at_risk=sum(1 for row in rows if row.state == FlakinessState.AT_RISK),+ totals_noisy=sum(1 for row in rows if row.state == FlakinessState.NOISY),+ totals_clean=sum(1 for row in rows if row.state == FlakinessState.CLEAN),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)),@@ -422,11 +504,19 @@ def _quarantine_only_raw(run_type=key.run_type,identifier=key.identifier,variant_count=0,+ hard_count=0,+ soft_count=0,+ window_runs=0,+ hard_rate=0.0,+ soft_rate=0.0,last_flaked_at=None,avg_diff_percentage=None,- daily_counts=[0] * strip_days,+ worst_soft_diff_percentage=None,+ headroom=None,+ daily_hard_counts=[0] * strip_days,+ daily_soft_counts=[0] * strip_days,baseline_moved_at=None,- is_unstable=False,+ state=FlakinessState.CLEAN,quarantine=quarantine,needs_decision=True,)@@ -438,8 +528,11 @@ def _quarantine_only_raw(rows=listed,snapshots_by_key={},tracked_total=0,+ totals_broken=0,totals_unstable=0,- totals_settled=0,+ totals_at_risk=0,+ totals_noisy=0,+ totals_clean=len(rows),# 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),@@ -450,6 +543,116 @@ def _quarantine_only_raw()+def _read_activity(+ *,+ in_window: Q,+ match: Q,+ identifiers: list[str] | None = None,+) -> dict[_SnapshotKey, _Activity]:+ """Window activity per snapshot identity, for the rows `match` selects.++ Grouped by day so one query serves both the rate and the activity strip:+ the total is summed from the days rather than asked for separately.+ """+ queryset = RunSnapshot.objects.filter(in_window).filter(match)+ if identifiers is not None:+ queryset = queryset.filter(identifier__in=identifiers)++ daily: dict[_SnapshotKey, dict[date, int]] = defaultdict(dict)+ totals: Counter[_SnapshotKey] = Counter()+ last_at: dict[_SnapshotKey, datetime] = {}+ worst: dict[_SnapshotKey, float] = {}+ for run_type, identifier, day, day_count, latest, worst_diff in (+ queryset.annotate(day=TruncDate("run__created_at"))+ .values("run__run_type", "identifier", "day")+ .annotate(+ day_count=Count("id"),+ latest=Max("run__created_at"),+ worst_diff=Max("diff_percentage"),+ )+ .values_list("run__run_type", "identifier", "day", "day_count", "latest", "worst_diff")+ ):+ key = _SnapshotKey(run_type=run_type, identifier=identifier)+ daily[key][day] = day_count+ totals[key] += day_count+ seen_last = last_at.get(key)+ if latest is not None and (seen_last is None or latest > seen_last):+ last_at[key] = latest+ seen_worst = worst.get(key)+ if worst_diff is not None and (seen_worst is None or worst_diff > seen_worst):+ worst[key] = worst_diff++ return {+ key: _Activity(+ total=total,+ last_at=last_at.get(key),+ daily=daily[key],+ worst_diff_percentage=worst.get(key),+ )+ for key, total in totals.items()+ }+++def _count_since(activity: _Activity | None, start: date) -> int:+ """Runs on or after `start`, summed from the per-day buckets already read.++ The daily grouping means the rate span costs no extra query: it is a slice+ of the series the strip renders.+ """+ if activity is None:+ return 0+ return sum(count for day, count in activity.daily.items() if day >= start)+++def _rate(count: int, window_runs: int) -> float:+ """Share of the window's runs, or 0.0 when the window holds no runs."""+ return count / window_runs if window_runs else 0.0+++def _headroom(worst_soft_diff_percentage: float | None) -> float | None:+ """Fraction of the pixel threshold the worst absorbed run leaves free.++ 1.0 means the snapshot rendered identically to its baseline every time it+ was absorbed; 0.0 means it reached the threshold and only luck kept it on+ the passing side. None when nothing was absorbed, which is not the same as+ full headroom and must not read as a safe row.+ """+ if worst_soft_diff_percentage is None:+ return None+ return max(0.0, (PIXEL_DIFF_THRESHOLD_PERCENT - worst_soft_diff_percentage) / PIXEL_DIFF_THRESHOLD_PERCENT)+++def _state(*, hard_rate: float, soft_count: int, headroom: float | None, window_runs: int) -> str:+ """Where a snapshot sits on the urgency ladder, and so what it is asking for.++ Ordered by hard failures first, because those are the ones that stopped+ somebody merging. `broken` needs a run count behind it: one failure out of+ two runs is a 50% rate that means nothing, and calling it broken would send+ a reader to fix a baseline on the strength of a single bad render.+ """+ if hard_rate >= FLAKINESS_BROKEN_RATE and window_runs >= FLAKINESS_MIN_WINDOW_RUNS:+ return FlakinessState.BROKEN+ if hard_rate > 0:+ return FlakinessState.UNSTABLE+ if soft_count == 0:+ return FlakinessState.CLEAN+ if headroom is not None and headroom < FLAKINESS_MIN_HEADROOM:+ return FlakinessState.AT_RISK+ return FlakinessState.NOISY+++# How far up the ladder each state sits, for ordering against the entry cap.+# Keyed by `str` because `_state` returns one: `FlakinessState` is a `StrEnum`,+# so the members are the keys either way.+_STATE_URGENCY: dict[str, int] = {+ FlakinessState.BROKEN: 4,+ FlakinessState.UNSTABLE: 3,+ FlakinessState.AT_RISK: 2,+ FlakinessState.NOISY: 1,+ FlakinessState.CLEAN: 0,+}++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]@@ -464,19 +667,32 @@ def snapshot_key(row: _FlakinessRow) -> _SnapshotKey:def _needs_decision(*,quarantine: QuarantinedIdentifier | None,- variant_count: int,+ hard_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.+ snapshot it covers has stopped failing the gate. 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.++ Turns on hard failures rather than on variants. A quarantine is opened for+ a snapshot that fails the gate, and the ways a snapshot fails the gate -+ a diff over a threshold, a missing baseline, a missing render - are exactly+ the ways that record no variant at all. Reading variants therefore said+ "gone clean, lift it" about every snapshot still failing every run, and+ lifting it turned the gate red again.++ A rate span holding few runs, or none, also returns True, and that is+ deliberate rather than an unguarded edge. "It stopped failing" and "this+ run type has not run for a week" both leave a human to decide what the+ quarantine is still for. The row reports `window_runs` beside the rate, so+ a reader can tell the two apart."""if quarantine is None:return False- if variant_count == 0:+ if hard_count == 0:return Truereturn quarantine.expires_at is not None and quarantine.expires_at <= expiry_soon_cutoff@@ -523,6 +739,20 @@ class _VariantStats:avg_diff_percentage: float | None+@frozen+class _Activity:+ """What one snapshot identity did in the window, for one kind of difference.++ `worst_diff_percentage` is None when the rows carry no pixel diff, which is+ every hard row classified by the structural tier.+ """++ total: int+ last_at: datetime | None+ daily: dict[date, int]+ worst_diff_percentage: float | None++@frozenclass _FlakinessRow:"""One scored snapshot identity, before thumbnails and users are attached."""@@ -530,11 +760,19 @@ class _FlakinessRow:run_type: stridentifier: strvariant_count: int+ hard_count: int+ soft_count: int+ window_runs: int+ hard_rate: float+ soft_rate: floatlast_flaked_at: datetime | Noneavg_diff_percentage: float | None- daily_counts: list[int]+ worst_soft_diff_percentage: float | None+ headroom: float | None+ daily_hard_counts: list[int]+ daily_soft_counts: list[int]baseline_moved_at: datetime | None- is_unstable: bool+ state: strquarantine: QuarantinedIdentifier | Noneneeds_decision: bool@@ -549,8 +787,11 @@ class _FlakinessRaw:rows: list[_FlakinessRow]snapshots_by_key: dict[_SnapshotKey, RunSnapshot]tracked_total: int+ totals_broken: inttotals_unstable: int- totals_settled: int+ totals_at_risk: int+ totals_noisy: int+ totals_clean: inttotals_quarantined: inttotals_needs_decision: intby_run_type: dict[str, int]@@ -563,8 +804,11 @@ class _FlakinessRaw:rows=[],snapshots_by_key={},tracked_total=tracked_total,+ totals_broken=0,totals_unstable=0,- totals_settled=0,+ totals_at_risk=0,+ totals_noisy=0,+ totals_clean=0,totals_quarantined=0,totals_needs_decision=0,by_run_type={},diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.pyindex b9dfceb31436..a9e1bebfd6e1 100644--- a/products/visual_review/backend/presentation/serializers.py+++ b/products/visual_review/backend/presentation/serializers.py@@ -8,7 +8,9 @@ from rest_framework import serializersfrom rest_framework_dataclasses.serializers import DataclassSerializerfrom ..facade.contracts import (- FLAKINESS_STRIP_DAYS,+ FLAKINESS_RATE_DAYS,+ FLAKINESS_WINDOW_DAYS,+ PIXEL_DIFF_THRESHOLD_PERCENT,AddSnapshotsInput,AddSnapshotsResult,ApproveRunRequestInput,@@ -335,21 +337,73 @@ class FlakinessEntrySerializer(DataclassSerializer):"baseline hash can never match again."))+ hard_count = serializers.IntegerField(+ help_text=(+ f"Default-branch runs in the last {FLAKINESS_RATE_DAYS} days where this snapshot failed "+ "the gate, so somebody could not merge until it was resolved. Counts every result that "+ "is not `unchanged`: a diff over a threshold, a baseline that was never committed or "+ "was dropped, and a baseline whose story no longer renders."+ )+ )+ soft_count = serializers.IntegerField(+ help_text=(+ f"Default-branch runs in the last {FLAKINESS_RATE_DAYS} days where this snapshot "+ "rendered differently from its baseline and a toleration absorbed it, blocking nobody."+ )+ )+ window_runs = serializers.IntegerField(+ help_text=(+ f"Completed default-branch runs of this run type in the last {FLAKINESS_RATE_DAYS} "+ "days. The rate denominator, so a reader can tell 2 failures out of 3 runs from 2 out "+ "of 300."+ )+ )+ hard_rate = serializers.FloatField(+ help_text=(+ "`hard_count` over `window_runs`. The denominator counts every run of this run type, "+ "so a snapshot that only started rendering partway through the window reads lower "+ "than it is."+ )+ )+ soft_rate = serializers.FloatField(help_text="`soft_count` over `window_runs`.")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."+ f"Last default-branch run in the last {FLAKINESS_WINDOW_DAYS} days that rendered this "+ "snapshot differently from its baseline, whether the gate failed or a toleration "+ "absorbed it. Reads over the full window rather than the rate span, so a snapshot that "+ "stopped failing still reports when it last did. Null when nothing happened at all."),)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."+ "Mean fraction of pixels that differed across the live variants. Separates sub-pixel "+ "noise from a small but real rendering change."+ ),+ )+ worst_soft_diff_percentage = serializers.FloatField(+ allow_null=True,+ required=False,+ help_text=(+ f"Largest pixel diff any absorbed run in the last {FLAKINESS_WINDOW_DAYS} days "+ "produced. Reads the full window rather than the rate span, because it asks for the "+ "worst case a snapshot can produce and more days are better evidence of that. Null "+ "when nothing was absorbed."+ ),+ )+ headroom = serializers.FloatField(+ allow_null=True,+ required=False,+ help_text=(+ f"Fraction of the {PIXEL_DIFF_THRESHOLD_PERCENT}% pixel threshold that "+ "`worst_soft_diff_percentage` leaves free. A snapshot is absorbed only while it stays "+ "under the threshold, so this is what says whether it will keep doing so: 1.0 means it "+ "rendered identically every time it was absorbed, 0.0 means it reached the line and "+ "only luck kept it on the passing side. Null when nothing was absorbed, which is not "+ "the same as full headroom."),)baseline_age_days = serializers.IntegerField(@@ -357,38 +411,44 @@ class FlakinessEntrySerializer(DataclassSerializer):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."+ "which is when that baseline took effect. Reads too new for a `broken` snapshot, which "+ "records a change against an unmoved baseline on every run."),)- daily_variant_counts = serializers.ListField(+ daily_hard_counts = serializers.ListField(child=serializers.IntegerField(),help_text=(- f"Variants recorded per day over the last {FLAKINESS_STRIP_DAYS} days, oldest first. "+ f"Gate-failing runs per day over the last {FLAKINESS_WINDOW_DAYS} days, oldest first. ""Always that length, so a fixed time axis can be rendered."),)+ daily_soft_counts = serializers.ListField(+ child=serializers.IntegerField(),+ help_text=f"Absorbed runs per day over the same {FLAKINESS_WINDOW_DAYS} days, oldest first.",+ )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."+ "Index into the daily series 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."+ "An urgency ladder, where each rung asks for a different fix. `broken` fails nearly "+ "every run, so its baseline is wrong and quarantining it only hides that. `unstable` "+ "fails some runs and not others, the classic flake. `at_risk` never fails, but its "+ "worst absorbed diff is already touching the threshold, so the next unrelated change "+ "turns it red. `noisy` renders variants and absorbs them with room to spare. `clean` "+ "matched its baseline on every run in the window."),)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."+ "True when an active quarantine has run out, is about to, or covers a snapshot that "+ "has stopped failing the gate. All three mean a human has to extend it or lift it."))quarantine = BaselineQuarantineSummarySerializer(@@ -409,7 +469,20 @@ class FlakinessTotalsSerializer(DataclassSerializer):"of the repo renders consistently."))- by_run_type = serializers.DictField(child=serializers.IntegerField())+ broken = serializers.IntegerField(help_text="Identifiers whose `flakiness_state` is `broken`.")+ unstable = serializers.IntegerField(help_text="Identifiers whose `flakiness_state` is `unstable`.")+ at_risk = serializers.IntegerField(help_text="Identifiers whose `flakiness_state` is `at_risk`.")+ noisy = serializers.IntegerField(help_text="Identifiers whose `flakiness_state` is `noisy`.")+ clean = serializers.IntegerField(+ help_text=(+ "Identifiers whose `flakiness_state` is `clean`. They are listed because they carry live "+ "variants or older history, and reported here so every listed entry is reachable."+ )+ )+ by_run_type = serializers.DictField(+ child=serializers.IntegerField(),+ help_text="Listed identifiers per run type, so one suite's noise can be told from another's.",+ )class Meta:dataclass = FlakinessTotalsdiff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.pyindex 41c7b85cb603..7a1905be4679 100644--- a/products/visual_review/backend/presentation/views.py+++ b/products/visual_review/backend/presentation/views.py@@ -320,12 +320,14 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):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 "+ "Snapshots in a repo whose rendering cannot be trusted: those that failed the gate or "+ "were absorbed by a toleration on a recent default-branch run, 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. Each entry carries "+ f"the share of the last {contracts.FLAKINESS_RATE_DAYS} days of default-branch runs "+ "that failed the gate (`hard_rate`) and the share a toleration absorbed "+ "(`soft_rate`), plus `headroom`, the fraction of the diff threshold its worst "+ "absorbed run leaves free. 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."),diff --git a/products/visual_review/backend/tests/test_flakiness.py b/products/visual_review/backend/tests/test_flakiness.pyindex dec113dd25a7..2123cb8ad315 100644--- a/products/visual_review/backend/tests/test_flakiness.py+++ b/products/visual_review/backend/tests/test_flakiness.py@@ -1,18 +1,18 @@"""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.+- A quarantine over a snapshot that still fails does not ask to be lifted.+- State turns on the share of window runs that failed, not on a count.+- `broken` needs enough runs behind it to mean anything.+- Headroom separates absorbed noise from a snapshot touching the threshold.+- Activity is bounded to the window, the default branch, and the row's run type.+- Both halves of an absorbed run count: the mint and the later matches.+- A snapshot failing the gate is listed even when it records no variant.+- Variants stay scoped to the current baseline hash.+- Only auto-minted, unexpired tolerations count toward `variant_count`.- `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.+- The activity strip is dense, split, and positions the baseline divider.+- The soft read is bounded to identifiers that can produce a row."""from datetime import timedelta@@ -30,12 +30,15 @@ from products.visual_review.backend.db import WRITER_DBfrom products.visual_review.backend.facade import api as vr_apifrom products.visual_review.backend.facade.contracts import (FLAKINESS_EXPIRY_SOON_DAYS,- FLAKINESS_RECENT_DAYS,- FLAKINESS_STRIP_DAYS,+ FLAKINESS_MIN_WINDOW_RUNS,+ FLAKINESS_RATE_DAYS,+ FLAKINESS_WINDOW_DAYS,+ PIXEL_DIFF_THRESHOLD_PERCENT,)from products.visual_review.backend.facade.enums import (ClassificationReason,FlakinessState,+ ReviewState,RunStatus,RunType,SnapshotResult,@@ -46,6 +49,25 @@ from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisCURRENT_BASELINE = "baseline-current"+# What a run recorded for a snapshot, in the terms the page scores on. `soft`+# splits into the run that minted a variant and the runs that matched it later,+# because the classifier writes a different reason for each.+EXACT = "exact"+SOFT_MINT = "soft_mint"+SOFT_MATCH = "soft_match"+HARD = "hard"+HARD_NEW = "hard_new"+HARD_REMOVED = "hard_removed"++_OUTCOMES = {+ EXACT: (SnapshotResult.UNCHANGED, ClassificationReason.EXACT),+ SOFT_MINT: (SnapshotResult.UNCHANGED, ClassificationReason.BELOW_THRESHOLD),+ SOFT_MATCH: (SnapshotResult.UNCHANGED, ClassificationReason.TOLERATED_HASH),+ HARD: (SnapshotResult.CHANGED, ""),+ HARD_NEW: (SnapshotResult.NEW, ""),+ HARD_REMOVED: (SnapshotResult.REMOVED, ""),+}+def _mk_run(repo: Repo,@@ -71,17 +93,22 @@ def _mk_snapshot(*,identifier: str,baseline_hash: str = CURRENT_BASELINE,- result: str = SnapshotResult.UNCHANGED,+ outcome: str = EXACT,+ diff_percentage: float | None = None,tolerated_hash_match: ToleratedHash | None = None,+ review_state: str = "",) -> RunSnapshot:+ result, reason = _OUTCOMES[outcome]return RunSnapshot.objects.create(run=run,team_id=run.team_id,identifier=identifier,baseline_hash=baseline_hash,result=result,+ classification_reason=reason,+ diff_percentage=diff_percentage,tolerated_hash_match=tolerated_hash_match,- classification_reason=ClassificationReason.TOLERATED_HASH if tolerated_hash_match else "",+ review_state=review_state,)@@ -95,8 +122,57 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):repo_external_id=4242,repo_full_name="PostHog/flaky",)+ # The universe run: newest completed master run, so its snapshots decide+ # which baseline each identifier is scored against. It is also a run+ # inside the window, so it counts toward every rate denominator.self.master_run = _mk_run(self.repo)+ def _mk_default_branch_run(self, *, age: timedelta, run_type: str = RunType.STORYBOOK) -> 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, run_type=run_type, superseded_by=self.master_run)+ Run.objects.filter(id=run.id).update(created_at=timezone.now() - age)+ run.refresh_from_db()+ return run++ def _render(+ self,+ identifier: str,+ *,+ outcome: str,+ count: int = 1,+ age: timedelta = timedelta(hours=1),+ diff_percentage: float | None = None,+ run_type: str = RunType.STORYBOOK,+ branch: str = "master",+ baseline_hash: str = CURRENT_BASELINE,+ tolerated_hash_match: ToleratedHash | None = None,+ review_state: str = "",+ ) -> None:+ """`count` default-branch runs that each rendered `identifier` that way.++ Every run also lands in the rate denominator, which is what makes the+ share a test asserts on predictable.+ """+ for _ in range(count):+ if branch == "master":+ run = self._mk_default_branch_run(age=age, run_type=run_type)+ else:+ run = _mk_run(self.repo, branch=branch, run_type=run_type, superseded_by=self.master_run)+ Run.objects.filter(id=run.id).update(created_at=timezone.now() - age)+ _mk_snapshot(+ run,+ identifier=identifier,+ outcome=outcome,+ diff_percentage=diff_percentage,+ baseline_hash=baseline_hash,+ tolerated_hash_match=tolerated_hash_match,+ review_state=review_state,+ )+def _mk_variant(self,*,@@ -104,22 +180,10 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):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(+ return ToleratedHash.objects.create(repo=self.repo,team_id=self.team.id,identifier=identifier,@@ -128,41 +192,317 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):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.+ def _mk_quarantine(self, identifier: str, *, expires_at=None) -> QuarantinedIdentifier:+ return QuarantinedIdentifier.objects.create(+ repo=self.repo,+ team_id=self.team.id,+ identifier=identifier,+ run_type=RunType.STORYBOOK,+ reason="Known flaky",+ expires_at=expires_at,+ )- 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 _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 _mk_match(self, tolerated: ToleratedHash, *, age: timedelta) -> Run:- """A run that rendered `tolerated` again and matched it.+ def test_a_quarantine_over_a_snapshot_still_failing_does_not_ask_to_be_lifted(self):+ # The bug this scoring replaced. A quarantine is opened for a snapshot+ # that fails the gate, and a snapshot only fails the gate when its diff+ # is over a threshold, which is the one case that records no variant.+ # Scoring on variants therefore reported every such quarantine as+ # covering a snapshot that had gone clean, and lifting it on that advice+ # turned the gate red again on the very next run.+ _mk_snapshot(self.master_run, identifier="muted", outcome=HARD)+ self._render("muted", outcome=HARD, count=20)+ self._mk_quarantine("muted")- 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,+ entry = self._entry("muted")++ assert entry is not None+ assert entry.variant_count == 0+ assert entry.hard_count == 21+ assert entry.flakiness_state == FlakinessState.BROKEN+ assert entry.needs_decision is False++ @parameterized.expand(+ [+ ("a_diff_over_the_threshold", HARD, CURRENT_BASELINE),+ # A dropped baseline leaves no hash to compare against, which is+ # what the real quarantined snapshots in this repo look like.+ ("a_baseline_that_was_never_committed", HARD_NEW, ""),+ ("a_story_that_stopped_rendering", HARD_REMOVED, CURRENT_BASELINE),+ ]+ )+ def test_every_way_of_failing_the_gate_keeps_a_quarantine_in_place(+ self, _name: str, outcome: str, baseline_hash: str+ ):+ # `gating._is_unresolved` fails the gate on every result that is not+ # UNCHANGED, so counting only CHANGED left the same bug in the two+ # quieter cases. A story whose baseline was dropped from the file comes+ # back NEW on every run, which is what a real quarantined snapshot in+ # this repo does, and it blocks a merge exactly like a CHANGED one.+ _mk_snapshot(self.master_run, identifier="muted", outcome=outcome, baseline_hash=baseline_hash)+ self._render("muted", outcome=outcome, count=20, baseline_hash=baseline_hash)+ self._mk_quarantine("muted")++ entry = self._entry("muted")++ assert entry is not None+ assert entry.hard_count == 21+ assert entry.flakiness_state == FlakinessState.BROKEN+ assert entry.needs_decision is False++ def test_a_quarantine_over_a_snapshot_that_stopped_failing_asks_to_be_lifted(self):+ _mk_snapshot(self.master_run, identifier="muted")+ self._render("muted", outcome=EXACT, count=20)+ self._mk_quarantine("muted")++ entry = self._entry("muted")++ assert entry is not None+ assert entry.hard_count == 0+ assert entry.needs_decision is True++ @parameterized.expand(+ [+ ("never_failed", 0, 20, FlakinessState.CLEAN),+ ("failed_sometimes", 2, 18, FlakinessState.UNSTABLE),+ ("failed_nearly_always", 20, 0, FlakinessState.BROKEN),+ ]+ )+ def test_state_turns_on_the_share_of_runs_that_failed(+ self, _name: str, hard_runs: int, exact_runs: int, expected: str+ ):+ # A bare count cannot separate one bad afternoon from a snapshot that+ # fails every run, and both want a different fix: the first a+ # quarantine, the second a corrected baseline.+ _mk_snapshot(self.master_run, identifier="story")+ self._render("story", outcome=HARD, count=hard_runs)+ self._render("story", outcome=EXACT, count=exact_runs)++ entry = self._entry("story")++ if expected == FlakinessState.CLEAN:+ assert entry is None # nothing to report, so not listed at all+ return+ assert entry is not None+ assert entry.window_runs == hard_runs + exact_runs + 1 # + the universe run+ assert entry.hard_count == hard_runs+ assert entry.flakiness_state == expected++ @parameterized.expand(+ [+ ("too_few_runs_to_judge", FLAKINESS_MIN_WINDOW_RUNS - 2, FlakinessState.UNSTABLE),+ ("enough_runs_to_judge", FLAKINESS_MIN_WINDOW_RUNS - 1, FlakinessState.BROKEN),+ ]+ )+ def test_broken_needs_enough_runs_behind_it(self, _name: str, extra_hard_runs: int, expected: str):+ # One failure out of two runs is a 50% rate that means nothing, and+ # calling it broken would send somebody to fix a baseline on the+ # strength of a single bad render.+ _mk_snapshot(self.master_run, identifier="story", outcome=HARD)+ self._render("story", outcome=HARD, count=extra_hard_runs)++ entry = self._entry("story")++ assert entry is not None+ assert entry.hard_rate == 1.0+ assert entry.flakiness_state == expected++ @parameterized.expand(+ [+ ("approved", ReviewState.APPROVED),+ ("tolerated", ReviewState.TOLERATED),+ ]+ )+ def test_a_signed_off_default_branch_failure_is_not_a_flake(self, _name: str, review_state: str):+ # PostHog's own default-branch runs are observe and carry no approvals, but+ # `purpose` defaults to review, so a repo whose CI omits the flag can land an+ # approved snapshot on master. Counting it would hold a quarantine open over+ # a change somebody already accepted.+ self._render("story", outcome=HARD, count=3, review_state=review_state)+ self._render("story", outcome=HARD, count=3)++ entry = self._entry("story")++ assert entry is not None+ # Six runs rendered a hard result; only the three nobody signed off count.+ assert entry.hard_count == 3+ assert entry.flakiness_state == FlakinessState.UNSTABLE++ @parameterized.expand(+ [+ ("far_under_the_threshold", 0.01, FlakinessState.NOISY),+ ("touching_the_threshold", PIXEL_DIFF_THRESHOLD_PERCENT - 0.05, FlakinessState.AT_RISK),+ ]+ )+ def test_headroom_separates_absorbed_noise_from_a_snapshot_on_the_edge(+ self, _name: str, worst_diff: float, expected: str+ ):+ # Always being absorbed is not a safety property. A snapshot is absorbed+ # only while it stays under the threshold, so one sitting just under the+ # line is a hard failure waiting for the next unrelated restyle, and it+ # must not read the same as one with 250x of margin.+ _mk_snapshot(self.master_run, identifier="jittery")+ variant = self._mk_variant(identifier="jittery", alternate_hash="a")+ self._render("jittery", outcome=SOFT_MATCH, count=5, diff_percentage=0.01, tolerated_hash_match=variant)+ self._render("jittery", outcome=SOFT_MATCH, diff_percentage=worst_diff, tolerated_hash_match=variant)++ entry = self._entry("jittery")++ assert entry is not None+ assert entry.worst_soft_diff_percentage == worst_diff+ assert entry.flakiness_state == expected++ def test_a_snapshot_failing_the_gate_is_listed_without_recording_a_variant(self):+ # A hard failure mints nothing, so a population drawn from tolerations+ # alone cannot see the snapshots that actually block merges.+ _mk_snapshot(self.master_run, identifier="blocking")+ self._render("blocking", outcome=HARD, count=2)++ entry = self._entry("blocking")++ assert entry is not None+ assert entry.variant_count == 0+ assert entry.hard_count == 2++ @parameterized.expand(+ [+ ("the_run_that_minted_the_variant", SOFT_MINT),+ ("a_later_run_that_matched_it", SOFT_MATCH),+ ]+ )+ def test_both_halves_of_an_absorbed_run_count(self, _name: str, outcome: str):+ # The mint is classified BELOW_THRESHOLD and never linked back to the+ # row it created; later matches are classified TOLERATED_HASH. Reading+ # only one reason loses either every first occurrence or every snapshot+ # that cycles through variants it already recorded.+ _mk_snapshot(self.master_run, identifier="jittery")+ variant = self._mk_variant(identifier="jittery", alternate_hash="a")+ self._render(+ "jittery",+ outcome=outcome,+ count=3,+ diff_percentage=0.02,+ tolerated_hash_match=variant if outcome == SOFT_MATCH else None,)- return run- def _entry(self, identifier: str):+ entry = self._entry("jittery")++ assert entry is not None+ assert entry.soft_count == 3+ assert entry.last_flaked_at is not None++ def test_a_deliberate_toleration_is_not_counted_as_rendering_noise(self):+ # A human or agent toleration can accept a diff well over the pixel+ # threshold, and the classifier copies that percentage onto every later+ # match. Counting those as absorbed noise drove headroom to zero and+ # labelled a snapshot somebody had already signed off on as at risk.+ _mk_snapshot(self.master_run, identifier="accepted")+ human = self._mk_variant(identifier="accepted", alternate_hash="a", reason=ToleratedReason.HUMAN)+ auto = self._mk_variant(identifier="accepted", alternate_hash="b", diff_percentage=0.01)+ for tolerated in (human, human, auto):+ run = self._mk_default_branch_run(age=timedelta(hours=1))+ _mk_snapshot(+ run,+ identifier="accepted",+ outcome=SOFT_MATCH,+ diff_percentage=12.0 if tolerated is human else 0.01,+ tolerated_hash_match=tolerated,+ )++ entry = self._entry("accepted")++ assert entry is not None+ assert entry.soft_count == 1 # only the auto-minted match+ assert entry.worst_soft_diff_percentage == 0.01+ assert entry.flakiness_state == FlakinessState.NOISY++ def test_the_rate_denominator_covers_the_same_days_as_its_numerator(self):+ # The numerator is summed from per-day buckets while the denominator was+ # counted from a timestamp, so the oldest partial day put runs in the+ # denominator whose failures never reached the numerator. Every rate+ # came out low, and how low depended on the time of day.+ _mk_snapshot(self.master_run, identifier="story", outcome=HARD)+ self._render("story", outcome=HARD, count=6, age=timedelta(days=FLAKINESS_RATE_DAYS - 1, hours=12))++ entry = self._entry("story")++ assert entry is not None+ assert entry.hard_count == entry.window_runs+ assert entry.hard_rate == 1.0++ @parameterized.expand(+ [+ ("inside_the_rate_span", timedelta(days=FLAKINESS_RATE_DAYS - 2), 3, 3),+ ("older_than_the_rate_span", timedelta(days=FLAKINESS_RATE_DAYS + 2), 0, 3),+ ("older_than_the_window", timedelta(days=FLAKINESS_WINDOW_DAYS + 5), 0, 0),+ ]+ )+ def test_rates_read_the_rate_span_and_the_strip_reads_the_window(+ self, _name: str, age: timedelta, expected_hard: int, expected_strip: int+ ):+ # The rate has to lapse before the strip does. A quarantine over a+ # snapshot that stopped failing last week must become liftable, and+ # scoring it over the whole window would keep reporting failures it no+ # longer produces. The strip still shows them, so the history is not+ # lost, just no longer counted against it.+ _mk_snapshot(self.master_run, identifier="story")+ self._render("story", outcome=HARD, count=3, age=age)+ self._mk_quarantine("story") # keeps the row listed once activity ages out++ entry = self._entry("story")++ assert entry is not None+ assert entry.hard_count == expected_hard+ assert sum(entry.daily_hard_counts) == expected_strip+ assert entry.needs_decision is (expected_hard == 0)++ def test_activity_on_a_pr_branch_does_not_count(self):+ # A PR rendering a difference is a property of that branch, not evidence+ # the default branch is unstable.+ _mk_snapshot(self.master_run, identifier="pr-only")+ self._render("pr-only", outcome=HARD, count=3, branch="feat/something")+ self._mk_quarantine("pr-only")++ entry = self._entry("pr-only")++ assert entry is not None+ assert entry.hard_count == 0++ def test_activity_does_not_leak_between_run_types(self):+ # A row is one `(run_type, identifier)`. A storybook failure 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._render("shared", outcome=HARD, count=3)+result = vr_api.get_flakiness_overview(self.repo.id)- return next((e for e in result.entries if e.identifier == identifier), None)+ by_type = {e.run_type: e for e in result.entries if e.identifier == "shared"}++ assert by_type[RunType.STORYBOOK].hard_count == 3+ assert RunType.PLAYWRIGHT not in by_type++ def test_a_rate_cannot_exceed_one(self):+ # The denominator counts runs of the run type, not runs that rendered+ # this identifier, so a row could otherwise report more failures than+ # there were runs.+ _mk_snapshot(self.master_run, identifier="shared")+ _mk_run(self.repo, run_type=RunType.PLAYWRIGHT)+ self._render("shared", outcome=HARD, count=4, run_type=RunType.PLAYWRIGHT)++ entry = next(+ e+ for e in vr_api.get_flakiness_overview(self.repo.id).entries+ if e.identifier == "shared" and e.run_type == RunType.PLAYWRIGHT+ )++ assert entry.hard_count == 4+ assert entry.hard_rate <= 1.0def test_variants_against_a_superseded_baseline_are_not_counted(self):_mk_snapshot(self.master_run, identifier="redesigned")@@ -188,7 +528,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):("agent_tolerations", ToleratedReason.AGENT),])- def test_deliberate_tolerations_are_not_counted_as_flakiness(self, _name: str, reason: str):+ def test_deliberate_tolerations_are_not_counted_as_variants(self, _name: str, reason: str):_mk_snapshot(self.master_run, identifier="accepted")self._mk_variant(identifier="accepted", alternate_hash="a", reason=reason)@@ -208,46 +548,10 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):assert entry is not Noneassert 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.+ def test_the_soft_read_skips_identifiers_that_cannot_produce_a_row(self):+ # Absorbed rows are the common case rather than the rare one, so an+ # unbounded read would scan most of the window's snapshots to throw the+ # result away. Only the hard read can afford to run wide._mk_snapshot(self.master_run, identifier="quiet")_mk_snapshot(self.master_run, identifier="flaky")self._mk_variant(identifier="flaky", alternate_hash="a")@@ -255,52 +559,35 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):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:+ soft_queries = [q["sql"] for q in captured.captured_queries if ClassificationReason.TOLERATED_HASH in q["sql"]]+ assert soft_queries+ for sql in soft_queries:assert "flaky" in sqlassert "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",- )+ self._mk_quarantine("brand-new")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_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)+ self._mk_quarantine("muted-early")++ 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_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@@ -316,86 +603,37 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):assert entry is not Noneassert 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",+ @parameterized.expand(+ [+ ("expiring_soon", timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS - 1), True),+ ("expiring_later", timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS + 5), False),+ ("open_ended_but_still_failing", None, False),+ ]+ )+ def test_needs_decision_flags_a_quarantine_that_stopped_fitting(+ self, _name: str, expires_in: timedelta | None, expected: bool+ ):+ _mk_snapshot(self.master_run, identifier="muted")+ self._render("muted", outcome=HARD, count=3)+ self._mk_quarantine(+ "muted",+ expires_at=timezone.now() + expires_in if expires_in is not None else None,)- 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")+ entry = self._entry("muted")assert entry is not None- assert entry.flakiness_state == FlakinessState.SETTLED+ assert entry.needs_decision is expecteddef 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.+ # still act on. A quarantine over a snapshot that stopped failing is the+ # one row somebody has to answer, and it carries the least activity._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",- )+ self._mk_quarantine("muted")_mk_snapshot(self.master_run, identifier="noisy")- for index in range(5):- self._mk_variant(identifier="noisy", alternate_hash=f"a-{index}")+ variant = self._mk_variant(identifier="noisy", alternate_hash="a")+ self._render("noisy", outcome=SOFT_MATCH, count=5, diff_percentage=0.01, tolerated_hash_match=variant)result = vr_api.get_flakiness_overview(self.repo.id)@@ -420,82 +658,27 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):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):+ def test_the_activity_strip_is_dense_split_and_places_today_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))+ variant = self._mk_variant(identifier="flaky", alternate_hash="a")+ self._render("flaky", outcome=HARD, age=timedelta(0))+ self._render("flaky", outcome=SOFT_MATCH, age=timedelta(0), diff_percentage=0.01, tolerated_hash_match=variant)+ self._render("flaky", outcome=HARD, age=timedelta(days=FLAKINESS_WINDOW_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+ assert len(entry.daily_hard_counts) == FLAKINESS_WINDOW_DAYS+ assert len(entry.daily_soft_counts) == FLAKINESS_WINDOW_DAYS+ assert entry.daily_hard_counts[-1] == 1+ assert entry.daily_soft_counts[-1] == 1+ assert sum(entry.daily_hard_counts) == 1 # the aged run is outside the windowdef 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)+ _mk_snapshot(older_run, identifier="flaky", outcome=HARD)Run.objects.filter(id=older_run.id).update(- created_at=timezone.now() - timedelta(days=FLAKINESS_STRIP_DAYS + 10)+ created_at=timezone.now() - timedelta(days=FLAKINESS_WINDOW_DAYS + 10))_mk_snapshot(self.master_run, identifier="flaky")self._mk_variant(identifier="flaky", alternate_hash="a")@@ -505,34 +688,33 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):assert entry is not Noneassert entry.baseline_moved_day_index is Noneassert entry.baseline_age_days is not None- assert entry.baseline_age_days >= FLAKINESS_STRIP_DAYS+ assert entry.baseline_age_days >= FLAKINESS_WINDOW_DAYSdef test_totals_count_the_whole_population(self):- _mk_snapshot(self.master_run, identifier="hot")- _mk_snapshot(self.master_run, identifier="cold")+ # The denominator is every storybook run in the window, so the runs+ # that rendered `jittery` dilute `wrecked`'s rate too. Enough hard runs+ # to clear the broken band anyway.+ _mk_snapshot(self.master_run, identifier="wrecked", outcome=HARD)+ self._render("wrecked", outcome=HARD, count=20)+ _mk_snapshot(self.master_run, identifier="jittery")+ variant = self._mk_variant(identifier="jittery", alternate_hash="a")+ self._render("jittery", outcome=SOFT_MATCH, diff_percentage=0.01, tolerated_hash_match=variant)_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",- )+ self._mk_quarantine("wrecked")totals = vr_api.get_flakiness_overview(self.repo.id).totalsassert totals.tracked == 3assert totals.listed == 2- assert totals.unstable == 1- assert totals.settled == 1+ assert totals.broken == 1+ assert totals.noisy == 1assert totals.quarantined == 1assert 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)+ variant = self._mk_variant(identifier="flaky", alternate_hash="a", diff_percentage=0.04)+ self._render("flaky", outcome=SOFT_MATCH, diff_percentage=0.04, tolerated_hash_match=variant)url = f"/api/projects/{self.team.id}/visual_review/repos/{self.repo.id}/flakiness/"response = self.client.get(url)@@ -542,8 +724,9 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):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 entry["soft_count"] == 1+ assert entry["flakiness_state"] == FlakinessState.NOISY+ assert len(entry["daily_hard_counts"]) == FLAKINESS_WINDOW_DAYSassert data["totals"]["tracked"] == 1def test_endpoint_404_for_unknown_repo(self):diff --git a/products/visual_review/backend/tests/test_two_tier_diff.py b/products/visual_review/backend/tests/test_two_tier_diff.pyindex c6c31bad27e8..9518ad957502 100644--- a/products/visual_review/backend/tests/test_two_tier_diff.py+++ b/products/visual_review/backend/tests/test_two_tier_diff.py@@ -8,11 +8,8 @@ import numpy as npfrom PIL import Image, ImageDrawfrom products.visual_review.backend.diff import compare_images-from products.visual_review.backend.diffing import (- PIXEL_DIFF_THRESHOLD_PERCENT,- SSIM_DISSIMILARITY_THRESHOLD,- classify_compare_result,-)+from products.visual_review.backend.diffing import classify_compare_result+from products.visual_review.backend.facade.contracts import PIXEL_DIFF_THRESHOLD_PERCENT, SSIM_DISSIMILARITY_THRESHOLDfrom products.visual_review.backend.facade.enums import ChangeKinddiff --git a/products/visual_review/frontend/components/FlakeStrip.tsx b/products/visual_review/frontend/components/FlakeStrip.tsxnew file mode 100644index 000000000000..fde064a53a6f--- /dev/null+++ b/products/visual_review/frontend/components/FlakeStrip.tsx@@ -0,0 +1,88 @@+import { dayjs } from 'lib/dayjs'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++interface FlakeStripProps {+ /** Runs per day that failed the gate, oldest first. The backend always sends a dense series. */+ dailyHardCounts: number[]+ /** Runs per day a toleration absorbed, oldest first. Same length as the hard series. */+ dailySoftCounts: number[]+ /**+ * Position of the baseline move inside the series, or null when it moved before the+ * window opened. Days before it are drawn faint: they describe a version of the+ * snapshot that is no longer what a run compares against.+ */+ baselineMovedDayIndex: number | null+}++// Every day with activity gets the same full-strength tick. A tick is 3px wide,+// so dimming quiet days to encode magnitude made the most common case the+// hardest to see. Magnitude is already in the rate beside the strip; the strip+// only has to answer when, and which of the two rows it happened in.+function tickClassName(count: number, { isFaint, isHard }: { isFaint: boolean; isHard: boolean }): string {+ if (count === 0) {+ return isFaint ? 'bg-border-light' : 'bg-border'+ }+ if (isFaint) {+ return 'bg-border-bold'+ }+ return isHard ? 'bg-danger' : 'bg-muted'+}++/**+ * Day-by-day view of when a snapshot rendered something other than its baseline.+ *+ * Two rows rather than one, because the same total means opposite things+ * depending on which row it lands in: a full bottom row is noise the toleration+ * cache is absorbing, and a full top row is a story blocking merges every day.+ * A bare count cannot separate a burst from a chronic flake either, which is+ * what the day axis is for.+ */+export function FlakeStrip({ dailyHardCounts, dailySoftCounts, baselineMovedDayIndex }: FlakeStripProps): JSX.Element {+ // Defaulted because a rolling deploy can hand this component a response from+ // a pod that predates these fields, and a bare reduce would take the whole+ // table down rather than one strip.+ const hard = dailyHardCounts ?? []+ const soft = dailySoftCounts ?? []+ const hardTotal = hard.reduce((sum, count) => sum + count, 0)+ const softTotal = soft.reduce((sum, count) => sum + count, 0)+ const windowStart = dayjs().subtract(Math.max(hard.length, 1) - 1, 'day')+ const summary =+ hardTotal === 0 && softTotal === 0+ ? `No difference from the baseline in the last ${hard.length} days`+ : `${hardTotal} failing and ${softTotal} absorbed in the last ${hard.length} days, since ${windowStart.format('MMM D')}`++ const rows: Array<{ counts: number[]; isHard: boolean }> = [+ { counts: hard, isHard: true },+ { counts: soft, isHard: false },+ ]++ return (+ <Tooltip+ title={+ <>+ <div>{summary}</div>+ <div className="text-xs">Top row failed the gate, bottom row was absorbed</div>+ {baselineMovedDayIndex !== null && (+ <div className="text-xs">Faint days are from before the baseline moved</div>+ )}+ </>+ }+ >+ <div className="flex flex-col gap-px" aria-label={summary}>+ {rows.map((row) => (+ <div key={row.isHard ? 'hard' : 'soft'} className="flex gap-px items-stretch h-1.5">+ {row.counts.map((count, index) => (+ <div+ key={index}+ className={`w-[3px] ${tickClassName(count, {+ isFaint: baselineMovedDayIndex !== null && index < baselineMovedDayIndex,+ isHard: row.isHard,+ })}`}+ />+ ))}+ </div>+ ))}+ </div>+ </Tooltip>+ )+}diff --git a/products/visual_review/frontend/components/FlakinessActivityCell.tsx b/products/visual_review/frontend/components/FlakinessActivityCell.tsxnew file mode 100644index 000000000000..9cd907f56071--- /dev/null+++ b/products/visual_review/frontend/components/FlakinessActivityCell.tsx@@ -0,0 +1,57 @@+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import type { FlakinessEntryApi } from '../generated/api.schemas'+import { FlakeStrip } from './FlakeStrip'++function formatRate(rate: number): string {+ // Sub-percent rates are the difference between "failed once this month" and+ // "never failed", so they must not both round to 0%.+ if (rate > 0 && rate < 0.01) {+ return '<1%'+ }+ return `${Math.round(rate * 100)}%`+}++function formatBaselineAge(baselineAgeDays: number | null | undefined): string {+ if (baselineAgeDays === null || baselineAgeDays === undefined) {+ return 'baseline never moved'+ }+ return `baseline ${baselineAgeDays}d old`+}++/**+ * How often this snapshot rendered something other than its baseline, and when.+ *+ * Leads with the failing rate because that is the one that stopped somebody+ * merging. The absorbed rate sits under it as context: the same snapshot can be+ * absorbed on every single run and still never have blocked anyone.+ */+export function ActivityCell({ entry }: { entry: FlakinessEntryApi }): JSX.Element {+ const failing = entry.hard_count > 0+ return (+ <div className="flex flex-col gap-1 items-end">+ <Tooltip+ title={+ failing+ ? `Failed the gate on ${entry.hard_count} of the last ${entry.window_runs} runs`+ : `Never failed the gate in the last ${entry.window_runs} runs`+ }+ >+ <span+ className={`font-mono font-semibold tabular-nums ${failing ? 'text-danger' : 'text-muted'}`}+ data-attr="visual-review-flakiness-hard-rate"+ >+ {formatRate(entry.hard_rate)}+ </span>+ </Tooltip>+ <FlakeStrip+ dailyHardCounts={entry.daily_hard_counts}+ dailySoftCounts={entry.daily_soft_counts}+ baselineMovedDayIndex={entry.baseline_moved_day_index ?? null}+ />+ <span className="text-[11px] text-muted font-mono">+ {formatRate(entry.soft_rate)} absorbed · {formatBaselineAge(entry.baseline_age_days)}+ </span>+ </div>+ )+}diff --git a/products/visual_review/frontend/components/FlakinessMarginCell.tsx b/products/visual_review/frontend/components/FlakinessMarginCell.tsxnew file mode 100644index 000000000000..5580e56deb6c--- /dev/null+++ b/products/visual_review/frontend/components/FlakinessMarginCell.tsx@@ -0,0 +1,50 @@+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import type { FlakinessEntryApi } from '../generated/api.schemas'++// 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 formatDiff(diffPercentage: number): string {+ return `${diffPercentage.toFixed(2)}%`+}++/**+ * How much of the diff threshold this snapshot still has to spare.+ *+ * A snapshot passes only while its diff stays under the threshold, so a story+ * absorbed at 0.01% and one absorbed just under the line are not equally safe,+ * even though both pass today and both show the same count of variants.+ */+export function MarginCell({ entry }: { entry: FlakinessEntryApi }): JSX.Element {+ const variants = `${entry.variant_count} ${entry.variant_count === 1 ? 'variant' : 'variants'}`+ if (entry.headroom === null || entry.headroom === undefined) {+ return (+ <div className="flex flex-col gap-1 items-end">+ <span className="text-muted">—</span>+ <span className="text-[11px] text-muted font-mono">{variants}</span>+ </div>+ )+ }++ const tight = entry.headroom < 0.2+ return (+ <div className="flex flex-col gap-1 items-end">+ <Tooltip+ title={+ `Its worst absorbed run differed by ${formatDiff(entry.worst_soft_diff_percentage ?? 0)}, ` ++ `leaving ${Math.round(entry.headroom * 100)}% of the threshold free. ` ++ (tight+ ? 'The next unrelated rendering change is likely to push it over.'+ : 'It has room before it would start failing.')+ }+ >+ <span className={`font-mono font-semibold tabular-nums ${tight ? 'text-warning-dark' : 'text-muted'}`}>+ {Math.round(entry.headroom * 100)}% left+ </span>+ </Tooltip>+ <span className="text-[11px] text-muted font-mono">+ {formatDiff(entry.worst_soft_diff_percentage ?? 0)} worst · {variants}+ </span>+ </div>+ )+}diff --git a/products/visual_review/frontend/components/FlakinessStatRow.tsx b/products/visual_review/frontend/components/FlakinessStatRow.tsxindex d927079606c6..c7a1d6cb0fde 100644--- a/products/visual_review/frontend/components/FlakinessStatRow.tsx+++ b/products/visual_review/frontend/components/FlakinessStatRow.tsx@@ -1,38 +1,50 @@-export type FlakinessPreset = 'unstable' | 'settled' | 'quarantined' | 'needs_decision'+export type FlakinessPreset = 'needs_decision' | 'broken' | 'unstable' | 'at_risk' | 'quiet' | 'quarantined'-// Mirrors `FLAKINESS_RECENT_DAYS` in+// Mirrors `FLAKINESS_RATE_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+// the backend value is the rate denominator and this constant drives the copy.+export const FLAKE_RATE_DAYS = 7const COLOR_BY_PRESET: Record<FlakinessPreset, string> = {- unstable: 'var(--danger)',- settled: 'var(--warning-dark)',- quarantined: 'var(--warning)',needs_decision: 'var(--primary-3000)',+ broken: 'var(--danger)',+ unstable: 'var(--warning-dark)',+ at_risk: 'var(--warning)',+ quiet: 'var(--muted)',+ quarantined: 'var(--brand-blue)',}const STATS: Array<{ value: FlakinessPreset; label: string; description: string }> = [+ {+ value: 'needs_decision',+ label: 'Needs a decision',+ description: 'Quarantine ran out, or nothing has failed under it recently',+ },+ {+ value: 'broken',+ label: 'Broken',+ description: 'Fails nearly every run, so its baseline is wrong or missing',+ },{value: 'unstable',label: 'Unstable',- description: `Rendered a variant in the last ${RECENT_VARIANT_WINDOW_DAYS} days`,+ description: 'Fails some runs and not others',},{- value: 'settled',- label: 'Settled',- description: 'Carries variants, but has been quiet for longer than that',+ value: 'at_risk',+ label: 'At risk',+ description: 'Passes, but its diff is already close to the threshold',+ },+ {+ value: 'quiet',+ label: 'Quiet',+ description: 'Absorbed with room to spare, or nothing failing now',},{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 {@@ -42,13 +54,21 @@ interface FlakinessStatRowProps {}/**- * 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.+ * The six populations this scene can show, ordered by how much attention each+ * one wants.+ *+ * Together they have to cover every listed row. `quiet` is the catch-all that+ * makes that hold: it takes both `noisy` and `clean`, because a row can be+ * listed for history the rate span no longer counts and would otherwise show+ * in the totals while no tile could reach it. The State column still names the+ * precise state, so nothing is lost by grouping them here.+ *+ * There is still no "all snapshots" tile: that 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">+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-2">{STATS.map((stat) => {const active = preset === stat.valuereturn (diff --git a/products/visual_review/frontend/components/FlakinessStateCell.tsx b/products/visual_review/frontend/components/FlakinessStateCell.tsxindex 17c3cb650046..1f10e1eb3923 100644--- a/products/visual_review/frontend/components/FlakinessStateCell.tsx+++ b/products/visual_review/frontend/components/FlakinessStateCell.tsx@@ -3,19 +3,46 @@ 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' },+const STATE_TAG: Record<+ string,+ { label: string; type: 'danger' | 'caution' | 'warning' | 'success' | 'muted'; title: string }+> = {+ broken: {+ label: 'Broken',+ type: 'danger',+ title: 'Fails nearly every run. Its baseline no longer matches what the story renders, or it never got one, so fix the baseline rather than quarantine it.',+ },+ unstable: {+ label: 'Unstable',+ type: 'caution',+ title: 'Fails some runs and not others. Stabilize the story, or quarantine it while you do.',+ },+ at_risk: {+ label: 'At risk',+ type: 'warning',+ title: 'Never fails today, but its worst diff is already close to the threshold. The next unrelated rendering change turns it red.',+ },+ noisy: {+ label: 'Noisy',+ type: 'muted',+ title: 'Renders more than one image, and the tolerated variants absorb it with room to spare. Nothing to do.',+ },+ clean: {+ label: 'Clean',+ type: 'success',+ title: 'Matched its baseline on every run in the window.',+ },}export function StateCell({ entry }: { entry: FlakinessEntryApi }): JSX.Element {const tag = STATE_TAG[entry.flakiness_state] ?? STATE_TAG.cleanreturn (<div className="flex flex-col gap-1 items-start">- <LemonTag type={tag.type}>{tag.label}</LemonTag>+ <LemonTag type={tag.type} title={tag.title}>+ {tag.label}+ </LemonTag>{entry.is_quarantined && (- <LemonTag type="warning" icon={<IconWarning />}>+ <LemonTag type="warning" icon={<IconWarning />} title="Skipped when a run decides pass or fail">Quarantined</LemonTag>)}diff --git a/products/visual_review/frontend/components/FlakinessVariantsCell.tsx b/products/visual_review/frontend/components/FlakinessVariantsCell.tsxdeleted file mode 100644index 4a83a3f41f5a..000000000000--- a/products/visual_review/frontend/components/FlakinessVariantsCell.tsx+++ /dev/null@@ -1,43 +0,0 @@-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/VariantStrip.tsx b/products/visual_review/frontend/components/VariantStrip.tsxdeleted file mode 100644index 9008d863dac5..000000000000--- a/products/visual_review/frontend/components/VariantStrip.tsx+++ /dev/null@@ -1,65 +0,0 @@-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/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.tsindex 01a065f4a1fc..8fbb53c36df1 100644--- a/products/visual_review/frontend/generated/api.schemas.ts+++ b/products/visual_review/frontend/generated/api.schemas.ts@@ -111,50 +111,78 @@ export interface BaselineOverviewApi {}/**+ * * `broken` - broken* * `unstable` - unstable- * * `settled` - settled+ * * `at_risk` - at_risk+ * * `noisy` - noisy* * `clean` - clean*/export type FlakinessStateEnumApi = (typeof FlakinessStateEnumApi)[keyof typeof FlakinessStateEnumApi]export const FlakinessStateEnumApi = {+ Broken: 'broken',Unstable: 'unstable',- Settled: 'settled',+ AtRisk: 'at_risk',+ Noisy: 'noisy',Clean: 'clean',} as constexport 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.+ /** Default-branch runs in the last 7 days where this snapshot failed the gate, so somebody could not merge until it was resolved. Counts every result that is not `unchanged`: a diff over a threshold, a baseline that was never committed or was dropped, and a baseline whose story no longer renders. */+ hard_count: number+ /** Default-branch runs in the last 7 days where this snapshot rendered differently from its baseline and a toleration absorbed it, blocking nobody. */+ soft_count: number+ /** Completed default-branch runs of this run type in the last 7 days. The rate denominator, so a reader can tell 2 failures out of 3 runs from 2 out of 300. */+ window_runs: number+ /** `hard_count` over `window_runs`. The denominator counts every run of this run type, so a snapshot that only started rendering partway through the window reads lower than it is. */+ hard_rate: number+ /** `soft_count` over `window_runs`. */+ soft_rate: number+ /**+ * Last default-branch run in the last 30 days that rendered this snapshot differently from its baseline, whether the gate failed or a toleration absorbed it. Reads over the full window rather than the rate span, so a snapshot that stopped failing still reports when it last did. Null when nothing happened at all.* @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.+ * Mean fraction of pixels that differed across the live 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.+ * Largest pixel diff any absorbed run in the last 30 days produced. Reads the full window rather than the rate span, because it asks for the worst case a snapshot can produce and more days are better evidence of that. Null when nothing was absorbed.+ * @nullable+ */+ worst_soft_diff_percentage?: number | null+ /**+ * Fraction of the 2.5% pixel threshold that `worst_soft_diff_percentage` leaves free. A snapshot is absorbed only while it stays under the threshold, so this is what says whether it will keep doing so: 1.0 means it rendered identically every time it was absorbed, 0.0 means it reached the line and only luck kept it on the passing side. Null when nothing was absorbed, which is not the same as full headroom.+ * @nullable+ */+ headroom?: number | null+ /**+ * Days since the first default-branch run that compared against the current baseline, which is when that baseline took effect. Reads too new for a `broken` snapshot, which records a change against an unmoved baseline on every run.* @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[]+ /** Gate-failing runs per day over the last 30 days, oldest first. Always that length, so a fixed time axis can be rendered. */+ daily_hard_counts: number[]+ /** Absorbed runs per day over the same 30 days, oldest first. */+ daily_soft_counts: number[]/**- * Index into `daily_variant_counts` where the baseline moved. Null when it moved before the window opened, which is the common case.+ * Index into the daily series 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.+ /** An urgency ladder, where each rung asks for a different fix. `broken` fails nearly every run, so its baseline is wrong and quarantining it only hides that. `unstable` fails some runs and not others, the classic flake. `at_risk` never fails, but its worst absorbed diff is already touching the threshold, so the next unrelated change turns it red. `noisy` renders variants and absorbs them with room to spare. `clean` matched its baseline on every run in the window.*+ * * `broken` - broken* * `unstable` - unstable- * * `settled` - settled+ * * `at_risk` - at_risk+ * * `noisy` - noisy* * `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. */+ /** True when an active quarantine has run out, is about to, or covers a snapshot that has stopped failing the gate. 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@@ -171,6 +199,9 @@ export interface FlakinessEntryApi {is_quarantined: boolean}+/**+ * Listed identifiers per run type, so one suite's noise can be told from another's.+ */export type FlakinessTotalsApiByRunType = { [key: string]: number }export interface FlakinessTotalsApi {@@ -178,9 +209,18 @@ export interface FlakinessTotalsApi {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+ /** Identifiers whose `flakiness_state` is `broken`. */+ broken: number+ /** Identifiers whose `flakiness_state` is `unstable`. */unstable: number- settled: number+ /** Identifiers whose `flakiness_state` is `at_risk`. */+ at_risk: number+ /** Identifiers whose `flakiness_state` is `noisy`. */+ noisy: number+ /** Identifiers whose `flakiness_state` is `clean`. They are listed because they carry live variants or older history, and reported here so every listed entry is reachable. */+ clean: number+ /** Listed identifiers per run type, so one suite's noise can be told from another's. */+ by_run_type: FlakinessTotalsApiByRunTypequarantined: numberneeds_decision: number}diff --git a/products/visual_review/frontend/generated/api.ts b/products/visual_review/frontend/generated/api.tsindex bb4f65d757cc..97f510b44452 100644--- a/products/visual_review/frontend/generated/api.ts+++ b/products/visual_review/frontend/generated/api.ts@@ -157,7 +157,7 @@ export const getVisualReviewReposFlakinessRetrieveUrl = (projectId: string, id:}/**- * 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.+ * Snapshots in a repo whose rendering cannot be trusted: those that failed the gate or were absorbed by a toleration on a recent default-branch run, 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. Each entry carries the share of the last 7 days of default-branch runs that failed the gate (`hard_rate`) and the share a toleration absorbed (`soft_rate`), plus `headroom`, the fraction of the diff threshold its worst absorbed run leaves free. 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,diff --git a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsxindex 5579732a97dd..ef7889b04377 100644--- a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx@@ -25,7 +25,7 @@ function series(pattern: 'chronic' | 'burst' | 'silent'): number[] {return 0}if (pattern === 'burst') {- // Two variants after the baseline moved on day 25, nothing before it.+ // Two runs 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@@ -40,10 +40,18 @@ const entry = (overrides: Partial<FlakinessEntryApi>): FlakinessEntryApi => ({width: 320,height: 200,variant_count: 41,+ hard_count: 4,+ soft_count: 26,+ window_runs: 770,+ hard_rate: 4 / 770,+ soft_rate: 26 / 770,last_flaked_at: '2026-06-10T09:00:00Z',avg_diff_percentage: 0.041,+ worst_soft_diff_percentage: 0.31,+ headroom: (2.5 - 0.31) / 2.5,baseline_age_days: 34,- daily_variant_counts: series('chronic'),+ daily_hard_counts: series('burst'),+ daily_soft_counts: series('chronic'),baseline_moved_day_index: null,flakiness_state: 'unstable',is_quarantined: false,@@ -56,12 +64,23 @@ const overview: FlakinessOverviewApi = {entries: [entry({}),entry({+ // A quarantine still doing its job: the snapshot fails nearly every+ // run, so nothing about it has gone clean and nobody has to answer.identifier: 'components-playerinspector-itemevent--default--dark',- variant_count: 33,- avg_diff_percentage: 0.112,+ variant_count: 0,+ hard_count: 764,+ soft_count: 0,+ hard_rate: 764 / 770,+ soft_rate: 0,+ worst_soft_diff_percentage: null,+ headroom: null,+ avg_diff_percentage: null,baseline_age_days: 61,+ daily_hard_counts: series('chronic'),+ daily_soft_counts: series('silent'),+ flakiness_state: 'broken',is_quarantined: true,- needs_decision: true,+ needs_decision: false,quarantine: {id: '00000000-0000-0000-0000-0000000000c1',reason: 'Non-deterministic rendering (animations, timestamps)',@@ -72,22 +91,38 @@ const overview: FlakinessOverviewApi = {},}),entry({+ // Absorbed on every run, but its worst diff is a rounding error+ // away from the threshold, so it is one restyle from turning red.identifier: 'charts-heatmap--linear-color-scale--light',variant_count: 2,- avg_diff_percentage: 0.021,+ hard_count: 0,+ soft_count: 705,+ hard_rate: 0,+ soft_rate: 705 / 770,+ avg_diff_percentage: 2.19,+ worst_soft_diff_percentage: 2.42,+ headroom: (2.5 - 2.42) / 2.5,baseline_age_days: 4,- daily_variant_counts: series('burst'),+ daily_hard_counts: series('silent'),+ daily_soft_counts: series('burst'),baseline_moved_day_index: 25,+ flakiness_state: 'at_risk',last_flaked_at: '2026-06-09T09:00:00Z',}),],totals: {listed: 3,tracked: 4494,+ broken: 18,unstable: 231,- settled: 604,+ at_risk: 63,+ noisy: 604,+ clean: 812,quarantined: 47,- needs_decision: 12,+ // Zero, and deliberately so: none of the three entries needs a decision,+ // and a total that disagreed with them would send the landing logic to a+ // preset with nothing to render.+ needs_decision: 0,by_run_type: { storybook: 3 },},truncated: false,@@ -99,8 +134,11 @@ const emptyOverview: FlakinessOverviewApi = {totals: {listed: 0,tracked: 4494,+ broken: 0,unstable: 0,- settled: 0,+ at_risk: 0,+ noisy: 0,+ clean: 0,quarantined: 0,needs_decision: 0,by_run_type: {},@@ -136,7 +174,12 @@ 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 = {}+export const Unstable: StoryObj = {+ // Names its own preset. Inheriting the default made this story a hostage to+ // it: the default changed, no fixture matched the new one, and the story+ // quietly rendered an empty table for a while before anybody noticed.+ parameters: { pageUrl: `/visual_review/repos/${REPO_ID}/flakiness#preset=unstable` },+}// 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.diff --git a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsxindex 1d2e277cc42d..8beea1a96f14 100644--- a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx@@ -19,10 +19,11 @@ import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ActivityCell } from '../components/FlakinessActivityCell'+import { MarginCell } from '../components/FlakinessMarginCell'import { QuarantineCell } from '../components/FlakinessQuarantineCell'import { StateCell } from '../components/FlakinessStateCell'-import { FlakinessStatRow } from '../components/FlakinessStatRow'-import { VariantsCell } from '../components/FlakinessVariantsCell'+import { FLAKE_RATE_DAYS, FlakinessStatRow } from '../components/FlakinessStatRow'import { QuarantineAction } from '../components/QuarantineAction'import { RepoSwitcher } from '../components/RepoSwitcher'import { SnapshotFacetSidebar } from '../components/SnapshotFacetSidebar'@@ -110,9 +111,10 @@ export function VisualReviewFlakinessScene(): JSX.Element {<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.+ A snapshot that renders differently from its baseline either fails the run, or stays under the diff+ threshold and gets absorbed as an allowed variant. Rates below count the last {FLAKE_RATE_DAYS} days of+ runs on the default branch. Being absorbed is not the same as being stable: it holds only while the diff+ stays under the threshold, which is what the threshold column shows.</LemonBanner>{!loadError && <FlakinessStatRow counts={statCounts} preset={filters.preset} onChange={setPreset} />}@@ -123,13 +125,13 @@ export function VisualReviewFlakinessScene(): JSX.Element {{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.+ baseline. The rest matched their baseline on every run and carry no quarantine.</div>)}{overview?.truncated && (<LemonBanner type="info">- Showing the {overview.entries.length.toLocaleString()} snapshots with the most variants. This repo+ Showing the {overview.entries.length.toLocaleString()} snapshots that most need attention. This repohas more than the page can list, so filtering here only searches the ones above.</LemonBanner>)}@@ -147,9 +149,9 @@ export function VisualReviewFlakinessScene(): JSX.Element {<LemonSegmentedButtonsize="small"value={filters.sort}- onChange={(value) => setSort(value as 'variants' | 'recent')}+ onChange={(value) => setSort(value as 'failures' | 'recent')}options={[- { value: 'variants', label: 'Most variants' },+ { value: 'failures', label: 'Most failures' },{ value: 'recent', label: 'Most recent' },]}/>@@ -186,8 +188,8 @@ export function VisualReviewFlakinessScene(): JSX.Element {<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.+ Snapshots show up here once a run renders one differently from its baseline, or once someone+ quarantines one. Nothing in this repo has done either.</p></div>) : (@@ -250,11 +252,18 @@ export function VisualReviewFlakinessScene(): JSX.Element {render: (_, entry: DecoratedEntry) => <StateCell entry={entry} />,},{- title: 'Allowed variants',- key: 'variants',+ title: 'Failing runs',+ key: 'activity',align: 'right',width: 190,- render: (_, entry: DecoratedEntry) => <VariantsCell entry={entry} />,+ render: (_, entry: DecoratedEntry) => <ActivityCell entry={entry} />,+ },+ {+ title: 'Threshold left',+ key: 'margin',+ align: 'right',+ width: 130,+ render: (_, entry: DecoratedEntry) => <MarginCell entry={entry} />,},{title: 'Last seen',@@ -268,9 +277,7 @@ export function VisualReviewFlakinessScene(): JSX.Element {// exact timestamps.<spanclassName={`font-mono text-xs ${- entry.flakiness_state === 'unstable'- ? 'text-danger font-semibold'- : 'text-muted'+ entry.hard_count > 0 ? 'text-danger font-semibold' : 'text-muted'}`}>{formatLastSeen(entry.last_flaked_at)}diff --git a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.tsindex db5f8fc01653..273f296cbcbb 100644--- a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts+++ b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts@@ -1,3 +1,4 @@+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'@@ -14,8 +15,11 @@ const overview: FlakinessOverviewApi = {totals: {listed: 0,tracked: 4494,+ broken: 18,unstable: 231,- settled: 604,+ at_risk: 63,+ noisy: 604,+ clean: 812,quarantined: 47,needs_decision: 12,by_run_type: {},@@ -51,14 +55,113 @@ describe('visualReviewFlakinessSceneLogic', () => {it('takes the stat counts from server totals rather than the listed entries', async () => {await expectLogic(logic).toFinishAllListeners()expect(logic.values.statCounts).toEqual({+ needs_decision: 12,+ broken: 18,unstable: 231,- settled: 604,+ at_risk: 63,+ quiet: 1416,quarantined: 47,- needs_decision: 12,})})})+ describe('when the default preset has nothing in it', () => {+ // A fixed default lands on an empty table whenever this repo has nothing+ // in that bucket, and every candidate is empty on some repo. The page has+ // to move to the most urgent preset that has rows.+ // Totals say twelve need a decision while none of the listed entries+ // does, which is what a capped response looks like. Landing on the+ // totals would put a filled tile over an empty table.+ const nothingNeedsADecision: FlakinessOverviewApi = {+ ...overview,+ entries: [+ {+ identifier: 'components-chart--donut--dark',+ run_type: 'storybook',+ browser: null,+ thumbnail_hash: null,+ width: null,+ height: null,+ variant_count: 0,+ hard_count: 40,+ soft_count: 0,+ window_runs: 41,+ hard_rate: 40 / 41,+ soft_rate: 0,+ last_flaked_at: '2026-06-10T09:00:00Z',+ avg_diff_percentage: null,+ worst_soft_diff_percentage: null,+ headroom: null,+ baseline_age_days: 3,+ daily_hard_counts: [],+ daily_soft_counts: [],+ baseline_moved_day_index: null,+ flakiness_state: 'broken',+ is_quarantined: false,+ needs_decision: false,+ quarantine: null,+ },+ ],+ }++ beforeEach(() => {+ initKeaTests()+ useMocks({ get: { [FLAKINESS_URL]: nothingNeedsADecision } })+ logic = visualReviewFlakinessSceneLogic({ repoId: REPO_ID })+ logic.mount()+ })++ it('lands on the most urgent preset that has rows', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.filters.preset).toBe('broken')+ })++ it('keeps the landed preset when the filters are cleared', async () => {+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setSearch('button')+ logic.actions.clearAllFilters()+ expect(logic.values.filters.search).toBe('')+ expect(logic.values.filters.preset).toBe('broken')+ })++ it('leaves a preset the link asked for alone', async () => {+ router.actions.push(`/visual_review/repos/${REPO_ID}/flakiness`, {}, { preset: 'at_risk' })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.filters.preset).toBe('at_risk')+ })++ it('leaves the default preset alone when the link names it', async () => {+ router.actions.push(`/visual_review/repos/${REPO_ID}/flakiness`, {}, { preset: 'needs_decision' })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.filters.preset).toBe('needs_decision')+ })+ })++ describe('when the preset arrives in the URL', () => {+ beforeEach(() => {+ initKeaTests()+ useMocks({ get: { [FLAKINESS_URL]: overview } })+ logic = visualReviewFlakinessSceneLogic({ repoId: REPO_ID })+ logic.mount()+ })++ // `settled` was this page's name for these rows before it scored on+ // failure rate. A link carrying it has to land on the rows it asked+ // for, and an unrecognized value has to land somewhere workable rather+ // than filter every row away.+ it.each([+ ['quiet', 'quiet'],+ ['settled', 'quiet'],+ ['noisy', 'quiet'],+ ['broken', 'broken'],+ ['nonsense', 'needs_decision'],+ ])('resolves %s to the %s preset', async (hashValue, expected) => {+ router.actions.push(`/visual_review/repos/${REPO_ID}/flakiness`, {}, { preset: hashValue })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.filters.preset).toBe(expected)+ })+ })+describe('while quarantine writes are in flight', () => {beforeEach(() => {initKeaTests()diff --git a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.tsindex e2d134334fc0..e707f847f8cd 100644--- a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts@@ -22,10 +22,10 @@ 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'+// "Most failures" ranks by how much a snapshot costs, "most recent" by urgency.+// A snapshot that failed forty runs three weeks ago and one that failed twice+// today are both worth attention, and neither order answers for the other.+export type FlakinessSort = 'failures' | 'recent'export type Filters = {preset: FlakinessPreset@@ -35,14 +35,16 @@ export type Filters = {sort: FlakinessSort}-// Unstable is the landing slice: it is the only one that means something is-// wrong right now.+// A decision waiting on a human is the landing slice: it is the only one that+// nothing else on the page can resolve. It is also the one most often empty, so+// `landOnSomethingUseful` moves off it when this repo has nothing there. See+// that listener for why the default cannot simply be a busier preset.const EMPTY_FILTERS: Filters = {- preset: 'unstable',+ preset: 'needs_decision',typeKeys: [],areas: [],search: '',- sort: 'variants',+ sort: 'failures',}// Collapses run_type + browser into one facet key, matching how the snapshots@@ -68,10 +70,13 @@ function typeLabelOf(key: string): string {function matchesPreset(entry: DecoratedEntry, preset: FlakinessPreset): boolean {switch (preset) {+ case 'broken':case 'unstable':- return entry.flakiness_state === 'unstable'- case 'settled':- return entry.flakiness_state === 'settled'+ case 'at_risk':+ return entry.flakiness_state === preset+ // The catch-all. See `FlakinessStatRow` for why these two share a tile.+ case 'quiet':+ return entry.flakiness_state === 'noisy' || entry.flakiness_state === 'clean'case 'quarantined':return entry.is_quarantinedcase 'needs_decision':@@ -124,12 +129,24 @@ function applyFilters(})}+const PRESETS: readonly FlakinessPreset[] = ['needs_decision', 'broken', 'unstable', 'at_risk', 'quiet', 'quarantined']++// `settled` was this page's name for "has variants, none recently" before it+// scored on failure rate. Links carrying it predate that, and `quiet` is where+// those rows live now.+function presetFromHash(value: string | undefined): FlakinessPreset {+ if (value === 'settled' || value === 'noisy') {+ return 'quiet'+ }+ return PRESETS.includes(value as FlakinessPreset) ? (value as FlakinessPreset) : EMPTY_FILTERS.preset+}+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+function hardCountOf(entry: DecoratedEntry): number {+ return entry.hard_count}// The multi-select filters only expose a toggle, so restoring one from the URL@@ -150,8 +167,8 @@ function syncToggles(next: string[], current: string[], toggle: (value: string)// 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+ const primary = sort === 'recent' ? recencyOf : hardCountOf+ const secondary = sort === 'recent' ? hardCountOf : recencyOfreturn [...entries].sort((a, b) => primary(b) - primary(a) || secondary(b) - secondary(a) || a.identifier.localeCompare(b.identifier))@@ -172,6 +189,7 @@ export interface visualReviewFlakinessSceneLogicValues {overview: FlakinessOverviewApi | nulloverviewLoading: booleanpendingQuarantineKeys: string[]+ presetChosen: booleanrepoId: stringstatCounts: Record<FlakinessPreset, number>thumbnailBasePath: string | null@@ -182,6 +200,9 @@ export interface visualReviewFlakinessSceneLogicActions {clearAllFilters: () => {value: true}+ landOnPreset: (preset: FlakinessPreset) => {+ preset: FlakinessPreset+ }loadOverview: () => anyloadOverviewFailure: (error: string,@@ -273,6 +294,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog})),actions({setPreset: (preset: FlakinessPreset) => ({ preset }),+ landOnPreset: (preset: FlakinessPreset) => ({ preset }),toggleType: (value: string) => ({ value }),toggleArea: (value: string) => ({ value }),setSearch: (search: string) => ({ search }),@@ -306,6 +328,15 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLogloadOverviewFailure: (_state: string | null, { error }: { error: string }) => error || 'Unknown error',},],+ // True once the preset came from somebody rather than the default, either+ // by clicking a tile or by arriving on a link that names one. Landing+ // must not move a preset that was asked for.+ presetChosen: [+ false,+ {+ setPreset: () => true,+ },+ ],pendingQuarantineKeys: [[] as string[],{@@ -323,6 +354,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLogEMPTY_FILTERS,{setPreset: (state, { preset }) => ({ ...state, preset }),+ landOnPreset: (state, { preset }) => ({ ...state, preset }),toggleType: (state, { value }) => ({...state,typeKeys: state.typeKeys.includes(value)@@ -337,7 +369,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog}),setSearch: (state, { search }) => ({ ...state, search }),setSort: (state, { sort }) => ({ ...state, sort }),- clearAllFilters: () => EMPTY_FILTERS,+ clearAllFilters: (state) => ({ ...EMPTY_FILTERS, preset: state.preset }),},],}),@@ -375,10 +407,12 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLogstatCounts: [(s) => [s.overview],(overview: FlakinessOverviewApi | null): Record<FlakinessPreset, number> => ({+ needs_decision: overview?.totals.needs_decision ?? 0,+ broken: overview?.totals.broken ?? 0,unstable: overview?.totals.unstable ?? 0,- settled: overview?.totals.settled ?? 0,+ at_risk: overview?.totals.at_risk ?? 0,+ quiet: (overview?.totals.noisy ?? 0) + (overview?.totals.clean ?? 0),quarantined: overview?.totals.quarantined ?? 0,- needs_decision: overview?.totals.needs_decision ?? 0,}),],facetGroups: [@@ -417,6 +451,30 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog],}),listeners(({ actions, values, props }) => ({+ // A fixed default lands on an empty list whenever this repo happens to+ // have nothing in that bucket, and every candidate is empty on some+ // repo: a suite with no quarantines has no decisions, and one whose+ // snapshots all render cleanly has nothing unstable. So the default+ // holds only until the counts arrive, then the page moves to the most+ // urgent preset that has anything in it.+ loadOverviewSuccess: () => {+ if (values.presetChosen) {+ return+ }+ // Counted over the entries, not over `statCounts`. The totals cover+ // the whole population while the entry list stops at the cap, so a+ // tile can read 12 with none of those twelve actually listed, and+ // landing on it would show a filled tile above an empty table.+ const rows = values.decoratedEntries+ const has = (preset: FlakinessPreset): boolean => rows.some((entry) => matchesPreset(entry, preset))+ if (has(values.filters.preset)) {+ return+ }+ const populated = PRESETS.find(has)+ if (populated) {+ actions.landOnPreset(populated)+ }+ },quarantineIdentifier: async ({ identifier, runType, reason, expiresAt, sourceRunId }) => {try {await visualReviewReposQuarantineCreate(String(values.currentProjectId), props.repoId, runType, {@@ -484,7 +542,10 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLogtoggleArea: toUrl,setSearch: toUrl,setSort: toUrl,- clearAllFilters: () => [path, {}, {}],+ // Not an empty hash: the preset survives a clear, and dropping it from+ // the URL would round-trip through urlToAction as "no preset asked for"+ // and reset the tile the reader was moved to.+ clearAllFilters: toUrl,}}),urlToAction(({ actions, values, props }) => ({@@ -494,13 +555,17 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog}const current: Filters = values.filtersconst next: Filters = {- preset: (hash.preset as FlakinessPreset) ?? EMPTY_FILTERS.preset,+ preset: presetFromHash(hash.preset),typeKeys: hash.types ? hash.types.split(',') : [],areas: hash.areas ? hash.areas.split(',') : [],search: hash.q ?? '',- sort: hash.sort === 'recent' ? 'recent' : 'variants',+ sort: hash.sort === 'recent' ? 'recent' : 'failures',}- if (next.preset !== current.preset) {+ // Dispatch whenever the hash names a preset, even one that already+ // matches state: `setPreset` is what marks the choice as somebody's,+ // and a link to the default would otherwise be treated as no choice+ // and moved off by `landOnSomethingUseful`.+ if (hash.preset !== undefined || next.preset !== current.preset) {actions.setPreset(next.preset)}if (next.search !== current.search) {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c58803c12256..50892add4196 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -39342,51 +39342,79 @@ export namespace Schemas {} as const;/**+ * * `broken` - broken* * `unstable` - unstable- * * `settled` - settled+ * * `at_risk` - at_risk+ * * `noisy` - noisy* * `clean` - clean*/export type FlakinessStateEnum = typeof FlakinessStateEnum[keyof typeof FlakinessStateEnum];export const FlakinessStateEnum = {+ Broken: 'broken',Unstable: 'unstable',- Settled: 'settled',+ AtRisk: 'at_risk',+ Noisy: 'noisy',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;+ /** Default-branch runs in the last 7 days where this snapshot failed the gate, so somebody could not merge until it was resolved. Counts every result that is not `unchanged`: a diff over a threshold, a baseline that was never committed or was dropped, and a baseline whose story no longer renders. */+ hard_count: number;+ /** Default-branch runs in the last 7 days where this snapshot rendered differently from its baseline and a toleration absorbed it, blocking nobody. */+ soft_count: number;+ /** Completed default-branch runs of this run type in the last 7 days. The rate denominator, so a reader can tell 2 failures out of 3 runs from 2 out of 300. */+ window_runs: number;+ /** `hard_count` over `window_runs`. The denominator counts every run of this run type, so a snapshot that only started rendering partway through the window reads lower than it is. */+ hard_rate: number;+ /** `soft_count` over `window_runs`. */+ soft_rate: 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.+ * Last default-branch run in the last 30 days that rendered this snapshot differently from its baseline, whether the gate failed or a toleration absorbed it. Reads over the full window rather than the rate span, so a snapshot that stopped failing still reports when it last did. Null when nothing happened at all.* @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.+ * Mean fraction of pixels that differed across the live 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.+ * Largest pixel diff any absorbed run in the last 30 days produced. Reads the full window rather than the rate span, because it asks for the worst case a snapshot can produce and more days are better evidence of that. Null when nothing was absorbed.+ * @nullable+ */+ worst_soft_diff_percentage?: number | null;+ /**+ * Fraction of the 2.5% pixel threshold that `worst_soft_diff_percentage` leaves free. A snapshot is absorbed only while it stays under the threshold, so this is what says whether it will keep doing so: 1.0 means it rendered identically every time it was absorbed, 0.0 means it reached the line and only luck kept it on the passing side. Null when nothing was absorbed, which is not the same as full headroom.+ * @nullable+ */+ headroom?: number | null;+ /**+ * Days since the first default-branch run that compared against the current baseline, which is when that baseline took effect. Reads too new for a `broken` snapshot, which records a change against an unmoved baseline on every run.* @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[];+ /** Gate-failing runs per day over the last 30 days, oldest first. Always that length, so a fixed time axis can be rendered. */+ daily_hard_counts: number[];+ /** Absorbed runs per day over the same 30 days, oldest first. */+ daily_soft_counts: number[];/**- * Index into `daily_variant_counts` where the baseline moved. Null when it moved before the window opened, which is the common case.+ * Index into the daily series 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.+ /** An urgency ladder, where each rung asks for a different fix. `broken` fails nearly every run, so its baseline is wrong and quarantining it only hides that. `unstable` fails some runs and not others, the classic flake. `at_risk` never fails, but its worst absorbed diff is already touching the threshold, so the next unrelated change turns it red. `noisy` renders variants and absorbs them with room to spare. `clean` matched its baseline on every run in the window.*+ * * `broken` - broken* * `unstable` - unstable- * * `settled` - settled+ * * `at_risk` - at_risk+ * * `noisy` - noisy* * `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. */+ /** True when an active quarantine has run out, is about to, or covers a snapshot that has stopped failing the gate. 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;@@ -39403,6 +39431,9 @@ export namespace Schemas {is_quarantined: boolean;}+ /**+ * Listed identifiers per run type, so one suite's noise can be told from another's.+ */export type FlakinessTotalsByRunType = {[key: string]: number};export interface FlakinessTotals {@@ -39410,9 +39441,18 @@ export namespace Schemas {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;+ /** Identifiers whose `flakiness_state` is `broken`. */+ broken: number;+ /** Identifiers whose `flakiness_state` is `unstable`. */unstable: number;- settled: number;+ /** Identifiers whose `flakiness_state` is `at_risk`. */+ at_risk: number;+ /** Identifiers whose `flakiness_state` is `noisy`. */+ noisy: number;+ /** Identifiers whose `flakiness_state` is `clean`. They are listed because they carry live variants or older history, and reported here so every listed entry is reachable. */+ clean: number;+ /** Listed identifiers per run type, so one suite's noise can be told from another's. */+ by_run_type: FlakinessTotalsByRunType;quarantined: number;needs_decision: number;}