Skip to content

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

fix(visual-review): scope a quarantine lift to the commit it was made at (#103663)

Julian Beza88a353bce94
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index 06c90f10b704..b810d42cf840 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -243,10 +243,12 @@ The story still renders on every run, so a code change to it makes the entry sta
It is also how a story gets an 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 `changed` or `new` snapshot on that run by identifier (the API or the `visual-review-runs-approve-create` MCP tool), finalize the run so the entry is committed to the PR branch, then merge the PR.
-Keep the quarantine on after the merge.
-An entry on the default branch does not reach a branch that forked before it, and healing cannot supply it either: healing reads the merge-base, which for such a branch also predates the entry.
-So every open branch still renders the story with no entry for it, and lifting the quarantine turns those runs `new` and reds their gate.
-Lift it once the open branches that render the story carry the entry, which they do after they merge the default branch.
+Lift the quarantine after the merge.
+A lift records the default branch's head commit, and a run whose commit does not contain that commit still treats the story as quarantined.
+That matters because an entry on the default branch does not reach a branch that forked before it, and healing cannot supply it either: healing reads the merge-base, which for such a branch also predates the entry.
+So an older branch keeps the quarantine until it merges the default branch, and the lift cannot red its gate.
+The scope lasts `LIFT_SCOPE_DAYS` from the lift, and after that the lift applies to every branch.
+A quarantine that expires on its own date records no commit, so its end applies to every branch at once.
**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.
diff --git a/products/visual_review/backend/admin.py b/products/visual_review/backend/admin.py
index 58b59a920b21..474c4b011690 100644
--- a/products/visual_review/backend/admin.py
+++ b/products/visual_review/backend/admin.py
@@ -609,6 +609,7 @@ class QuarantinedIdentifierAdmin(admin.ModelAdmin):
"reason",
"source",
"expires_at",
+ "lifted_at_sha",
"created_by_id",
"created_by_link",
"created_at",
diff --git a/products/visual_review/backend/logic/gating.py b/products/visual_review/backend/logic/gating.py
index 180c12e6a4a1..b09af384e87c 100644
--- a/products/visual_review/backend/logic/gating.py
+++ b/products/visual_review/backend/logic/gating.py
@@ -8,18 +8,21 @@ from django.utils import timezone
from ..db import WRITER_DB
from ..facade.enums import INTENTIONAL_TOLERATE_REASONS, ReviewState, RunPurpose, SnapshotResult
from ..models import QuarantinedIdentifier, Run, RunSnapshot
-from . import baselines, ci_status, comment_markdown, comments
+from . import baselines, ci_status, comment_markdown, comments, quarantine
def _stamp_quarantine(run: Run) -> None:
- """Evaluate quarantine policy and freeze it on each snapshot."""
+ """Evaluate quarantine policy and freeze it on each snapshot.
+
+ A quarantine lifted at a commit this run does not contain still applies to this run.
+ """
now = timezone.now()
quarantined_ids = set(
QuarantinedIdentifier.objects.using(WRITER_DB)
.filter(repo_id=run.repo_id, run_type=run.run_type, team_id=run.team_id)
.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))
.values_list("identifier", flat=True)
- )
+ ) | quarantine.identifiers_lifted_after_commit(run, now=now)
if not quarantined_ids:
run.snapshots.using(WRITER_DB).filter(is_quarantined=True).update(is_quarantined=False)
diff --git a/products/visual_review/backend/logic/github_api.py b/products/visual_review/backend/logic/github_api.py
index ef69806721d4..49e4c38e9a46 100644
--- a/products/visual_review/backend/logic/github_api.py
+++ b/products/visual_review/backend/logic/github_api.py
@@ -66,6 +66,55 @@ def _get_default_branch(github: GitHubIntegration, repo_full_name: str) -> str:
return "master"
+def default_branch_head_sha(repo: Repo) -> str | None:
+ """The commit the repo's default branch points at, or None when GitHub cannot say."""
+ try:
+ github = get_github_integration_for_repo(repo)
+ # Not `_get_default_branch`: its fallback name can point at a branch that is not the default,
+ # and a commit from that branch would scope the lift wrongly.
+ branch = github.get_default_branch(repo.repo_full_name)
+ # One path segment, so a branch name with a slash does not split the ref.
+ response = github.api_request("GET", f"/repos/{repo.repo_full_name}/commits/{quote(branch, safe='')}")
+ except Exception:
+ logger.warning("visual_review.default_branch_head_fetch_failed", repo_id=str(repo.id))
+ return None
+ if response.status_code != 200:
+ logger.warning(
+ "visual_review.default_branch_head_fetch_failed", repo_id=str(repo.id), status=response.status_code
+ )
+ return None
+ return response.json().get("sha")
+
+
+def _is_ancestor(repo: Repo, ancestor_sha: str, head_sha: str) -> bool | None:
+ """Whether `ancestor_sha` is in the history of `head_sha`, or None when GitHub cannot tell."""
+ try:
+ github = get_github_integration_for_repo(repo)
+ merge_base = _get_merge_base_sha(github, repo.repo_full_name, ancestor_sha, head_sha)
+ except (errors.GitHubIntegrationNotFoundError, GitHubRateLimitError):
+ logger.warning("visual_review.commit_ancestry_unknown", repo_id=str(repo.id), ancestor=ancestor_sha)
+ return None
+ if merge_base is None:
+ return None
+ return merge_base == ancestor_sha
+
+
+def commit_contains(repo: Repo, ancestor_sha: str, head_sha: str) -> bool:
+ """Whether `ancestor_sha` is in the history of `head_sha`. False when GitHub cannot tell.
+
+ Two commits never change their ancestry, so a known answer is cached and later calls for the
+ same pair make no request. An unknown answer is not cached, so the next call asks again.
+ """
+ if ancestor_sha == head_sha:
+ return True
+ ancestry = content_cache.load_by_hash(
+ "commit_ancestry",
+ f"{repo.id}:{ancestor_sha}..{head_sha}",
+ lambda: _is_ancestor(repo, ancestor_sha, head_sha),
+ )
+ return ancestry is True
+
+
_MERGE_QUEUE_BRANCH_RE = re.compile(r"^trunk-merge/pr-(?P<pr_number>\d+)/")
diff --git a/products/visual_review/backend/logic/quarantine.py b/products/visual_review/backend/logic/quarantine.py
index 929a2cac7046..bdee2cd4d080 100644
--- a/products/visual_review/backend/logic/quarantine.py
+++ b/products/visual_review/backend/logic/quarantine.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from collections import defaultdict
from datetime import datetime, timedelta
from uuid import UUID
@@ -13,9 +14,13 @@ from ..db import READER_DB, WRITER_DB
from ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS
from ..facade.enums import ActorType
from ..models import QuarantinedIdentifier, Run
-from . import errors, repos
+from . import errors, github_api, repos
from .run_queries import SnapshotKey
+# How long a lift stays scoped to its commit. A branch that forked before the lift and is still
+# open after this has usually merged the default branch since; past it, the lift applies everywhere.
+LIFT_SCOPE_DAYS = 30
+
def list_quarantined_identifiers(
repo_id: UUID, team_id: int, identifier: str | None = None, run_type: str | None = None
@@ -128,13 +133,18 @@ def quarantine_identifier(
def unquarantine_identifier(repo_id: UUID, identifier: str, run_type: str, team_id: int) -> None:
- repos.get_repo(repo_id, team_id) # raises RepoNotFoundError if repo not owned by team
+ repo = repos.get_repo(repo_id, team_id) # raises RepoNotFoundError if repo not owned by team
+ # Take the cutoff before the GitHub request, and lift only rows that existed at the cutoff. A
+ # quarantine that somebody creates while the request is in flight must survive this lift.
+ now = timezone.now()
+ lifted_at_sha = github_api.default_branch_head_sha(repo)
QuarantinedIdentifier.objects.using(WRITER_DB).filter(
repo_id=repo_id,
identifier=identifier,
run_type=run_type,
team_id=team_id,
- ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=timezone.now())).update(expires_at=timezone.now())
+ created_at__lte=now,
+ ).filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)).update(expires_at=now, lifted_at_sha=lifted_at_sha)
def expire_quarantine_entry(entry_id: UUID, team_id: int) -> None:
@@ -145,10 +155,50 @@ def expire_quarantine_entry(entry_id: UUID, team_id: int) -> None:
except QuarantinedIdentifier.DoesNotExist as e:
raise errors.RunNotFoundError(f"Quarantine entry {entry_id} not found or already expired") from e
+ # The cutoff is `now`, taken before the GitHub request, for the same reason as in
+ # `unquarantine_identifier`.
+ lifted_at_sha = github_api.default_branch_head_sha(entry.repo)
# Expire all active entries for the same identifier/run_type, not just this one
QuarantinedIdentifier.objects.using(WRITER_DB).filter(
repo_id=entry.repo_id,
identifier=entry.identifier,
run_type=entry.run_type,
team_id=team_id,
- ).filter(active).update(expires_at=now)
+ created_at__lte=now,
+ ).filter(active).update(expires_at=now, lifted_at_sha=lifted_at_sha)
+
+
+def identifiers_lifted_after_commit(run: Run, *, now: datetime) -> set[str]:
+ """Identifiers in `run` whose quarantine was lifted at a commit that `run`'s commit does not contain.
+
+ Such a run is on a branch that forked before the lift. The quarantine still applies there,
+ because the branch lacks what the lift relied on. It stops applying once the branch merges the
+ default branch. Only the latest quarantine event of an identifier counts, so a lift that a
+ newer quarantine replaced no longer applies. A lift whose ancestry GitHub cannot confirm keeps
+ applying the quarantine, because a missed gate costs less than a red run that nobody on the
+ branch can fix.
+ """
+ latest_events = (
+ QuarantinedIdentifier.objects.using(WRITER_DB)
+ .filter(
+ repo_id=run.repo_id,
+ run_type=run.run_type,
+ team_id=run.team_id,
+ identifier__in=run.snapshots.using(WRITER_DB).values("identifier"),
+ )
+ .order_by("identifier", "-created_at")
+ .distinct("identifier")
+ .values_list("identifier", "lifted_at_sha", "expires_at")
+ )
+ scope_start = now - timedelta(days=LIFT_SCOPE_DAYS)
+ identifiers_by_sha: dict[str, set[str]] = defaultdict(set)
+ for identifier, lifted_at_sha, expires_at in latest_events:
+ if lifted_at_sha is not None and expires_at is not None and scope_start < expires_at <= now:
+ identifiers_by_sha[lifted_at_sha].add(identifier)
+
+ return {
+ identifier
+ for lifted_at_sha, identifiers in identifiers_by_sha.items()
+ if not github_api.commit_contains(run.repo, lifted_at_sha, run.commit_sha)
+ for identifier in identifiers
+ }
diff --git a/products/visual_review/backend/migrations/0016_quarantinedidentifier_lifted_at_sha.py b/products/visual_review/backend/migrations/0016_quarantinedidentifier_lifted_at_sha.py
new file mode 100644
index 000000000000..508ddcfa72ee
--- /dev/null
+++ b/products/visual_review/backend/migrations/0016_quarantinedidentifier_lifted_at_sha.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-09-21 12:00
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("visual_review", "0015_repo_debt_digest_enabled"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="quarantinedidentifier",
+ name="lifted_at_sha",
+ field=models.CharField(blank=True, max_length=40, null=True),
+ ),
+ ]
diff --git a/products/visual_review/backend/migrations/max_migration.txt b/products/visual_review/backend/migrations/max_migration.txt
index c0e36f42c330..046f442325c1 100644
--- a/products/visual_review/backend/migrations/max_migration.txt
+++ b/products/visual_review/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0015_repo_debt_digest_enabled
+0016_quarantinedidentifier_lifted_at_sha
diff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.py
index 57094dc38e18..cf726b2d3f71 100644
--- a/products/visual_review/backend/models.py
+++ b/products/visual_review/backend/models.py
@@ -393,6 +393,11 @@ class QuarantinedIdentifier(ProductTeamModel):
blank=True,
related_name="originated_quarantines",
)
+ # The default-branch head when the quarantine was lifted. A run on a commit that does not
+ # contain it still treats the identifier as quarantined: that branch forked before the lift,
+ # so it lacks what the lift relied on, such as a baseline entry that landed on the default
+ # branch. Null for a quarantine that expired on its own or was lifted before this column.
+ lifted_at_sha = models.CharField(max_length=40, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/visual_review/backend/tests/logic/test_gating.py b/products/visual_review/backend/tests/logic/test_gating.py
index 005e2f1c3e7a..87e978a9f228 100644
--- a/products/visual_review/backend/tests/logic/test_gating.py
+++ b/products/visual_review/backend/tests/logic/test_gating.py
@@ -2,9 +2,11 @@
import pytest
+from django.utils import timezone
+
from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
from products.visual_review.backend.facade.enums import RunType
-from products.visual_review.backend.logic import approvals, artifact_store, quarantine, repos, runs
+from products.visual_review.backend.logic import approvals, artifact_store, github_api, quarantine, repos, runs
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -71,9 +73,32 @@ class TestQuarantineStamping:
assert snapshots["Button-secondary"].is_quarantined is False
assert snapshots["Card-default"].is_quarantined is False
- def test_unquarantine_clears_flag_on_approve(self, repo, team, user, mocker):
+ @pytest.mark.parametrize(
+ ("lifted_at_sha", "merge_base", "superseded", "expect_quarantined"),
+ [
+ (None, None, False, False),
+ ("lift", "lift", False, False),
+ ("lift", "older", False, True),
+ ("lift", None, False, True),
+ ("lift", "older", True, False),
+ ],
+ ids=[
+ "lift-without-sha",
+ "run-contains-lift",
+ "branch-forked-before-lift",
+ "ancestry-unknown",
+ "lift-superseded-by-newer-quarantine",
+ ],
+ )
+ def test_unquarantine_clears_flag_on_approve(
+ self, repo, team, user, mocker, lifted_at_sha, merge_base, superseded, expect_quarantined
+ ):
from products.visual_review.backend.models import QuarantinedIdentifier
+ mocker.patch.object(github_api, "default_branch_head_sha", return_value=lifted_at_sha)
+ mocker.patch.object(github_api, "get_github_integration_for_repo")
+ mocker.patch.object(github_api, "_get_merge_base_sha", return_value=merge_base)
+
# Create quarantine entry
QuarantinedIdentifier.objects.create(
repo=repo,
@@ -99,12 +124,21 @@ class TestQuarantineStamping:
quarantine.unquarantine_identifier(
repo_id=repo.id, identifier="Button-primary", run_type=RunType.STORYBOOK, team_id=team.id
)
+ if superseded:
+ QuarantinedIdentifier.objects.create(
+ repo=repo,
+ team_id=team.id,
+ identifier="Button-primary",
+ run_type=RunType.STORYBOOK,
+ reason="flaky again",
+ expires_at=timezone.now(),
+ )
# Finalize the run — _stamp_quarantine re-evaluates
approvals.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)
snapshot.refresh_from_db()
- assert snapshot.is_quarantined is False
+ assert snapshot.is_quarantined is expect_quarantined
def test_quarantine_excludes_from_changed_count(self, repo, team, mocker):
from products.visual_review.backend.models import QuarantinedIdentifier