: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): run the retention sweep once a night (#98118)
Julian Bezeb2cbf329f97
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 750b191e5576..5039ad207558 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -1021,9 +1021,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="prune old streamlit app versions",)+ # The minute is fixed because beat rebuilds its schedule on every start. A+ # randrange minute draws a new value on each restart, so a restart inside the+ # scheduled hour makes the sweep run a second time that night, and a restart+ # that draws an earlier minute can make it skip the night. Minute 23 is odd,+ # which also keeps the sweep off the minutes the */2 heartbeat tasks use.add_periodic_task_with_expiry(sender,- crontab(hour="2", minute=str(randrange(0, 40))),+ crontab(hour="2", minute="23"),sweep_visual_review_retention.s(),name="sweep visual review retention",)diff --git a/products/visual_review/backend/logic/retention.py b/products/visual_review/backend/logic/retention.pyindex f11c8575417a..fab906dad817 100644--- a/products/visual_review/backend/logic/retention.py+++ b/products/visual_review/backend/logic/retention.py@@ -3,8 +3,9 @@from __future__ import annotationsimport time-from datetime import datetime, timedelta+from datetime import date, datetime, timedeltafrom itertools import batched+from typing import TypeVarfrom uuid import UUIDfrom django.db import connections, transaction@@ -23,6 +24,8 @@ from . import artifact_store, run_querieslogger = 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@@ -45,9 +48,9 @@ ARTIFACT_ORPHAN_GRACE_DAYS = 7ARTIFACT_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+# Caps per invocation. The task runs daily and catches up over several days, so+# a large backlog does not have to clear in one night.+MAX_RUNS_PER_SWEEP = 10_000MAX_ARTIFACTS_PER_SWEEP = 20_000# The caps above bound rows, not wall clock. Deletes over the backlog are slow@@ -273,6 +276,20 @@ class RetentionSweep:return ArtifactSweepResult(deleted=deleted, objects_leaked=objects_leaked)+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(repo: Repo, now: datetime | None = None, deadline: float | None = None) -> RetentionSweepResult:sweep = RetentionSweep(repo,diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.pyindex 85b64402622f..3a706da12519 100644--- a/products/visual_review/backend/tasks/tasks.py+++ b/products/visual_review/backend/tasks/tasks.py@@ -9,6 +9,7 @@ when Celery loads this module at startup."""import time+from datetime import datefrom uuid import UUIDimport structlog@@ -179,6 +180,7 @@ def sweep_visual_review_retention() -> None:# open for its whole run.# nosemgrep: idor-lookup-without-team — cross-team retention sweep, no user inputrepos = list(Repo.objects.unscoped().using(READER_DB).order_by("created_at"))+ repos = retention.rotate_for_day(repos, date.today())for swept, repo in enumerate(repos):if time.monotonic() >= deadline:logger.warning(@@ -187,6 +189,7 @@ def sweep_visual_review_retention() -> None:repos_total=len(repos),)break+ started = time.monotonic()try:result = retention.sweep_repo(repo, deadline=deadline)except Exception as e:@@ -205,4 +208,5 @@ def sweep_visual_review_retention() -> None:runs_deleted=result.runs_deleted,artifacts_deleted=result.artifacts_deleted,objects_leaked=result.objects_leaked,+ duration_seconds=round(time.monotonic() - started, 1),)diff --git a/products/visual_review/backend/tests/logic/test_retention.py b/products/visual_review/backend/tests/logic/test_retention.pyindex 3c5b0db9f56a..00daf80d6bf0 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 timedelta+from datetime import date, timedeltaimport pytest@@ -323,3 +323,21 @@ class TestRetentionSweep:sweep_visual_review_retention()assert sweep_repo.call_count == 0+++class TestRotateForDay:+ def test_every_item_leads_the_list_once_over_a_full_cycle(self):+ items = ["a", "b", "c", "d"]+ first_day = date(2026, 9, 10)++ leaders = [retention.rotate_for_day(items, first_day + timedelta(days=n))[0] for n in range(len(items))]++ assert sorted(leaders) == sorted(items)++ def test_rotation_keeps_every_item(self):+ items = ["a", "b", "c", "d"]++ assert sorted(retention.rotate_for_day(items, date(2026, 9, 10))) == sorted(items)++ def test_an_empty_list_stays_empty(self):+ assert retention.rotate_for_day([], date(2026, 9, 10)) == []