: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 orphaned prewarmed runs stuck in QUEUED (#67051)
Alessandro Pogliaghiad50030887e4
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 603230411542..6dee9fa31fc4 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -64,6 +64,19 @@ STALE_QUEUED_TASK_RUN_ERRORS_COUNTER = Counter("Errors raised while marking a TaskRun FAILED in the stale-queued cleanup sweep",)+# Separate from the stale-queued counters above so the 24h sweep and the prewarmed fast-reap+# stay distinguishable in Prometheus (dashboards/alerts on the 24h sweep shouldn't absorb the+# prewarmed reap rate).+PREWARMED_QUEUED_TASK_RUN_SWEPT_COUNTER = Counter(+ "posthog_task_run_prewarmed_queued_swept_total",+ "Orphaned prewarmed TaskRuns marked FAILED by the prewarmed-queued cleanup sweep",+)++PREWARMED_QUEUED_TASK_RUN_ERRORS_COUNTER = Counter(+ "posthog_task_run_prewarmed_queued_errors_total",+ "Errors raised while marking an orphaned prewarmed TaskRun FAILED in the prewarmed-queued cleanup sweep",+)+@shared_task(ignore_result=True)def delete_expired_exported_assets() -> None:@@ -148,30 +161,53 @@ def kill_stale_queued_task_runs() -> None:BATCH_SIZE = 500STALE_AFTER = datetime.timedelta(hours=24)CREATED_HARD_CAP = datetime.timedelta(hours=48)+ # A live warm run self-terminates via the in-workflow WARM_IDLE_TIMEOUT (10m); one still QUEUED+ # past this window has no workflow behind it (dispatch lost) so there is nothing else to finalize+ # it. Kept comfortably above WARM_IDLE_TIMEOUT so a still-idling warm run is never killed early.+ PREWARMED_STALE_AFTER = datetime.timedelta(minutes=30)REASON = "Run was stuck in QUEUED state for over 24h and was killed by the cleanup job."+ PREWARMED_REASON = "Prewarmed run never started its workflow and was orphaned in QUEUED; reaped by the cleanup job."++ def _fail_each(run_ids: list, reason: str, swept_counter: Counter, errors_counter: Counter) -> tuple[int, int]:+ swept = errors = 0+ for run_id in run_ids:+ try:+ # fail_task_run refetches with status=QUEUED, handling the race where a worker+ # picked up the run between selection and update (returns False -> skip).+ if tasks_facade.fail_task_run(run_id, reason):+ swept += 1+ swept_counter.inc()+ except Exception as exc: # noqa: BLE001 - one run must not block the sweep+ errors += 1+ errors_counter.inc()+ capture_exception(exc)+ return swept, errors# 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, created_hard_cap=CREATED_HARD_CAP)- swept = 0- errors = 0- for run_id in stale_ids:- try:- # fail_task_run refetches with status=QUEUED, handling the race where a worker- # picked up the run between selection and update (returns False -> skip).- if tasks_facade.fail_task_run(run_id, REASON):- swept += 1- STALE_QUEUED_TASK_RUN_SWEPT_COUNTER.inc()- except Exception as exc: # noqa: BLE001 - one run must not block the sweep- errors += 1- STALE_QUEUED_TASK_RUN_ERRORS_COUNTER.inc()- capture_exception(exc)- saturated = len(stale_ids) >= BATCH_SIZE+ swept, errors = _fail_each(+ stale_ids, REASON, STALE_QUEUED_TASK_RUN_SWEPT_COUNTER, STALE_QUEUED_TASK_RUN_ERRORS_COUNTER+ )++ # Fast-reap orphaned prewarmed runs so they don't ride QUEUED to the 24h sweep above.+ prewarmed_ids = tasks_facade.get_stale_prewarmed_queued_task_run_ids(PREWARMED_STALE_AFTER, BATCH_SIZE)+ prewarmed_swept, prewarmed_errors = _fail_each(+ prewarmed_ids,+ PREWARMED_REASON,+ PREWARMED_QUEUED_TASK_RUN_SWEPT_COUNTER,+ PREWARMED_QUEUED_TASK_RUN_ERRORS_COUNTER,+ )++ saturated = len(stale_ids) >= BATCH_SIZE or len(prewarmed_ids) >= BATCH_SIZElog = logger.warning if saturated else logger.infolog("kill_stale_queued_task_runs.sweep_done",candidates=len(stale_ids),swept=swept,errors=errors,+ prewarmed_candidates=len(prewarmed_ids),+ prewarmed_swept=prewarmed_swept,+ prewarmed_errors=prewarmed_errors,batch_size=BATCH_SIZE,saturated=saturated,)diff --git a/posthog/tasks/test/test_kill_stale_queued_task_runs.py b/posthog/tasks/test/test_kill_stale_queued_task_runs.pyindex 81c1a5478b3f..2ac0502dccf0 100644--- a/posthog/tasks/test/test_kill_stale_queued_task_runs.py+++ b/posthog/tasks/test/test_kill_stale_queued_task_runs.py@@ -38,9 +38,12 @@ class TestKillStaleQueuedTaskRuns(TestCase):status: str,age: datetime.timedelta,updated_age: datetime.timedelta | None = None,+ *,+ prewarmed: bool = False,) -> "TaskRun":TaskRun = apps.get_model("tasks", "TaskRun")- run = TaskRun.objects.create(task=self.task, team=self.team, status=status)+ state = {"prewarmed": True, "await_user_message": True} if prewarmed else {}+ run = TaskRun.objects.create(task=self.task, team=self.team, status=status, state=state)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)@@ -85,6 +88,31 @@ class TestKillStaleQueuedTaskRuns(TestCase):self.assertIsNone(run.completed_at)self.assertIsNone(run.error_message)+ def test_reaps_orphaned_prewarmed_run_well_before_24h(self) -> None:+ # A prewarmed run whose workflow never started has no in-workflow timer to finalize it,+ # so it must be reaped on the short prewarmed window rather than riding QUEUED to 24h.+ TaskRun = apps.get_model("tasks", "TaskRun")+ run = self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(minutes=31), prewarmed=True)++ kill_stale_queued_task_runs()++ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.FAILED)+ self.assertIn("orphaned in QUEUED", run.error_message or "")+ self.assertIsNotNone(run.completed_at)++ def test_spares_prewarmed_run_still_inside_idle_window(self) -> None:+ # A live warm run idles in QUEUED awaiting its first message; it must not be killed before+ # the in-workflow WARM_IDLE_TIMEOUT (10m) has had a chance to finalize an abandoned one.+ TaskRun = apps.get_model("tasks", "TaskRun")+ run = self._make_run(TaskRun.Status.QUEUED, datetime.timedelta(minutes=10), prewarmed=True)++ kill_stale_queued_task_runs()++ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.QUEUED)+ 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(diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex a3dab6e3a323..438ae4937f20 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -123,6 +123,7 @@ __all__ = ["get_latest_run_by_task","get_sandbox_environment","get_sandbox_snapshot",+ "get_stale_prewarmed_queued_task_run_ids","get_stale_queued_task_run_ids","get_task_automation","get_task_detail",@@ -549,6 +550,30 @@ def get_stale_queued_task_run_ids()+def get_stale_prewarmed_queued_task_run_ids(older_than: timedelta, limit: int) -> list[UUID]:+ """Ids of prewarmed runs orphaned in QUEUED — their processing workflow never started, so the+ in-workflow ``WARM_IDLE_TIMEOUT`` (10m) never armed to finalize them.++ A live warm run idles in QUEUED awaiting its first message and self-terminates at+ ``WARM_IDLE_TIMEOUT``, so a prewarmed run still QUEUED well past that window has no workflow+ behind it (dispatch lost — e.g. an ``on_commit`` callback that never ran) and can be reaped+ immediately rather than lingering until the 24h stale sweep. ``older_than`` should sit safely+ above ``WARM_IDLE_TIMEOUT`` so a still-idling warm run is never killed early.++ Intentionally cross-team — the janitor sweep runs without a team context.+ """+ now = django_timezone.now()+ return list(+ TaskRun.objects.filter( # nosemgrep: celery-task-team-scope-audit+ status=TaskRun.Status.QUEUED,+ state__prewarmed=True,+ updated_at__lt=now - older_than,+ )+ .order_by("updated_at")+ .values_list("id", flat=True)[:limit]+ )++def _gauge_rows(values_qs, value_key: str, *, with_status: bool, now=None) -> list[contracts.TaskRunGaugeRow]:rows = []for row in values_qs:diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex 341abfbd2a35..a7fa8e694345 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -155,9 +155,14 @@ async def execute_task_processing_workflow_async("execute_task_processing_workflow_async_called",extra={"task_id": task_id, "run_id": run_id},)- task_run_for_metrics = await _aget_task_run_for_metrics(run_id)- observe_task_run_workflow_start(task_run_for_metrics, outcome="attempted", reason="requested")+ # Keep the metrics lookups inside the try: if either raises, the except clauses must still+ # terminalize the run. When they ran before the try, an exception here aborted the dispatch+ # without marking the run FAILED, orphaning it in QUEUED until the 24h janitor swept it.+ # observe_task_run_workflow_start tolerates a None task_run.+ task_run_for_metrics: TaskRun | None = Nonetry:+ task_run_for_metrics = await _aget_task_run_for_metrics(run_id)+ observe_task_run_workflow_start(task_run_for_metrics, outcome="attempted", reason="requested")await Team.objects.select_related("organization").aget(id=team_id)await sync_to_async(_capture_sandbox_event_ingest_flag)(run_id)@@ -227,9 +232,12 @@ def execute_task_processing_workflow(Start the task processing workflow synchronously. Fire-and-forget.Use this from sync contexts (e.g., API endpoints)."""- task_run_for_metrics = _get_task_run_for_metrics(run_id)- observe_task_run_workflow_start(task_run_for_metrics, outcome="attempted", reason="requested")+ # Metrics lookups stay inside the try so a failure here can't bypass terminalization and+ # leave the run orphaned in QUEUED (see the async variant above).+ task_run_for_metrics: TaskRun | None = Nonetry:+ task_run_for_metrics = _get_task_run_for_metrics(run_id)+ observe_task_run_workflow_start(task_run_for_metrics, outcome="attempted", reason="requested")logger.info("execute_task_processing_workflow_called",extra={"task_id": task_id, "run_id": run_id, "team_id": team_id, "user_id": user_id},