: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): clean up abandoned prewarm tasks (#81202)
Alessandro Pogliaghi2815cf533bbb
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 02f3ac1efc62..cbd16601c7d7 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -87,6 +87,16 @@ PREWARMED_QUEUED_TASK_RUN_ERRORS_COUNTER = Counter("Errors raised while marking an orphaned prewarmed TaskRun FAILED in the prewarmed-queued cleanup sweep",)+PREWARMED_TERMINAL_TASK_SWEPT_COUNTER = Counter(+ "posthog_task_prewarmed_terminal_swept_total",+ "Empty tasks hidden after their unclaimed prewarmed run reached a terminal status",+)++PREWARMED_TERMINAL_TASK_ERRORS_COUNTER = Counter(+ "posthog_task_prewarmed_terminal_errors_total",+ "Errors raised while hiding empty tasks left by terminal unclaimed prewarmed runs",+)+STALE_LOCAL_QUEUED_TASK_RUN_COMPLETED_COUNTER = Counter("posthog_task_run_stale_local_queued_completed_total","Idle local (desktop-driven) TaskRuns quietly marked COMPLETED by the stale-queued cleanup sweep",@@ -249,7 +259,20 @@ def kill_stale_queued_task_runs() -> None:PREWARMED_QUEUED_TASK_RUN_ERRORS_COUNTER,)- saturated = len(stale_ids) >= BATCH_SIZE or len(local_ids) >= BATCH_SIZE or len(prewarmed_ids) >= BATCH_SIZE+ terminal_prewarmed_ids = tasks_facade.get_stale_terminal_prewarmed_task_run_ids(PREWARMED_STALE_AFTER, BATCH_SIZE)+ terminal_prewarmed_swept, terminal_prewarmed_errors = _sweep_each(+ terminal_prewarmed_ids,+ tasks_facade.soft_delete_unclaimed_prewarm_task,+ PREWARMED_TERMINAL_TASK_SWEPT_COUNTER,+ PREWARMED_TERMINAL_TASK_ERRORS_COUNTER,+ )++ saturated = (+ len(stale_ids) >= BATCH_SIZE+ or len(local_ids) >= BATCH_SIZE+ or len(prewarmed_ids) >= BATCH_SIZE+ or len(terminal_prewarmed_ids) >= BATCH_SIZE+ )log = logger.warning if saturated else logger.infolog("kill_stale_queued_task_runs.sweep_done",@@ -262,6 +285,9 @@ def kill_stale_queued_task_runs() -> None:prewarmed_candidates=len(prewarmed_ids),prewarmed_swept=prewarmed_swept,prewarmed_errors=prewarmed_errors,+ terminal_prewarmed_candidates=len(terminal_prewarmed_ids),+ terminal_prewarmed_swept=terminal_prewarmed_swept,+ terminal_prewarmed_errors=terminal_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 4b5d76613f27..cd6b327eaaf6 100644--- a/posthog/tasks/test/test_kill_stale_queued_task_runs.py+++ b/posthog/tasks/test/test_kill_stale_queued_task_runs.py@@ -143,6 +143,28 @@ class TestKillStaleQueuedTaskRuns(TestCase):self.assertIn("orphaned in QUEUED", run.error_message or "")self.assertIsNotNone(run.completed_at)+ def test_reaps_task_shell_for_orphaned_prewarmed_run(self) -> None:+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.QUEUED,+ state={"prewarmed": True, "await_user_message": True},+ )+ TaskRun.objects.filter(pk=run.pk).update(updated_at=timezone.now() - datetime.timedelta(minutes=31))++ kill_stale_queued_task_runs()++ task.refresh_from_db()+ self.assertTrue(task.deleted)+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.@@ -155,6 +177,28 @@ class TestKillStaleQueuedTaskRuns(TestCase):self.assertEqual(run.status, TaskRun.Status.QUEUED)self.assertIsNone(run.error_message)+ def test_cleans_up_existing_terminal_prewarm_task_shell(self) -> None:+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ state={"prewarmed": True, "await_user_message": True},+ )+ TaskRun.objects.filter(pk=run.pk).update(updated_at=timezone.now() - datetime.timedelta(minutes=31))++ kill_stale_queued_task_runs()++ task.refresh_from_db()+ self.assertTrue(task.deleted)+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 6dc5b52f09ef..40ec1cb68558 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -177,6 +177,7 @@ __all__ = ["get_sandbox_environment","get_sandbox_snapshot","get_stale_prewarmed_queued_task_run_ids",+ "get_stale_terminal_prewarmed_task_run_ids","get_stale_queued_task_run_ids","get_task_automation","get_task_detail",@@ -944,6 +945,23 @@ def get_stale_prewarmed_queued_task_run_ids(older_than: timedelta, limit: int) -)+def get_stale_terminal_prewarmed_task_run_ids(older_than: timedelta, limit: int) -> list[UUID]:+ now = django_timezone.now()+ return list(+ TaskRun.objects.filter( # nosemgrep: celery-task-team-scope-audit+ status__in=[TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED],+ state__prewarmed=True,+ state__await_user_message=True,+ task__deleted=False,+ task__title="",+ task__description="",+ 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:@@ -1240,9 +1258,15 @@ def fail_task_run(run_id: str | UUID, error: str, error_type: str | None = None)if run is None:return Falserun.mark_failed(error, error_type=error_type)+ run.task.soft_delete_if_unclaimed_prewarm(run)return True+def soft_delete_unclaimed_prewarm_task(run_id: str | UUID) -> bool:+ run = TaskRun.objects.select_related("task").filter(pk=run_id).first() # nosemgrep: celery-task-team-scope-audit+ return run.task.soft_delete_if_unclaimed_prewarm(run) if run is not None else False++def complete_idle_local_task_run(run_id: str | UUID) -> bool:"""Quietly finalize a local (desktop-driven) run left idling in QUEUED. Returns whethera run was acted on.diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex d19ec1df5e45..29756baf7492 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -527,6 +527,27 @@ class Task(DeletedMetaFields, models.Model):capture_fn=capture_fn,)+ def soft_delete_if_unclaimed_prewarm(self, task_run: "TaskRun") -> bool:+ deleted_at = django_timezone.now()+ updated = Task.objects.filter(+ pk=self.pk,+ deleted=False,+ title="",+ description="",+ runs__id=task_run.id,+ runs__state__prewarmed=True,+ runs__state__await_user_message=True,+ ).update(deleted=True, deleted_at=deleted_at, updated_at=deleted_at)+ if not updated:+ return False+ self.deleted = True+ self.deleted_at = deleted_at+ self.updated_at = deleted_at+ self.capture_event(+ "task_deleted", {"duration_seconds": round((deleted_at - self.created_at).total_seconds(), 1)}+ )+ return True+def delete(self, *args, **kwargs):raise Exception("Cannot hard delete Task. Use soft_delete() instead.")diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.pyindex 6fd07a4b6d3d..09268ed5ab26 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py@@ -3,6 +3,7 @@ from unittest.mock import patchfrom asgiref.sync import async_to_syncfrom temporalio.exceptions import ApplicationError+from temporalio.testing import ActivityEnvironmentfrom products.tasks.backend.models import Loop, TaskRunfrom products.tasks.backend.temporal.process_task.activities.update_task_run_status import (@@ -15,6 +16,12 @@ from products.tasks.backend.temporal.process_task.activities.update_task_run_staTOKEN_USAGE = {"input_tokens": 1200, "output_tokens": 300, "total_tokens": 1500, "turns": 3}+async def _run_update_task_run_status(+ activity_environment: ActivityEnvironment, input_data: UpdateTaskRunStatusInput+) -> None:+ await activity_environment.run(update_task_run_status, input_data)++@pytest.mark.requires_secretsclass TestUpdateTaskRunStatusActivity:@pytest.mark.django_db(transaction=True)@@ -86,6 +93,28 @@ class TestUpdateTaskRunStatusActivity:# Merge, not replace: pre-existing state keys survive the marker write.assert test_task_run.state.get("existing_key") == "kept"+ @pytest.mark.django_db(transaction=True)+ def test_timed_out_unclaimed_prewarm_soft_deletes_task(+ self, activity_environment: ActivityEnvironment, test_task_run: TaskRun+ ) -> None:+ test_task_run.task.title = ""+ test_task_run.task.description = ""+ test_task_run.task.save(update_fields=["title", "description", "updated_at"])+ test_task_run.state = {"prewarmed": True, "await_user_message": True}+ test_task_run.save(update_fields=["state", "updated_at"])++ async_to_sync(_run_update_task_run_status)(+ activity_environment,+ UpdateTaskRunStatusInput(+ run_id=str(test_task_run.id),+ status=TaskRun.Status.COMPLETED,+ timed_out_inactivity=True,+ ),+ )++ test_task_run.task.refresh_from_db()+ assert test_task_run.task.deleted is True+@pytest.mark.django_db(transaction=True)@pytest.mark.parametrize("marker",diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.pyindex 143d11ff2b4e..f6a6f034d44a 100644--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py@@ -117,6 +117,9 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:if input.status in [TaskRun.Status.COMPLETED, TaskRun.Status.FAILED] and old_status != input.status:_capture_terminal_analytics(task_run, input)+ if input.timed_out_inactivity and old_status != input.status:+ task_run.task.soft_delete_if_unclaimed_prewarm(task_run)+# This activity is how workflow-driven runs (finish tool, failures, timeouts, cancellations)# reach a terminal status, so loop bookkeeping must hook in here, not only in the HTTP PATCH# path (facade.api.update_task_run). Guarded on the actual transition so repeats and thediff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 3c180fba7252..d7054dadd360 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -407,6 +407,29 @@ class TestTask(TestCase):self.assertTrue(task.deleted)self.assertIsNotNone(task.deleted_at)+ def test_unclaimed_prewarm_cleanup_does_not_overwrite_claimed_task(self) -> None:+ task = Task.objects.create(+ team=self.team,+ title="",+ description="",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.QUEUED,+ state={"prewarmed": True, "await_user_message": True},+ )+ Task.objects.filter(pk=task.pk).update(title="Claimed task", description="User prompt")++ cleaned_up = task.soft_delete_if_unclaimed_prewarm(run)++ task.refresh_from_db()+ self.assertFalse(cleaned_up)+ self.assertFalse(task.deleted)+ self.assertEqual(task.title, "Claimed task")+ self.assertEqual(task.description, "User prompt")+def test_hard_delete_blocked(self):task = Task.objects.create(team=self.team,