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.

chore(visual-review): tighten run retention windows (#104475)

Julian Bez840d59cf9443
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index 27a2fe7c51fa..6ac290cc7079 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -32,9 +32,11 @@ No sync problems, no "baseline service went down", no mystery diffs from someone
Two daily Celery tasks delete data that can no longer be used: `sweep visual review runs`, and an hour later `sweep visual review artifacts`.
The windows and the reasons behind them are constants in `backend/logic/retention.py`.
-- Superseded runs on PR branches go after 30 days, on the default branch after 180 days.
+- Superseded runs on PR branches go after 3 days, on the default branch after 180 days.
A run without a PR number counts as default-branch history, because we do not record a repo's real default branch.
-- A PR branch with no run in 90 days loses its latest runs too, except the repo's newest completed full run per run type, which is the last row naming the committed baseline hashes.
+- A PR branch with no run in 30 days loses its latest runs too, except the repo's newest completed full run per run type, which is the last row naming the committed baseline hashes.
+ Merge-queue branches (`trunk-merge/`) hold one batch run each and go after 7 days.
+- A run that an active quarantine names as its source stays, so the quarantine can still show where it came from.
- Artifacts go by reference, never by age: content addressing means one upload backs every later run with the same pixels.
An artifact goes when no snapshot of the repo points at it or names its hash, no artifact uses it as a thumbnail, and it is over 7 days old.
- Rows go before objects, and run registration and the delete share a per-repo lock, so a run is never told an artifact exists that the sweep then removes.
diff --git a/products/visual_review/backend/logic/quarantine.py b/products/visual_review/backend/logic/quarantine.py
index bdee2cd4d080..acc70828ce1d 100644
--- a/products/visual_review/backend/logic/quarantine.py
+++ b/products/visual_review/backend/logic/quarantine.py
@@ -110,26 +110,35 @@ def quarantine_identifier(
# quarantine itself still wins; we just lose the "what was wrong" pointer.
# We fetch (not just .exists()) so the facade can serialize source_run
# without a lazy-load on the freshly-created row.
- source_run: Run | None = None
- if source_run_id is not None:
- source_run = Run.objects.using(WRITER_DB).filter(id=source_run_id, repo_id=repo_id, team_id=team_id).first()
- QuarantinedIdentifier.objects.using(WRITER_DB).select_for_update().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=now)).update(expires_at=now)
- return QuarantinedIdentifier.objects.using(WRITER_DB).create(
- repo_id=repo_id,
- identifier=identifier,
- run_type=run_type,
- team_id=team_id,
- reason=reason,
- expires_at=expires_at,
- created_by_id=user_id,
- source_run=source_run,
- source=source,
- )
+ # The source run is locked first, in the same order as the retention sweep,
+ # so a run the sweep deletes meanwhile resolves to None instead of failing
+ # the insert.
+ with transaction.atomic(using=WRITER_DB):
+ source_run: Run | None = None
+ if source_run_id is not None:
+ source_run = (
+ Run.objects.using(WRITER_DB)
+ .select_for_update()
+ .filter(id=source_run_id, repo_id=repo_id, team_id=team_id)
+ .first()
+ )
+ QuarantinedIdentifier.objects.using(WRITER_DB).select_for_update().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=now)).update(expires_at=now)
+ return QuarantinedIdentifier.objects.using(WRITER_DB).create(
+ repo_id=repo_id,
+ identifier=identifier,
+ run_type=run_type,
+ team_id=team_id,
+ reason=reason,
+ expires_at=expires_at,
+ created_by_id=user_id,
+ source_run=source_run,
+ source=source,
+ )
def unquarantine_identifier(repo_id: UUID, identifier: str, run_type: str, team_id: int) -> None:
diff --git a/products/visual_review/backend/logic/retention.py b/products/visual_review/backend/logic/retention.py
index 69b241a30536..be1eb7004bf4 100644
--- a/products/visual_review/backend/logic/retention.py
+++ b/products/visual_review/backend/logic/retention.py
@@ -22,7 +22,7 @@ from posthog.exceptions_capture import capture_exception
from ..db import READER_DB, WRITER_DB
from ..facade.enums import RunStatus
-from ..models import Artifact, Repo, Run, RunSnapshot
+from ..models import Artifact, QuarantinedIdentifier, Repo, Run, RunSnapshot
from ..storage import ArtifactStorage, StoryIndexStorage
from . import artifact_store, run_queries, story_index
@@ -33,8 +33,8 @@ T = TypeVar("T")
# A superseded run on a PR branch is history that no page reads after the next
# push replaces it. Its last readers are the "stale" review-state filter and the
# run detail page, so this window is a grace period for people who open an old
-# link.
-SUPERSEDED_RUN_RETENTION_DAYS = 30
+# link, and for a flake someone debugs after a weekend.
+SUPERSEDED_RUN_RETENTION_DAYS = 3
# Default-branch runs feed the baseline overview (90 days) and the snapshot
# history page, which is unbounded, so they are kept much longer.
@@ -42,7 +42,12 @@ DEFAULT_BRANCH_RUN_RETENTION_DAYS = 180
# A PR branch with no run this recent belongs to a merged or abandoned PR.
# Nothing links to it any more, so its latest runs go too.
-QUIET_BRANCH_RETENTION_DAYS = 90
+QUIET_BRANCH_RETENTION_DAYS = 30
+
+# Each merge-queue batch runs once on its own branch, and the PR's own runs keep
+# the review history.
+MERGE_QUEUE_BRANCH_PREFIX = "trunk-merge/"
+MERGE_QUEUE_RUN_RETENTION_DAYS = 7
# An artifact can exist for a short time before anything names it, because a
# diff or thumbnail image is written to storage first and linked to its snapshot
@@ -69,8 +74,17 @@ MAX_ARTIFACTS_PER_SWEEP = 20_000
SWEEP_TIME_BUDGET_SECONDS = 15 * 60
# Repos do not record their real default branch, so a run with no PR number is
-# read as default-branch history and the rule fails toward keeping it.
-_PROTECTED_HISTORY = Q(branch__in=run_queries._DEFAULT_BRANCHES) | Q(pr_number__isnull=True)
+# read as default-branch history and the rule fails toward keeping it. A
+# merge-queue branch is never the default branch, whatever its PR number.
+_PROTECTED_HISTORY = Q(branch__in=run_queries._DEFAULT_BRANCHES) | (
+ Q(pr_number__isnull=True) & ~Q(branch__startswith=MERGE_QUEUE_BRANCH_PREFIX)
+)
+
+# Merge-queue first, because the general pass would keep them for the full window.
+_QUIET_BRANCH_PASSES = (
+ (MERGE_QUEUE_RUN_RETENTION_DAYS, Q(branch__startswith=MERGE_QUEUE_BRANCH_PREFIX)),
+ (QUIET_BRANCH_RETENTION_DAYS, Q()),
+)
# The row goes first and the object second, and the DELETE repeats the reference
# checks of the candidate query, so a reference acquired between the SELECT and
@@ -141,19 +155,42 @@ class RetentionSweep:
def _artifacts(self) -> QuerySet[Artifact]:
return Artifact.objects.for_team(self.team_id, canonical=True).using(WRITER_DB).filter(repo_id=self.repo.id)
+ def _source_of_active_quarantine(self) -> Exists:
+ # The quarantine UI shows the commit, branch and PR of this run.
+ return Exists(
+ QuarantinedIdentifier.objects.for_team(self.team_id, canonical=True)
+ .using(WRITER_DB)
+ .filter(source_run_id=OuterRef("id"))
+ .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=self.now))
+ )
+
def _expired_superseded_run_ids(self, limit: int) -> list[UUID]:
+ merge_queue = Q(branch__startswith=MERGE_QUEUE_BRANCH_PREFIX)
+ # A PR-branch run's grace starts when its successor arrives, so a run left
+ # alone for days still keeps its window after the next push.
expired = (
- _PROTECTED_HISTORY & Q(created_at__lt=self.now - timedelta(days=DEFAULT_BRANCH_RUN_RETENTION_DAYS))
- ) | (~_PROTECTED_HISTORY & Q(created_at__lt=self.now - timedelta(days=SUPERSEDED_RUN_RETENTION_DAYS)))
+ (_PROTECTED_HISTORY & Q(created_at__lt=self.now - timedelta(days=DEFAULT_BRANCH_RUN_RETENTION_DAYS)))
+ | (
+ ~_PROTECTED_HISTORY
+ & ~merge_queue
+ & Q(superseded_by__created_at__lt=self.now - timedelta(days=SUPERSEDED_RUN_RETENTION_DAYS))
+ )
+ | (
+ ~_PROTECTED_HISTORY
+ & merge_queue
+ & Q(superseded_by__created_at__lt=self.now - timedelta(days=MERGE_QUEUE_RUN_RETENTION_DAYS))
+ )
+ )
return list(
self._runs()
.filter(Q(superseded_by__isnull=False) & expired)
+ .exclude(self._source_of_active_quarantine())
.order_by("created_at")
.values_list("id", flat=True)[:limit]
)
- def _quiet_branch_run_ids(self, limit: int) -> list[UUID]:
- quiet_cutoff = self.now - timedelta(days=QUIET_BRANCH_RETENTION_DAYS)
+ def _quiet_branch_run_ids(self, limit: int, *, quiet_days: int, branches: Q) -> list[UUID]:
+ quiet_cutoff = self.now - timedelta(days=quiet_days)
recent_run_on_branch = self._runs().filter(branch=OuterRef("branch"), created_at__gte=quiet_cutoff)
# Every superseded run of a group points at the group's latest run, so
# the latest run can only go when none of them is left.
@@ -175,8 +212,9 @@ class RetentionSweep:
)
return list(
self._runs()
- .filter(superseded_by__isnull=True, created_at__lt=quiet_cutoff)
+ .filter(branches, superseded_by__isnull=True, created_at__lt=quiet_cutoff)
.exclude(_PROTECTED_HISTORY)
+ .exclude(self._source_of_active_quarantine())
.filter(~Exists(recent_run_on_branch), ~Exists(superseded_run_in_group), Exists(newer_completed_run))
.order_by("created_at")
.values_list("id", flat=True)[:limit]
@@ -214,6 +252,12 @@ class RetentionSweep:
if self._out_of_time():
break
with transaction.atomic(using=WRITER_DB):
+ # A quarantine can name the run after the candidate query read it.
+ # Its insert takes a key-share lock on the run row, so locking the
+ # row first makes the check and the delete see the same quarantines.
+ list(self._runs().select_for_update().filter(id=run_id).values_list("id", flat=True))
+ if self._runs().filter(self._source_of_active_quarantine(), id=run_id).exists():
+ continue
self._splice_out_of_chain(run_id)
_total, per_model = self._runs().filter(id=run_id).delete()
run_deleted = per_model.get(Run._meta.label, 0)
@@ -223,17 +267,21 @@ class RetentionSweep:
return deleted
def delete_expired_runs(self) -> int:
- # Both candidate queries are expensive reads, so each one runs only when
+ # The candidate queries are expensive reads, so each one runs only when
# there is time left to act on its result.
if self._out_of_time():
return 0
deleted = self._delete_runs(self._expired_superseded_run_ids(MAX_RUNS_PER_SWEEP))
- remaining = MAX_RUNS_PER_SWEEP - deleted
- if remaining <= 0 or self._out_of_time():
- return deleted
- # The quiet-branch pass reads the groups the pass above has already
- # emptied, so the two cannot run in the other order.
- return deleted + self._delete_runs(self._quiet_branch_run_ids(remaining))
+ # The quiet-branch passes read the groups the pass above has already
+ # emptied, so they cannot run before it.
+ for quiet_days, branches in _QUIET_BRANCH_PASSES:
+ remaining = MAX_RUNS_PER_SWEEP - deleted
+ if remaining <= 0 or self._out_of_time():
+ break
+ deleted += self._delete_runs(
+ self._quiet_branch_run_ids(remaining, quiet_days=quiet_days, branches=branches)
+ )
+ return deleted
def _unreferenced_artifact_ids(self, limit: int) -> list[UUID]:
snapshots = self._snapshots()
diff --git a/products/visual_review/backend/tests/logic/test_retention.py b/products/visual_review/backend/tests/logic/test_retention.py
index 2d2113507cae..96724482a3a1 100644
--- a/products/visual_review/backend/tests/logic/test_retention.py
+++ b/products/visual_review/backend/tests/logic/test_retention.py
@@ -1,6 +1,6 @@
"""Unit tests for logic/retention.py, the run and artifact retention sweep."""
-from datetime import date, timedelta
+from datetime import UTC, date, datetime, timedelta
import pytest
@@ -80,8 +80,11 @@ class TestRetentionSweep:
@pytest.mark.parametrize(
("branch", "pr_number", "age_days", "survives"),
[
- ("feature/x", 7, 31, False),
- ("feature/x", 7, 29, True),
+ ("feature/x", 7, 4, False),
+ ("feature/x", 7, 2, True),
+ ("trunk-merge/pr-7/0c0ffee", 7, 8, False),
+ ("trunk-merge/pr-7/0c0ffee", 7, 6, True),
+ ("trunk-merge/pr-7/0c0ffee", None, 8, False),
("master", None, 31, True),
("master", None, 181, False),
("feature/x", None, 31, True),
@@ -97,6 +100,15 @@ class TestRetentionSweep:
assert Run.objects.filter(id=superseded.id).exists() is survives
assert Run.objects.filter(id=latest.id).exists()
+ @pytest.mark.parametrize(("successor_age_days", "survives"), [(2, True), (4, False)])
+ def test_superseded_grace_starts_when_the_successor_arrives(self, successor_age_days, survives, repo, now):
+ latest = self._run(repo, now, age_days=successor_age_days)
+ superseded = self._run(repo, now, age_days=30, superseded_by=latest)
+
+ retention.sweep_repo_runs(repo, now=now)
+
+ assert Run.objects.filter(id=superseded.id).exists() is survives
+
def test_default_branch_latest_run_survives_any_age(self, repo, now):
latest = self._run(repo, now, age_days=400, branch="master", pr_number=None)
@@ -105,8 +117,25 @@ class TestRetentionSweep:
assert result.runs_deleted == 0
assert Run.objects.filter(id=latest.id).exists()
+ @pytest.mark.parametrize(
+ ("branch", "age_days", "survives"),
+ [
+ ("feature/x", 31, False),
+ ("feature/x", 29, True),
+ ("trunk-merge/pr-7/0c0ffee", 8, False),
+ ("trunk-merge/pr-7/0c0ffee", 6, True),
+ ],
+ )
+ def test_quiet_branch_window_depends_on_branch(self, branch, age_days, survives, repo, now):
+ quiet = self._run(repo, now, age_days=age_days, branch=branch)
+ self._run(repo, now, age_days=1, branch="feature/y", pr_number=8)
+
+ retention.sweep_repo_runs(repo, now=now)
+
+ assert Run.objects.filter(id=quiet.id).exists() is survives
+
def test_quiet_branch_group_goes_in_one_sweep(self, repo, now):
- latest = self._run(repo, now, age_days=91)
+ latest = self._run(repo, now, age_days=31)
superseded = self._run(repo, now, age_days=100, superseded_by=latest)
self._run(repo, now, age_days=1, branch="feature/y", pr_number=8)
@@ -116,7 +145,7 @@ class TestRetentionSweep:
assert not Run.objects.filter(id__in=[latest.id, superseded.id]).exists()
def test_quiet_branch_keeps_the_newest_completed_run_of_a_run_type(self, repo, now):
- latest = self._run(repo, now, age_days=91)
+ latest = self._run(repo, now, age_days=31)
assert retention.sweep_repo_runs(repo, now=now).runs_deleted == 0
assert Run.objects.filter(id=latest.id).exists()
@@ -131,7 +160,7 @@ class TestRetentionSweep:
assert not Run.objects.filter(id=latest.id).exists()
def test_quiet_branch_kept_when_another_run_type_is_recent(self, repo, now):
- stale_latest = self._run(repo, now, age_days=91, run_type=RunType.STORYBOOK)
+ stale_latest = self._run(repo, now, age_days=31, run_type=RunType.STORYBOOK)
self._run(repo, now, age_days=2, run_type=RunType.PLAYWRIGHT)
retention.sweep_repo_runs(repo, now=now)
@@ -179,7 +208,14 @@ class TestRetentionSweep:
ToleratedHash,
{"baseline_hash": "base1", "alternate_hash": "alt1", "reason": ToleratedReason.HUMAN},
),
- (QuarantinedIdentifier, {"run_type": RunType.STORYBOOK, "reason": "flaky in CI"}),
+ (
+ QuarantinedIdentifier,
+ {
+ "run_type": RunType.STORYBOOK,
+ "reason": "flaky in CI",
+ "expires_at": datetime(2020, 1, 1, tzinfo=UTC),
+ },
+ ),
],
)
def test_audit_rows_outlive_the_run_that_created_them(self, model, extra_fields, repo, now):
@@ -198,6 +234,27 @@ class TestRetentionSweep:
row.refresh_from_db()
assert row.source_run_id is None
+ @pytest.mark.parametrize("expired_quarantine", [False, True])
+ @pytest.mark.parametrize("source", ["superseded", "quiet"])
+ def test_active_quarantine_keeps_its_source_run(self, source, expired_quarantine, repo, now):
+ latest = self._run(repo, now, age_days=31)
+ superseded = self._run(repo, now, age_days=40, superseded_by=latest)
+ self._run(repo, now, age_days=1, branch="feature/y", pr_number=8)
+ source_run = superseded if source == "superseded" else latest
+ QuarantinedIdentifier.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ identifier="Button",
+ run_type=RunType.STORYBOOK,
+ reason="flaky in CI",
+ source_run=source_run,
+ expires_at=now - timedelta(days=1) if expired_quarantine else None,
+ )
+
+ retention.sweep_repo_runs(repo, now=now)
+
+ assert Run.objects.filter(id=source_run.id).exists() is not expired_quarantine
+
def test_run_cap_bounds_one_invocation(self, repo, now, monkeypatch):
monkeypatch.setattr(retention, "MAX_RUNS_PER_SWEEP", 1)
latest = self._run(repo, now, age_days=91)
@@ -290,7 +347,7 @@ class TestRetentionSweep:
def test_a_story_index_goes_with_the_last_run_that_names_it(self, repo, now, stub_object_delete):
released, shared = "a" * 64, "b" * 64
- latest = self._run(repo, now, age_days=1)
+ latest = self._run(repo, now, age_days=5)
for story_index_hash, run in (
(shared, latest),
(released, self._run(repo, now, age_days=400, superseded_by=latest)),