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.

feat(visual-review): sweep runs and artifacts past their retention window (#96449)

Julian Bez4797ea052b3f
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 16afe3d585cf..44ccbd624468 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -124,6 +124,7 @@ from products.tasks.backend.facade.tasks import (
sweep_inactive_tasks_task,
sweep_loop_task_retention_task,
)
+from products.visual_review.backend.facade.tasks import sweep_visual_review_retention
from products.warehouse_sources.backend.facade.tasks import sweep_stopped_schema_syncs
from products.web_analytics.backend.achievements.tasks import sweep_web_analytics_achievement_team_tracks
from products.web_analytics.backend.tasks.heatmap_screenshot import (
@@ -1012,6 +1013,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="prune old streamlit app versions",
)
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(hour="2", minute=str(randrange(0, 40))),
+ sweep_visual_review_retention.s(),
+ name="sweep visual review retention",
+ )
+
sender.add_periodic_task(
TEST_CENSUS_CRONTAB,
emit_test_ownership_census.s(),
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index c1e7578204ec..7eb4d0bb80a1 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -27,6 +27,20 @@ No sync problems, no "baseline service went down", no mystery diffs from someone
**Supersession** — when a new run is created for the same (repo, branch, run_type), older runs get a `superseded_by` pointer. This prevents approving stale runs without GitHub API polling — the DB knows what's current.
+### Retention
+
+A daily Celery task, `sweep visual review retention`, deletes data that can no longer be used.
+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.
+ 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.
+- 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.
+ An artifact row is what makes the CLI skip an upload, so a row without its object is the one state to avoid; a leaked object only costs storage.
+- Each invocation is capped by rows and by a time budget, so a backlog drains over days.
+
## The flow
### Single-command flow (`vr submit`)
@@ -187,6 +201,5 @@ Variants recorded against a superseded baseline can never match again.
**Not yet built:**
- Auto-release of a quarantine whose snapshot has gone clean (the flakiness tab flags it, a human still decides)
-- Retention / cleanup of old runs and artifacts
- Server-side thumbnailing for the snapshot strip
- Webhook-driven run creation (currently CLI-initiated only)
diff --git a/products/visual_review/backend/facade/tasks.py b/products/visual_review/backend/facade/tasks.py
new file mode 100644
index 000000000000..31b3cc4f25ef
--- /dev/null
+++ b/products/visual_review/backend/facade/tasks.py
@@ -0,0 +1,5 @@
+"""Celery tasks core schedules for visual_review (see products/architecture.md, wiring couplings)."""
+
+from products.visual_review.backend.tasks.tasks import sweep_visual_review_retention
+
+__all__ = ["sweep_visual_review_retention"]
diff --git a/products/visual_review/backend/logic/artifact_store.py b/products/visual_review/backend/logic/artifact_store.py
index b4d3db7ff059..a12271094775 100644
--- a/products/visual_review/backend/logic/artifact_store.py
+++ b/products/visual_review/backend/logic/artifact_store.py
@@ -5,14 +5,29 @@ from __future__ import annotations
from collections.abc import Iterable, Iterator
from uuid import UUID
-from django.db import models as db_models
+from django.db import (
+ connections,
+ models as db_models,
+)
+from ..db import WRITER_DB
from ..models import Artifact, Repo, RunSnapshot
from ..storage import ArtifactStorage
ARTIFACT_HASH_BATCH_SIZE = 500
+def lock_artifact_registry(repo_id: UUID) -> None:
+ """Serialize artifact registration and deletion for one repo until the transaction ends.
+
+ A run registers its hashes and learns which artifacts exist in one transaction. The
+ retention sweep cannot see those rows before the commit, so without this lock it could
+ delete an artifact the run was just told not to upload again.
+ """
+ with connections[WRITER_DB].cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"visual-review-artifacts:{repo_id}"])
+
+
def _iter_batches(values: Iterable[str], batch_size: int) -> Iterator[list[str]]:
batch: list[str] = []
for value in values:
diff --git a/products/visual_review/backend/logic/baseline_overview.py b/products/visual_review/backend/logic/baseline_overview.py
index 2db1fe9eecca..bc61d758abbf 100644
--- a/products/visual_review/backend/logic/baseline_overview.py
+++ b/products/visual_review/backend/logic/baseline_overview.py
@@ -172,7 +172,9 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
# across all completed master/main runs ever. Real baseline flips on
# master leave a CHANGED/REMOVED row in the run that introduced them
# (subsequent runs see UNCHANGED against the new YAML baseline), so
- # this count IS the number of times the YAML moved. Postgres uses
+ # this count IS the number of times the YAML moved. "Ever" reaches
+ # back as far as retention keeps default-branch runs, which is
+ # `retention.DEFAULT_BRANCH_RUN_RETENTION_DAYS`. Postgres uses
# the `snapshot_run_result` index on (run_id, result) to bitmap-scan
# straight to the rare event rows (~1k of millions). No window
# function, no per-row LAG comparison.
diff --git a/products/visual_review/backend/logic/flakiness.py b/products/visual_review/backend/logic/flakiness.py
index 7e35ae9353ef..c2da8bd5b774 100644
--- a/products/visual_review/backend/logic/flakiness.py
+++ b/products/visual_review/backend/logic/flakiness.py
@@ -344,7 +344,9 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:
# precisely, but it admits every historical row rather than the rare event
# rows, which is the shape `baseline_overview` documents as ~7s and an OOM
# on the web pod. This uses the `snapshot_run_result` index the same way its
- # neighbour does.
+ # neighbour does. The history it reads reaches back only as far as retention
+ # keeps default-branch runs, which is
+ # `retention.DEFAULT_BRANCH_RUN_RETENTION_DAYS`.
baseline_moved_at_by_key: dict[_SnapshotKey, datetime] = {}
for identifier, run_type, moved_at in (
RunSnapshot.objects.filter(
diff --git a/products/visual_review/backend/logic/history.py b/products/visual_review/backend/logic/history.py
index a88add9af30d..49344219d406 100644
--- a/products/visual_review/backend/logic/history.py
+++ b/products/visual_review/backend/logic/history.py
@@ -1,4 +1,8 @@
-"""Baseline timeline for a single snapshot identifier."""
+"""Baseline timeline for a single snapshot identifier.
+
+The timeline reaches back only as far as retention keeps default-branch runs,
+which is `retention.DEFAULT_BRANCH_RUN_RETENTION_DAYS`.
+"""
from __future__ import annotations
diff --git a/products/visual_review/backend/logic/retention.py b/products/visual_review/backend/logic/retention.py
new file mode 100644
index 000000000000..723aa261d85c
--- /dev/null
+++ b/products/visual_review/backend/logic/retention.py
@@ -0,0 +1,272 @@
+"""Retention sweep: deletes expired runs and the artifacts nothing references any more."""
+
+from __future__ import annotations
+
+import time
+from datetime import datetime, timedelta
+from itertools import batched
+from uuid import UUID
+
+from django.db import connections, transaction
+from django.db.models import Exists, OuterRef, Q, QuerySet
+from django.utils import timezone
+
+import structlog
+
+from posthog.dataclasses import frozen
+
+from ..db import WRITER_DB
+from ..facade.enums import RunStatus
+from ..models import Artifact, Repo, Run, RunSnapshot
+from ..storage import ArtifactStorage
+from . import artifact_store, run_queries
+
+logger = structlog.get_logger(__name__)
+
+# 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
+
+# Default-branch runs feed the baseline overview (90 days) and the snapshot
+# history page, which is unbounded, so they are kept much longer.
+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
+
+# 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
+# after. The hash checks in the candidate query cover every state after that, so
+# the grace period only has to cover this gap.
+ARTIFACT_ORPHAN_GRACE_DAYS = 7
+
+ARTIFACT_SWEEP_BATCH = 500
+
+# Caps per invocation. The task runs daily and catches up over several days,
+# which keeps the first sweep of a large backlog off one long transaction.
+MAX_RUNS_PER_SWEEP = 2_000
+MAX_ARTIFACTS_PER_SWEEP = 20_000
+
+# The caps above bound rows, not wall clock. Deletes over the backlog are slow
+# enough that the first sweeps would run for hours, so an invocation also stops
+# when its deadline passes.
+SWEEP_TIME_BUDGET_SECONDS = 30 * 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)
+
+# 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
+# the DELETE keeps the row. An Artifact row is what makes the CLI skip an upload
+# (`find_missing_hashes`), so a row that outlives its object makes every later
+# run point at an image nobody will upload again. A leaked object costs storage
+# and nothing else.
+#
+# The hash checks are scoped to the repo, because an artifact and its storage key
+# belong to one repo, so a snapshot of another repo can never use this row. The id
+# checks need no scope, because an id is unique on its own.
+_DELETE_ARTIFACTS_SQL = """
+DELETE FROM visual_review_artifact a
+WHERE a.id = ANY(%(artifact_ids)s::uuid[])
+ AND a.team_id = %(team_id)s
+ AND NOT EXISTS (SELECT 1 FROM visual_review_runsnapshot s WHERE s.current_artifact_id = a.id)
+ AND NOT EXISTS (SELECT 1 FROM visual_review_runsnapshot s WHERE s.baseline_artifact_id = a.id)
+ AND NOT EXISTS (SELECT 1 FROM visual_review_runsnapshot s WHERE s.diff_artifact_id = a.id)
+ AND NOT EXISTS (
+ SELECT 1 FROM visual_review_runsnapshot s
+ JOIN visual_review_run r ON r.id = s.run_id
+ WHERE s.team_id = a.team_id AND r.repo_id = a.repo_id AND s.current_hash = a.content_hash
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM visual_review_runsnapshot s
+ JOIN visual_review_run r ON r.id = s.run_id
+ WHERE s.team_id = a.team_id AND r.repo_id = a.repo_id AND s.baseline_hash = a.content_hash
+ )
+ AND NOT EXISTS (SELECT 1 FROM visual_review_artifact t WHERE t.thumbnail_id = a.id)
+RETURNING a.id, a.storage_path
+"""
+
+
+@frozen
+class ArtifactSweepResult:
+ deleted: int
+ objects_leaked: int
+
+
+@frozen
+class RetentionSweepResult:
+ runs_deleted: int
+ artifacts_deleted: int
+ objects_leaked: int
+
+
+class RetentionSweep:
+ """Applies the retention policy to one repo."""
+
+ def __init__(self, repo: Repo, now: datetime, deadline: float) -> None:
+ self.repo = repo
+ # ProductTeamModel.save() writes the canonical team_id, so the stored
+ # value needs no second resolution.
+ self.team_id = repo.team_id
+ self.now = now
+ self.deadline = deadline
+
+ def _out_of_time(self) -> bool:
+ return time.monotonic() >= self.deadline
+
+ def _runs(self) -> QuerySet[Run]:
+ return Run.objects.for_team(self.team_id, canonical=True).using(WRITER_DB).filter(repo_id=self.repo.id)
+
+ def _snapshots(self) -> QuerySet[RunSnapshot]:
+ return RunSnapshot.objects.for_team(self.team_id, canonical=True).using(WRITER_DB)
+
+ 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 _expired_superseded_run_ids(self, limit: int) -> list[UUID]:
+ 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)))
+ return list(
+ self._runs()
+ .filter(Q(superseded_by__isnull=False) & expired)
+ .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)
+ 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.
+ superseded_run_in_group = self._runs().filter(
+ branch=OuterRef("branch"),
+ run_type=OuterRef("run_type"),
+ superseded_by__isnull=False,
+ )
+ # When the repo has no protected-history run, the snapshot rows of the
+ # newest completed run of a run type are the only thing left that names
+ # the baseline hashes committed to the repo, whatever their branch.
+ # A partial run skips the identifiers outside its subset, so it names
+ # only part of the baseline and cannot take over as the keeper.
+ newer_completed_run = self._runs().filter(
+ run_type=OuterRef("run_type"),
+ status=RunStatus.COMPLETED,
+ is_partial=False,
+ created_at__gt=OuterRef("created_at"),
+ )
+ return list(
+ self._runs()
+ .filter(superseded_by__isnull=True, created_at__lt=quiet_cutoff)
+ .exclude(_PROTECTED_HISTORY)
+ .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]
+ )
+
+ def _delete_runs(self, run_ids: list[UUID]) -> int:
+ deleted = 0
+ # One run per DELETE, in the order given (oldest first). Django applies
+ # SET_NULL to the runs that point at a deleted run before it deletes
+ # anything, so a batch that holds two links of one supersession chain
+ # would set the older link to NULL while the group's latest run still
+ # exists and break the unique_latest_run_per_group index.
+ for run_id in run_ids:
+ if self._out_of_time():
+ break
+ _total, per_model = self._runs().filter(id=run_id).delete()
+ deleted += per_model.get(Run._meta.label, 0)
+ return deleted
+
+ def delete_expired_runs(self) -> int:
+ # Both 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))
+
+ def _unreferenced_artifact_ids(self, limit: int) -> list[UUID]:
+ snapshots = self._snapshots()
+ return list(
+ self._artifacts()
+ .filter(created_at__lt=self.now - timedelta(days=ARTIFACT_ORPHAN_GRACE_DAYS))
+ .filter(
+ ~Exists(snapshots.filter(current_artifact_id=OuterRef("id"))),
+ ~Exists(snapshots.filter(baseline_artifact_id=OuterRef("id"))),
+ ~Exists(snapshots.filter(diff_artifact_id=OuterRef("id"))),
+ # A snapshot names its images by hash when the run is created
+ # and gets its artifact FKs only when the link step and the
+ # classifier run, so a NULL FK does not mean the row is free.
+ ~Exists(snapshots.filter(run__repo_id=self.repo.id, current_hash=OuterRef("content_hash"))),
+ ~Exists(snapshots.filter(run__repo_id=self.repo.id, baseline_hash=OuterRef("content_hash"))),
+ # A thumbnail stays while the artifact that points at it exists.
+ # That artifact's delete leaves the thumbnail unreferenced, and
+ # the next sweep collects it.
+ ~Exists(self._artifacts().filter(thumbnail_id=OuterRef("id"))),
+ )
+ .values_list("id", flat=True)[:limit]
+ )
+
+ def _delete_artifact_rows(self, artifact_ids: list[UUID]) -> list[tuple[UUID, str]]:
+ with transaction.atomic(using=WRITER_DB), connections[WRITER_DB].cursor() as cursor:
+ artifact_store.lock_artifact_registry(self.repo.id)
+ cursor.execute(
+ _DELETE_ARTIFACTS_SQL,
+ {"artifact_ids": [str(artifact_id) for artifact_id in artifact_ids], "team_id": self.team_id},
+ )
+ return [(row[0], row[1]) for row in cursor.fetchall()]
+
+ def delete_orphaned_artifacts(self) -> ArtifactSweepResult:
+ # The candidate query is the most expensive read of the sweep, so it
+ # runs only when there is time left to act on its result.
+ if self._out_of_time():
+ return ArtifactSweepResult(deleted=0, objects_leaked=0)
+
+ storage = ArtifactStorage(str(self.repo.id))
+ candidates = self._unreferenced_artifact_ids(MAX_ARTIFACTS_PER_SWEEP)
+
+ deleted = 0
+ objects_leaked = 0
+ for batch in batched(candidates, ARTIFACT_SWEEP_BATCH, strict=False):
+ if self._out_of_time():
+ break
+ deleted_rows = self._delete_artifact_rows(list(batch))
+ deleted += len(deleted_rows)
+ failed_paths = storage.delete_paths([storage_path for _, storage_path in deleted_rows])
+ objects_leaked += len(failed_paths)
+
+ if objects_leaked:
+ logger.warning(
+ "visual_review.retention_artifact_object_leaked",
+ repo_id=str(self.repo.id),
+ team_id=self.team_id,
+ objects_leaked=objects_leaked,
+ )
+ return ArtifactSweepResult(deleted=deleted, objects_leaked=objects_leaked)
+
+
+def sweep_repo(repo: Repo, now: datetime | None = None, deadline: float | None = None) -> RetentionSweepResult:
+ sweep = RetentionSweep(
+ repo,
+ now or timezone.now(),
+ deadline if deadline is not None else time.monotonic() + SWEEP_TIME_BUDGET_SECONDS,
+ )
+ # Runs go first, because the snapshot rows they take with them are what
+ # holds most artifacts in use.
+ runs_deleted = sweep.delete_expired_runs()
+ artifacts = sweep.delete_orphaned_artifacts()
+ return RetentionSweepResult(
+ runs_deleted=runs_deleted,
+ artifacts_deleted=artifacts.deleted,
+ objects_leaked=artifacts.objects_leaked,
+ )
diff --git a/products/visual_review/backend/logic/runs.py b/products/visual_review/backend/logic/runs.py
index 5e1bf9f30e8f..16d4e0ed374d 100644
--- a/products/visual_review/backend/logic/runs.py
+++ b/products/visual_review/backend/logic/runs.py
@@ -138,6 +138,7 @@ def _register_snapshots(
added_count += 1
# Generate upload URLs for missing artifacts
+ artifact_store.lock_artifact_registry(repo_id)
missing_hashes = artifact_store.find_missing_hashes(repo_id, list(all_hashes))
storage = ArtifactStorage(str(repo_id))
diff --git a/products/visual_review/backend/storage.py b/products/visual_review/backend/storage.py
index 7d59963c5a78..4403f9940eaa 100644
--- a/products/visual_review/backend/storage.py
+++ b/products/visual_review/backend/storage.py
@@ -66,6 +66,13 @@ class ArtifactStorage:
object_storage.delete(self._key(content_hash))
+ def delete_paths(self, storage_paths: list[str]) -> list[str]:
+ """Delete objects in bulk by stored key. Returns the paths that were not deleted."""
+ if not settings.OBJECT_STORAGE_ENABLED:
+ return []
+
+ return object_storage.delete_objects(storage_paths)
+
def write(self, content_hash: str, content: bytes) -> str:
"""
Directly write content to storage (for server-side uploads like diff images).
diff --git a/products/visual_review/backend/tasks/__init__.py b/products/visual_review/backend/tasks/__init__.py
index 3dc68f7d1cab..9dedc8602749 100644
--- a/products/visual_review/backend/tasks/__init__.py
+++ b/products/visual_review/backend/tasks/__init__.py
@@ -1,4 +1,8 @@
# Re-export tasks for Celery autodiscover
-from products.visual_review.backend.tasks.tasks import post_approval_comment, process_run_diffs
+from products.visual_review.backend.tasks.tasks import (
+ post_approval_comment,
+ process_run_diffs,
+ sweep_visual_review_retention,
+)
-__all__ = ["post_approval_comment", "process_run_diffs"]
+__all__ = ["post_approval_comment", "process_run_diffs", "sweep_visual_review_retention"]
diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.py
index 463ed3865741..85b64402622f 100644
--- a/products/visual_review/backend/tasks/tasks.py
+++ b/products/visual_review/backend/tasks/tasks.py
@@ -8,6 +8,7 @@ NOTE: Imports are done inside functions to avoid circular imports
when Celery loads this module at startup.
"""
+import time
from uuid import UUID
import structlog
@@ -15,9 +16,13 @@ from celery import shared_task
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
+from posthog.exceptions_capture import capture_exception
from posthog.models.scoping import with_team_scope
+from posthog.scoping_audit import skip_team_scope_audit
+from ..db import READER_DB
from ..logic.errors import HashIntegrityError
+from ..models import Repo
logger = structlog.get_logger(__name__)
TRACER = trace.get_tracer(__name__)
@@ -154,3 +159,50 @@ def post_approval_comment(self, team_id: int, run_id: str, add_images: bool = Fa
logger.warning("visual_review.approval_comment_giving_up", run_id=run_id)
except Exception:
logger.exception("visual_review.approval_comment_task_failed", run_id=run_id, team_id=team_id)
+
+
+@shared_task(
+ name="products.visual_review.backend.tasks.sweep_visual_review_retention",
+ ignore_result=True,
+)
+@skip_team_scope_audit # cross-team housekeeping; sweep_repo scopes every query to the repo's team
+def sweep_visual_review_retention() -> None:
+ """Apply the retention policy to every repo.
+
+ One repo's failure must not stop the rest, so each repo is swept on its
+ own and the next daily run retries whatever failed.
+ """
+ from ..logic import retention # noqa: PLC0415 — avoids the logic/tasks circular import
+
+ deadline = time.monotonic() + retention.SWEEP_TIME_BUDGET_SECONDS
+ # A handful of rows, materialized so the sweep does not hold a reader cursor
+ # open for its whole run.
+ # nosemgrep: idor-lookup-without-team — cross-team retention sweep, no user input
+ repos = list(Repo.objects.unscoped().using(READER_DB).order_by("created_at"))
+ for swept, repo in enumerate(repos):
+ if time.monotonic() >= deadline:
+ logger.warning(
+ "visual_review.retention_sweep_budget_exhausted",
+ repos_swept=swept,
+ repos_total=len(repos),
+ )
+ break
+ try:
+ result = retention.sweep_repo(repo, deadline=deadline)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception(
+ "visual_review.retention_sweep_failed",
+ repo_id=str(repo.id),
+ team_id=repo.team_id,
+ )
+ continue
+
+ logger.info(
+ "visual_review.retention_sweep_completed",
+ repo_id=str(repo.id),
+ team_id=repo.team_id,
+ runs_deleted=result.runs_deleted,
+ artifacts_deleted=result.artifacts_deleted,
+ objects_leaked=result.objects_leaked,
+ )
diff --git a/products/visual_review/backend/tests/logic/test_retention.py b/products/visual_review/backend/tests/logic/test_retention.py
new file mode 100644
index 000000000000..18d79a453d1c
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_retention.py
@@ -0,0 +1,311 @@
+"""Unit tests for logic/retention.py, the run and artifact retention sweep."""
+
+from datetime import timedelta
+
+import pytest
+
+from django.utils import timezone
+
+from products.visual_review.backend.facade.enums import RunStatus, RunType, ToleratedReason
+from products.visual_review.backend.logic import artifact_store, repos, retention
+from products.visual_review.backend.models import Artifact, QuarantinedIdentifier, Run, RunSnapshot, ToleratedHash
+from products.visual_review.backend.tasks.tasks import sweep_visual_review_retention
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestRetentionSweep:
+ @pytest.fixture(autouse=True)
+ def stub_object_delete(self, mocker, settings):
+ # No test may reach S3. The setting is forced on so the storage layer
+ # takes the delete path regardless of how the suite is configured.
+ settings.OBJECT_STORAGE_ENABLED = True
+ return mocker.patch(
+ "products.visual_review.backend.storage.object_storage.delete_objects",
+ return_value=[],
+ )
+
+ @pytest.fixture
+ def now(self):
+ return timezone.now()
+
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=99999, repo_full_name="org/test")
+
+ @pytest.fixture
+ def other_repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=88888, repo_full_name="org/other")
+
+ def _run(
+ self,
+ repo,
+ now,
+ *,
+ age_days: int,
+ branch: str = "feature/x",
+ run_type: str = RunType.STORYBOOK,
+ pr_number: int | None = 7,
+ superseded_by: Run | None = None,
+ is_partial: bool = False,
+ status: str = RunStatus.COMPLETED,
+ ) -> Run:
+ run = Run.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ branch=branch,
+ run_type=run_type,
+ commit_sha="abc123",
+ pr_number=pr_number,
+ superseded_by=superseded_by,
+ is_partial=is_partial,
+ status=status,
+ )
+ # created_at is auto_now_add, so the age has to be written afterwards.
+ Run.objects.filter(id=run.id).update(created_at=now - timedelta(days=age_days))
+ return run
+
+ def _artifact(self, repo, now, *, content_hash: str, age_days: int, thumbnail: Artifact | None = None) -> Artifact:
+ artifact, _ = artifact_store.get_or_create_artifact(
+ repo_id=repo.id,
+ content_hash=content_hash,
+ storage_path=f"visual_review/{content_hash}",
+ )
+ if thumbnail is not None:
+ artifact.thumbnail = thumbnail
+ artifact.save(update_fields=["thumbnail"])
+ Artifact.objects.filter(id=artifact.id).update(created_at=now - timedelta(days=age_days))
+ return artifact
+
+ @pytest.mark.parametrize(
+ ("branch", "pr_number", "age_days", "survives"),
+ [
+ ("feature/x", 7, 31, False),
+ ("feature/x", 7, 29, True),
+ ("master", None, 31, True),
+ ("master", None, 181, False),
+ ("feature/x", None, 31, True),
+ ("feature/x", None, 181, False),
+ ],
+ )
+ def test_superseded_run_retention_depends_on_branch(self, branch, pr_number, age_days, survives, repo, now):
+ latest = self._run(repo, now, age_days=age_days, branch=branch, pr_number=pr_number)
+ superseded = self._run(repo, now, age_days=age_days, branch=branch, pr_number=pr_number, superseded_by=latest)
+
+ retention.sweep_repo(repo, now=now)
+
+ assert Run.objects.filter(id=superseded.id).exists() is survives
+ assert Run.objects.filter(id=latest.id).exists()
+
+ 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)
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.runs_deleted == 0
+ assert Run.objects.filter(id=latest.id).exists()
+
+ def test_quiet_branch_group_goes_in_one_sweep(self, repo, now):
+ latest = self._run(repo, now, age_days=91)
+ superseded = self._run(repo, now, age_days=100, superseded_by=latest)
+ self._run(repo, now, age_days=1, branch="feature/y", pr_number=8)
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.runs_deleted == 2
+ 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)
+
+ assert retention.sweep_repo(repo, now=now).runs_deleted == 0
+ assert Run.objects.filter(id=latest.id).exists()
+
+ self._run(repo, now, age_days=2, branch="feature/z", pr_number=9, is_partial=True)
+
+ assert retention.sweep_repo(repo, now=now).runs_deleted == 0
+
+ self._run(repo, now, age_days=1, branch="feature/y", pr_number=8)
+
+ assert retention.sweep_repo(repo, now=now).runs_deleted == 1
+ 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)
+ self._run(repo, now, age_days=2, run_type=RunType.PLAYWRIGHT)
+
+ retention.sweep_repo(repo, now=now)
+
+ assert Run.objects.filter(id=stale_latest.id).exists()
+
+ def test_supersession_chain_goes_oldest_first_in_one_sweep(self, repo, now):
+ latest = self._run(repo, now, age_days=5)
+ second = self._run(repo, now, age_days=40, superseded_by=latest)
+ first = self._run(repo, now, age_days=50, superseded_by=second)
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.runs_deleted == 2
+ assert not Run.objects.filter(id__in=[first.id, second.id]).exists()
+ # unique_latest_run_per_group allows one run per group with a NULL
+ # superseded_by. A batched delete sets the surviving older link to NULL
+ # while the group's latest run is still there, which raises
+ # IntegrityError on that index.
+ assert (
+ Run.objects.filter(
+ repo=repo, branch="feature/x", run_type=RunType.STORYBOOK, superseded_by__isnull=True
+ ).count()
+ == 1
+ )
+
+ @pytest.mark.parametrize(
+ ("model", "extra_fields"),
+ [
+ (
+ ToleratedHash,
+ {"baseline_hash": "base1", "alternate_hash": "alt1", "reason": ToleratedReason.HUMAN},
+ ),
+ (QuarantinedIdentifier, {"run_type": RunType.STORYBOOK, "reason": "flaky in CI"}),
+ ],
+ )
+ def test_audit_rows_outlive_the_run_that_created_them(self, model, extra_fields, repo, now):
+ latest = self._run(repo, now, age_days=91)
+ superseded = self._run(repo, now, age_days=100, superseded_by=latest)
+ row = model.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ identifier="Button",
+ source_run=superseded,
+ **extra_fields,
+ )
+
+ retention.sweep_repo(repo, now=now)
+
+ row.refresh_from_db()
+ assert row.source_run_id is None
+
+ 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)
+ self._run(repo, now, age_days=110, superseded_by=latest)
+ self._run(repo, now, age_days=100, superseded_by=latest)
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.runs_deleted == 1
+ assert Run.objects.filter(id=latest.id).exists()
+ assert Run.objects.filter(superseded_by=latest).count() == 1
+
+ def test_deleting_a_run_frees_the_artifacts_only_it_referenced(self, repo, now):
+ latest = self._run(repo, now, age_days=91)
+ superseded = self._run(repo, now, age_days=100, superseded_by=latest)
+ artifact = self._artifact(repo, now, content_hash="current1", age_days=100)
+ RunSnapshot.objects.create(run=superseded, team_id=repo.team_id, identifier="Button", current_artifact=artifact)
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert not RunSnapshot.objects.filter(run_id=superseded.id).exists()
+ assert result.artifacts_deleted == 1
+ assert not Artifact.objects.filter(id=artifact.id).exists()
+
+ @pytest.mark.parametrize(("age_days", "survives"), [(3, True), (8, False)])
+ def test_orphaned_artifact_waits_out_the_grace_period(self, age_days, survives, repo, now):
+ artifact = self._artifact(repo, now, content_hash="orphan1", age_days=age_days)
+
+ retention.sweep_repo(repo, now=now)
+
+ assert Artifact.objects.filter(id=artifact.id).exists() is survives
+
+ @pytest.mark.parametrize(
+ "field",
+ ["current_artifact", "baseline_artifact", "diff_artifact", "current_hash", "baseline_hash"],
+ )
+ def test_artifact_referenced_by_a_snapshot_is_kept(self, field, repo, now):
+ run = self._run(repo, now, age_days=1)
+ artifact = self._artifact(repo, now, content_hash="referenced1", age_days=30)
+ reference = artifact.content_hash if field.endswith("_hash") else artifact
+ RunSnapshot.objects.create(run=run, team_id=repo.team_id, identifier="Button", **{field: reference})
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.artifacts_deleted == 0
+ assert Artifact.objects.filter(id=artifact.id).exists()
+
+ @pytest.mark.parametrize("field", ["current_hash", "baseline_hash"])
+ def test_hash_reference_from_another_repo_does_not_keep_an_artifact(self, field, repo, other_repo, now):
+ artifact = self._artifact(repo, now, content_hash="shared1", age_days=30)
+ run = self._run(other_repo, now, age_days=1)
+ RunSnapshot.objects.create(run=run, team_id=repo.team_id, identifier="Button", **{field: artifact.content_hash})
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.artifacts_deleted == 1
+ assert not Artifact.objects.filter(id=artifact.id).exists()
+
+ def test_thumbnail_is_collected_one_sweep_after_its_parent(self, repo, now):
+ thumbnail = self._artifact(repo, now, content_hash="thumb1", age_days=30)
+ parent = self._artifact(repo, now, content_hash="parent1", age_days=30, thumbnail=thumbnail)
+
+ assert retention.sweep_repo(repo, now=now).artifacts_deleted == 1
+ assert not Artifact.objects.filter(id=parent.id).exists()
+ assert Artifact.objects.filter(id=thumbnail.id).exists()
+
+ assert retention.sweep_repo(repo, now=now).artifacts_deleted == 1
+ assert not Artifact.objects.filter(id=thumbnail.id).exists()
+
+ def test_a_failed_object_delete_leaks_the_object(self, repo, now, stub_object_delete):
+ artifact = self._artifact(repo, now, content_hash="orphan2", age_days=30)
+ stub_object_delete.return_value = [artifact.storage_path]
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.artifacts_deleted == 1
+ assert result.objects_leaked == 1
+ assert not Artifact.objects.filter(id=artifact.id).exists()
+
+ def test_artifact_cap_bounds_one_invocation(self, repo, now, monkeypatch):
+ monkeypatch.setattr(retention, "MAX_ARTIFACTS_PER_SWEEP", 1)
+ self._artifact(repo, now, content_hash="orphan3", age_days=30)
+ self._artifact(repo, now, content_hash="orphan4", age_days=30)
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.artifacts_deleted == 1
+ assert Artifact.objects.filter(repo_id=repo.id).count() == 1
+
+ def test_sweeping_one_repo_leaves_another_repo_alone(self, repo, other_repo, now):
+ kept_latest = self._run(other_repo, now, age_days=200)
+ kept_superseded = self._run(other_repo, now, age_days=300, superseded_by=kept_latest)
+ kept_artifact = self._artifact(other_repo, now, content_hash="otherorphan", age_days=30)
+ self._artifact(repo, now, content_hash="orphan5", age_days=30)
+
+ result = retention.sweep_repo(repo, now=now)
+
+ assert result.runs_deleted == 0
+ assert result.artifacts_deleted == 1
+ assert Run.objects.filter(id__in=[kept_latest.id, kept_superseded.id]).count() == 2
+ assert Artifact.objects.filter(id=kept_artifact.id).exists()
+
+ def test_task_sweeps_every_repo_when_one_of_them_fails(self, repo, other_repo, mocker):
+ sweep_repo = mocker.patch.object(
+ retention,
+ "sweep_repo",
+ side_effect=[
+ Exception("boom"),
+ retention.RetentionSweepResult(runs_deleted=0, artifacts_deleted=0, objects_leaked=0),
+ ],
+ )
+ capture_exception = mocker.patch("products.visual_review.backend.tasks.tasks.capture_exception")
+
+ sweep_visual_review_retention()
+
+ assert {call.args[0].id for call in sweep_repo.call_args_list} == {repo.id, other_repo.id}
+ assert capture_exception.call_count == 1
+
+ def test_task_stops_sweeping_repos_when_the_time_budget_is_gone(self, repo, other_repo, mocker):
+ mocker.patch.object(retention, "SWEEP_TIME_BUDGET_SECONDS", 0)
+ sweep_repo = mocker.patch.object(retention, "sweep_repo")
+
+ sweep_visual_review_retention()
+
+ assert sweep_repo.call_count == 0
diff --git a/tach.toml b/tach.toml
index 4dd5c630ea68..54af786ebb53 100644
--- a/tach.toml
+++ b/tach.toml
@@ -135,6 +135,7 @@ depends_on = [
"products.tasks",
"products.tracing",
"products.user_interviews",
+ "products.visual_review",
"products.mcp_analytics",
"products.mcp_registry",
"products.web_analytics",