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.

20.1 KB
Raw Blame
"""Retention sweep: deletes expired runs and the artifacts nothing references any more."""

from __future__ import annotations

import time
from collections.abc import Callable
from dataclasses import asdict
from datetime import date, datetime, timedelta
from itertools import batched
from typing import TypeVar
from uuid import UUID

from django.db import connections, transaction
from django.db.models import Exists, OuterRef, Q, QuerySet
from django.db.models.fields.json import KeyTextTransform
from django.utils import timezone

import structlog

from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception

from ..db import READER_DB, WRITER_DB
from ..facade.enums import RunStatus
from ..models import Artifact, QuarantinedIdentifier, Repo, Run, RunSnapshot
from ..storage import ArtifactStorage, StoryIndexStorage
from . import artifact_store, run_queries, story_index

logger = structlog.get_logger(__name__)

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, 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.
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 = 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
# 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 tasks run daily and catch up over several days, so
# a large backlog does not have to clear in one night.
MAX_RUNS_PER_SWEEP = 10_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.
#
# A deploy stops a busy worker and kills it when its grace period ends, which is
# about 20 minutes in production. A task that always ends inside that period
# cannot be killed by a deploy, whenever the deploy starts. The budget stays
# below it with room for the one query or batch that can start just before the
# deadline.
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. 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
# 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 RunSweepResult:
    runs_deleted: int
    story_indexes_deleted: int


@frozen
class ArtifactSweepResult:
    artifacts_deleted: int
    objects_leaked: int


class RetentionSweep:
    """Applies the retention policy to one repo."""

    def __init__(self, repo: Repo, deadline: float | None = None, now: datetime | None = None) -> 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 or timezone.now()
        self.deadline = deadline if deadline is not None else time.monotonic() + SWEEP_TIME_BUDGET_SECONDS
        # Hashes of the story-to-file maps named by runs this sweep deleted.
        self.released_story_index_hashes: set[str] = set()

    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 _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
                & ~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, *, 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.
        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(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]
        )

    def _splice_out_of_chain(self, run_id: UUID) -> None:
        """Give the runs that name this run its own successor instead."""
        successor_id = self._runs().filter(id=run_id).values_list("superseded_by_id", flat=True).first()
        if successor_id is None:
            # The run is the group's latest. Only the quiet-branch pass deletes
            # one of those, and it takes a group where no run is superseded, so
            # there is nothing to re-point.
            return
        self._runs().filter(superseded_by_id=run_id).update(superseded_by_id=successor_id)

    def _delete_runs(self, run_ids: list[UUID]) -> int:
        deleted = 0
        hash_by_run_id = dict(
            self._runs()
            .filter(id__in=run_ids, metadata__has_key=story_index.METADATA_KEY)
            .values_list("id", KeyTextTransform(story_index.METADATA_KEY, "metadata"))
        )
        # 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.
        #
        # Oldest first is not enough on its own, because the retention class is
        # a property of the row, not of its age: a run with no PR number counts
        # as protected history and gets 180 days while the runs after it on the
        # same branch get 30. Such a run survives the sweep that deletes the run
        # it names, so it has to be re-pointed before the DELETE runs.
        for run_id in run_ids:
            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)
            deleted += run_deleted
            if run_deleted and run_id in hash_by_run_id:
                self.released_story_index_hashes.add(hash_by_run_id[run_id])
        return deleted

    def delete_expired_runs(self) -> int:
        # 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))
        # 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()
        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(artifacts_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(artifacts_deleted=deleted, objects_leaked=objects_leaked)

    def delete_released_story_indexes(self) -> int:
        """Delete the story-to-file maps that no remaining run names, among those the deleted runs named.

        A map is stored once per distinct content and no row tracks it, so this is the only thing that
        removes one. Only the maps of runs this sweep deleted are candidates, so nothing lists storage.
        """
        if not self.released_story_index_hashes or self._out_of_time():
            return 0

        still_named = set(
            self._runs()
            .annotate(story_index_hash=KeyTextTransform(story_index.METADATA_KEY, "metadata"))
            .filter(story_index_hash__in=self.released_story_index_hashes)
            .values_list("story_index_hash", flat=True)
        )
        unnamed = sorted(self.released_story_index_hashes - still_named)
        if not unnamed:
            return 0

        failed_paths = StoryIndexStorage(str(self.repo.id)).delete_hashes(unnamed)
        deleted = len(unnamed) - len(failed_paths)
        logger.info(
            "visual_review.retention_story_indexes_deleted",
            repo_id=str(self.repo.id),
            team_id=self.team_id,
            deleted=deleted,
            failed=len(failed_paths),
        )
        return deleted


def rotate_for_day(items: list[T], day: date) -> list[T]:
    """Move the start of the list on by one place a day.

    The repos share one time budget, so a repo with a backlog big enough to
    spend it keeps the repos behind it from being swept at all. A fixed order
    starves the same repos every night, and rotating the start gives each of
    them the front of the queue in turn.
    """
    if not items:
        return items
    offset = day.toordinal() % len(items)
    return items[offset:] + items[:offset]


def sweep_repo_runs(repo: Repo, deadline: float | None = None, now: datetime | None = None) -> RunSweepResult:
    sweep = RetentionSweep(repo, deadline, now)
    runs_deleted = sweep.delete_expired_runs()
    # Right after the runs, because only this sweep knows which maps the deleted runs named.
    story_indexes_deleted = sweep.delete_released_story_indexes()
    return RunSweepResult(runs_deleted=runs_deleted, story_indexes_deleted=story_indexes_deleted)


def sweep_repo_artifacts(repo: Repo, deadline: float | None = None, now: datetime | None = None) -> ArtifactSweepResult:
    """Delete the artifacts nothing references any more.

    This pass is a task of its own with its own budget, so a backlog of runs
    cannot use up the time it needs.
    """
    return RetentionSweep(repo, deadline, now).delete_orphaned_artifacts()


def sweep_every_repo(
    sweep_name: str, sweep_repo: Callable[[Repo, float], RunSweepResult | ArtifactSweepResult]
) -> None:
    """Run one sweep over every repo, inside one shared time budget.

    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.
    """
    deadline = time.monotonic() + 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"))
    repos = rotate_for_day(repos, date.today())
    for swept, repo in enumerate(repos):
        if time.monotonic() >= deadline:
            logger.warning(
                "visual_review.retention_sweep_budget_exhausted",
                sweep=sweep_name,
                repos_swept=swept,
                repos_total=len(repos),
            )
            break
        started = time.monotonic()
        try:
            result = sweep_repo(repo, deadline)
        except Exception as e:
            capture_exception(e)
            logger.exception(
                "visual_review.retention_sweep_failed",
                sweep=sweep_name,
                repo_id=str(repo.id),
                team_id=repo.team_id,
            )
            continue

        logger.info(
            "visual_review.retention_sweep_completed",
            sweep=sweep_name,
            repo_id=str(repo.id),
            team_id=repo.team_id,
            duration_seconds=round(time.monotonic() - started, 1),
            **asdict(result),
        )