: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(tasks): reap ancient queued runs whose updated_at keeps bumping (#66391)
Alessandro Pogliaghifbdea5286772
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex dfe22556c245..603230411542 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -135,21 +135,23 @@ def kill_stale_queued_task_runs() -> None:refetch with status=QUEUED handles the race where a worker picks up the runbetween selection and update.- Staleness is keyed on `updated_at`, not `created_at`. `prepare_for_cloud_handoff`+ Staleness is keyed primarily on `updated_at`, not `created_at`. `prepare_for_cloud_handoff`re-queues an existing run (status=QUEUED, completed_at=None) without resetting`created_at`; using `created_at` would cause the cleanup to kill freshlyre-queued long-lived runs. `updated_at` (auto_now=True) advances on every save,so a re-queued run won't appear in this candidate set until it has actually- been QUEUED for the full STALE_AFTER window.+ been QUEUED for the full STALE_AFTER window. `CREATED_HARD_CAP` is a backstop for a+ run whose `updated_at` keeps being bumped while it stays QUEUED."""from products.tasks.backend.facade import api as tasks_facadeBATCH_SIZE = 500STALE_AFTER = datetime.timedelta(hours=24)+ CREATED_HARD_CAP = datetime.timedelta(hours=48)REASON = "Run was stuck in QUEUED state for over 24h and was killed by the cleanup job."# Janitor sweep is intentionally cross-team — it runs without a team context.- stale_ids = tasks_facade.get_stale_queued_task_run_ids(STALE_AFTER, BATCH_SIZE)+ stale_ids = tasks_facade.get_stale_queued_task_run_ids(STALE_AFTER, BATCH_SIZE, created_hard_cap=CREATED_HARD_CAP)swept = 0errors = 0for run_id in stale_ids:diff --git a/posthog/tasks/test/test_kill_stale_queued_task_runs.py b/posthog/tasks/test/test_kill_stale_queued_task_runs.pyindex 845430df9c60..81c1a5478b3f 100644--- a/posthog/tasks/test/test_kill_stale_queued_task_runs.py+++ b/posthog/tasks/test/test_kill_stale_queued_task_runs.py@@ -33,11 +33,18 @@ class TestKillStaleQueuedTaskRuns(TestCase):origin_product=Task.OriginProduct.USER_CREATED,)- def _make_run(self, status: str, age: datetime.timedelta) -> "TaskRun":+ def _make_run(+ self,+ status: str,+ age: datetime.timedelta,+ updated_age: datetime.timedelta | None = None,+ ) -> "TaskRun":TaskRun = apps.get_model("tasks", "TaskRun")run = TaskRun.objects.create(task=self.task, team=self.team, status=status)- past = timezone.now() - age- TaskRun.objects.filter(pk=run.pk).update(created_at=past, updated_at=past)+ now = timezone.now()+ TaskRun.objects.filter(pk=run.pk).update(+ created_at=now - age, updated_at=now - (updated_age if updated_age is not None else age)+ )run.refresh_from_db()return run@@ -78,6 +85,34 @@ class TestKillStaleQueuedTaskRuns(TestCase):self.assertIsNone(run.completed_at)self.assertIsNone(run.error_message)+ def test_hard_cap_reaps_ancient_run_with_bumped_updated_at(self) -> None:+ TaskRun = apps.get_model("tasks", "TaskRun")+ run = self._make_run(+ TaskRun.Status.QUEUED,+ datetime.timedelta(hours=50),+ updated_age=datetime.timedelta(hours=2),+ )++ kill_stale_queued_task_runs()++ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.FAILED)+ self.assertIsNotNone(run.completed_at)++ def test_hard_cap_spares_ancient_run_touched_within_grace(self) -> None:+ TaskRun = apps.get_model("tasks", "TaskRun")+ run = self._make_run(+ TaskRun.Status.QUEUED,+ datetime.timedelta(hours=50),+ updated_age=datetime.timedelta(minutes=10),+ )++ kill_stale_queued_task_runs()++ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.QUEUED)+ self.assertIsNone(run.error_message)+@parameterized.expand([(apps.get_model("tasks", "TaskRun").Status.NOT_STARTED,),diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 36a95bb493c8..34a967d3dcdc 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -514,16 +514,24 @@ def get_latest_run_by_task(task_ids: Iterable[str | UUID]) -> dict[str, contractreturn {str(run.task_id): _task_run_to_dto(run) for run in runs}-def get_stale_queued_task_run_ids(older_than: timedelta, limit: int) -> list[UUID]:- """Ids of runs stuck in QUEUED with ``updated_at`` older than the cutoff.+def get_stale_queued_task_run_ids(+ older_than: timedelta,+ limit: int,+ *,+ created_hard_cap: timedelta | None = None,+ hard_cap_min_queued: timedelta = timedelta(hours=1),+) -> list[UUID]:+ """Ids of runs stuck in QUEUED, by ``updated_at`` age or an optional ``created_at`` backstop.Intentionally cross-team — the janitor sweep runs without a team context."""- cutoff = django_timezone.now() - older_than+ now = django_timezone.now()+ stale = Q(updated_at__lt=now - older_than)+ if created_hard_cap is not None:+ stale |= Q(created_at__lt=now - created_hard_cap, updated_at__lt=now - hard_cap_min_queued)return list(- TaskRun.objects.filter( # nosemgrep: celery-task-team-scope-audit- status=TaskRun.Status.QUEUED, updated_at__lt=cutoff- )+ TaskRun.objects.filter(status=TaskRun.Status.QUEUED) # nosemgrep: celery-task-team-scope-audit+ .filter(stale).order_by("updated_at").values_list("id", flat=True)[:limit])diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex d4c3880e3909..9c863f986757 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -209,6 +209,26 @@ class TestFacadeReadsAndMappers(TestCase):self.assertEqual(stale.status, TaskRun.Status.FAILED.value)self.assertEqual(stale.error_message, "boom")+ def test_stale_queued_created_at_hard_cap(self):+ task = self._make_task()+ now = django_timezone.now()+ ancient = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)+ TaskRun.objects.filter(pk=ancient.pk).update(+ created_at=now - timedelta(hours=50), updated_at=now - timedelta(hours=2)+ )+ resuming = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)+ TaskRun.objects.filter(pk=resuming.pk).update(+ created_at=now - timedelta(hours=50), updated_at=now - timedelta(minutes=10)+ )++ self.assertNotIn(ancient.id, facade.get_stale_queued_task_run_ids(older_than=timedelta(hours=24), limit=100))++ hard_capped = facade.get_stale_queued_task_run_ids(+ older_than=timedelta(hours=24), limit=100, created_hard_cap=timedelta(hours=48)+ )+ self.assertIn(ancient.id, hard_capped)+ self.assertNotIn(resuming.id, hard_capped)+def test_update_task_run_state(self):task = self._make_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED, state={"mode": "bg"})