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.

fix(tasks): stop the 24h janitor failing idle local task runs (#70050)

Alessandro Pogliaghi1a340e003bc4
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index a851440181a0..bda275611bc8 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -1,5 +1,6 @@
import time
import datetime
+from collections.abc import Callable
from typing import TYPE_CHECKING, Optional
if TYPE_CHECKING:
@@ -83,6 +84,16 @@ PREWARMED_QUEUED_TASK_RUN_ERRORS_COUNTER = Counter(
"Errors raised while marking an orphaned prewarmed TaskRun FAILED in the prewarmed-queued cleanup sweep",
)
+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",
+)
+
+STALE_LOCAL_QUEUED_TASK_RUN_ERRORS_COUNTER = Counter(
+ "posthog_task_run_stale_local_queued_errors_total",
+ "Errors raised while marking an idle local TaskRun COMPLETED in the stale-queued cleanup sweep",
+)
+
@shared_task(ignore_result=True)
def delete_expired_exported_assets() -> None:
@@ -143,16 +154,23 @@ def delete_expired_delegation_invites() -> None:
@shared_task(ignore_result=True, soft_time_limit=300, time_limit=360)
def kill_stale_queued_task_runs() -> None:
- """Mark TaskRuns stuck in QUEUED for >24h as FAILED.
-
- A TaskRun sits in QUEUED until the Temporal `process-task` workflow flips it
- to IN_PROGRESS. If that workflow never starts (worker down, schedule call
- failed), the row would otherwise stay QUEUED forever. mark_failed() (per row,
- not bulk .update()) preserves publish_stream_state_event and the
- `task_run_failed` analytics capture. Materializing ids first avoids
- server-side cursor invalidation while updating the same table; the inner
- refetch with status=QUEUED handles the race where a worker picks up the run
- between selection and update.
+ """Terminalize TaskRuns stuck in QUEUED for >24h: cloud runs FAIL, local runs COMPLETE.
+
+ A cloud TaskRun sits in QUEUED until the Temporal `process-task` workflow flips
+ it to IN_PROGRESS. If that workflow never starts (worker down, schedule call
+ failed), the row would otherwise stay QUEUED forever — so a stale cloud run is a
+ genuine failure. A local (desktop-driven) run, by contrast, sits in QUEUED by
+ design for its whole life: the desktop agent drives the session and never reports
+ status, so an idle local run is a session that simply ended and finalizes as
+ COMPLETED — quietly, with no push notification (see the environment discussion on
+ `get_stale_queued_task_run_ids`). Failing local runs here used to flood users with
+ bogus failures on runs that never ran in the cloud at all.
+
+ Per-row finalizers (not bulk .update()) preserve publish_stream_state_event and
+ the terminal analytics captures. Materializing ids first avoids server-side
+ cursor invalidation while updating the same table; the inner refetch with
+ status=QUEUED handles the race where a worker picks up the run between selection
+ and update.
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
@@ -160,7 +178,10 @@ def kill_stale_queued_task_runs() -> None:
re-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. `CREATED_HARD_CAP` is a backstop for a
- run whose `updated_at` keeps being bumped while it stays QUEUED.
+ cloud run whose `updated_at` keeps being bumped while it stays QUEUED; the local
+ sweep deliberately has no such backstop — a local run whose `updated_at` keeps
+ advancing is a desktop session that is genuinely alive (the desktop PATCHes
+ output/branch as it works) and must not be finalized under the user.
"""
from products.tasks.backend.facade import api as tasks_facade
@@ -174,13 +195,15 @@ def kill_stale_queued_task_runs() -> None:
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]:
+ def _sweep_each(
+ run_ids: list, finalize: Callable[[UUID], bool], 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
+ # Finalizers refetch 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):
+ if finalize(run_id):
swept += 1
swept_counter.inc()
except Exception as exc: # noqa: BLE001 - one run must not block the sweep
@@ -190,27 +213,49 @@ def kill_stale_queued_task_runs() -> None:
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, errors = _fail_each(
- stale_ids, REASON, STALE_QUEUED_TASK_RUN_SWEPT_COUNTER, STALE_QUEUED_TASK_RUN_ERRORS_COUNTER
+ stale_ids = tasks_facade.get_stale_queued_task_run_ids(
+ STALE_AFTER,
+ BATCH_SIZE,
+ created_hard_cap=CREATED_HARD_CAP,
+ environment=tasks_facade.TaskRunEnvironment.CLOUD,
+ )
+ swept, errors = _sweep_each(
+ stale_ids,
+ lambda run_id: tasks_facade.fail_task_run(run_id, REASON),
+ STALE_QUEUED_TASK_RUN_SWEPT_COUNTER,
+ STALE_QUEUED_TASK_RUN_ERRORS_COUNTER,
+ )
+
+ # Idle local runs: complete quietly instead of failing (see docstring).
+ local_ids = tasks_facade.get_stale_queued_task_run_ids(
+ STALE_AFTER, BATCH_SIZE, environment=tasks_facade.TaskRunEnvironment.LOCAL
+ )
+ local_swept, local_errors = _sweep_each(
+ local_ids,
+ tasks_facade.complete_idle_local_task_run,
+ STALE_LOCAL_QUEUED_TASK_RUN_COMPLETED_COUNTER,
+ STALE_LOCAL_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_swept, prewarmed_errors = _sweep_each(
prewarmed_ids,
- PREWARMED_REASON,
+ lambda run_id: tasks_facade.fail_task_run(run_id, 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_SIZE
+ saturated = len(stale_ids) >= BATCH_SIZE or len(local_ids) >= BATCH_SIZE or len(prewarmed_ids) >= BATCH_SIZE
log = logger.warning if saturated else logger.info
log(
"kill_stale_queued_task_runs.sweep_done",
candidates=len(stale_ids),
swept=swept,
errors=errors,
+ local_candidates=len(local_ids),
+ local_completed=local_swept,
+ local_errors=local_errors,
prewarmed_candidates=len(prewarmed_ids),
prewarmed_swept=prewarmed_swept,
prewarmed_errors=prewarmed_errors,
@@ -245,9 +290,11 @@ def redispatch_orphaned_queued_task_runs() -> None:
RECONCILE_AFTER = datetime.timedelta(minutes=5)
# Janitor sweep is intentionally cross-team — it runs without a team context.
- # cloud_only: local (desktop) runs idle in QUEUED by design while the desktop agent drives
+ # Cloud only: local (desktop) runs idle in QUEUED by design while the desktop agent drives
# them; cloud-dispatching one hijacks the live session and eventually marks it failed.
- candidate_ids = tasks_facade.get_stale_queued_task_run_ids(RECONCILE_AFTER, BATCH_SIZE, cloud_only=True)
+ candidate_ids = tasks_facade.get_stale_queued_task_run_ids(
+ RECONCILE_AFTER, BATCH_SIZE, environment=tasks_facade.TaskRunEnvironment.CLOUD
+ )
outcomes: dict[str, int] = {}
for run_id in candidate_ids:
try:
diff --git a/posthog/tasks/test/test_kill_stale_queued_task_runs.py b/posthog/tasks/test/test_kill_stale_queued_task_runs.py
index 2ac0502dccf0..2e72f29a0876 100644
--- a/posthog/tasks/test/test_kill_stale_queued_task_runs.py
+++ b/posthog/tasks/test/test_kill_stale_queued_task_runs.py
@@ -40,10 +40,17 @@ class TestKillStaleQueuedTaskRuns(TestCase):
updated_age: datetime.timedelta | None = None,
*,
prewarmed: bool = False,
+ environment: str | None = None,
) -> "TaskRun":
TaskRun = apps.get_model("tasks", "TaskRun")
state = {"prewarmed": True, "await_user_message": True} if prewarmed else {}
- run = TaskRun.objects.create(task=self.task, team=self.team, status=status, state=state)
+ run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=status,
+ state=state,
+ **({"environment": environment} if environment else {}),
+ )
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)
@@ -73,6 +80,37 @@ class TestKillStaleQueuedTaskRuns(TestCase):
self.assertIsNone(run.completed_at)
self.assertIsNone(run.error_message)
+ def test_completes_stale_local_run_quietly_instead_of_failing(self) -> None:
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ stale_local = self._make_run(
+ TaskRun.Status.QUEUED, datetime.timedelta(hours=25), environment=TaskRun.Environment.LOCAL
+ )
+ fresh_local = self._make_run(
+ TaskRun.Status.QUEUED, datetime.timedelta(hours=23, minutes=59), environment=TaskRun.Environment.LOCAL
+ )
+ # A local run whose updated_at keeps advancing is a live desktop session (the desktop
+ # PATCHes output/branch as it works) — the created_at hard cap must never reap it.
+ live_local = self._make_run(
+ TaskRun.Status.QUEUED,
+ datetime.timedelta(hours=50),
+ updated_age=datetime.timedelta(hours=2),
+ environment=TaskRun.Environment.LOCAL,
+ )
+
+ with patch("products.tasks.backend.push_dispatcher.notify_task_run_completed") as mock_notify:
+ kill_stale_queued_task_runs()
+
+ stale_local.refresh_from_db()
+ self.assertEqual(stale_local.status, TaskRun.Status.COMPLETED)
+ self.assertIsNone(stale_local.error_message)
+ self.assertIsNotNone(stale_local.completed_at)
+ mock_notify.assert_not_called()
+
+ fresh_local.refresh_from_db()
+ live_local.refresh_from_db()
+ self.assertEqual(fresh_local.status, TaskRun.Status.QUEUED)
+ self.assertEqual(live_local.status, TaskRun.Status.QUEUED)
+
def test_leaves_re_queued_run_with_old_created_at_alone(self) -> None:
TaskRun = apps.get_model("tasks", "TaskRun")
# prepare_for_cloud_handoff re-queues an existing run without resetting
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 4ed5cbef745f..e5e1c34c9f04 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -139,6 +139,7 @@ __all__ = [
"ensure_sandbox_custom_image_builder_task",
"delete_task_automation",
"edit_task_run_living_artifact",
+ "complete_idle_local_task_run",
"fail_task_run",
"finalize_task_run_artifact_uploads",
"finalize_task_staged_artifacts",
@@ -627,13 +628,16 @@ def get_stale_queued_task_run_ids(
*,
created_hard_cap: timedelta | None = None,
hard_cap_min_queued: timedelta = timedelta(hours=1),
- cloud_only: bool = False,
+ environment: str | None = None,
) -> list[UUID]:
"""Ids of runs stuck in QUEUED, by ``updated_at`` age or an optional ``created_at`` backstop.
- ``cloud_only`` restricts the sweep to cloud-environment runs. Local (desktop) runs sit in
- QUEUED by design while the desktop agent drives them, so dispatch-recovery callers must
- exclude them — cloud-dispatching one hijacks the user's live local session.
+ ``environment`` restricts the sweep to runs of that environment. A QUEUED cloud run is
+ awaiting a workflow that should have started, but a local (desktop) run sits in QUEUED by
+ design while the desktop agent drives it — so sweep callers must scope themselves and act
+ per environment: dispatch recovery must only touch cloud runs (cloud-dispatching a local
+ run hijacks the user's live local session), and the janitor fails stale cloud runs but
+ quietly completes stale local ones.
Intentionally cross-team — the janitor sweep runs without a team context.
"""
@@ -642,8 +646,8 @@ def get_stale_queued_task_run_ids(
if created_hard_cap is not None:
stale |= Q(created_at__lt=now - created_hard_cap, updated_at__lt=now - hard_cap_min_queued)
queryset = TaskRun.objects.filter(status=TaskRun.Status.QUEUED) # nosemgrep: celery-task-team-scope-audit
- if cloud_only:
- queryset = queryset.filter(environment=TaskRun.Environment.CLOUD)
+ if environment is not None:
+ queryset = queryset.filter(environment=environment)
return list(queryset.filter(stale).order_by("updated_at").values_list("id", flat=True)[:limit])
@@ -891,6 +895,34 @@ def fail_task_run(run_id: str | UUID, error: str) -> bool:
return True
+def complete_idle_local_task_run(run_id: str | UUID) -> bool:
+ """Quietly finalize a local (desktop-driven) run left idling in QUEUED. Returns whether
+ a run was acted on.
+
+ Local runs never get a cloud workflow, so QUEUED is their steady state while the desktop
+ drives the session — once the desktop goes away, nothing else ever terminalizes the row.
+ An idle session that ended is the run's normal end state, so it finalizes as COMPLETED,
+ and without a push notification: pinging a user a day after they closed their session is
+ noise, not signal.
+
+ Compare-and-set claim (like ``claim_and_fail_stale_run``): the conditional update flips the
+ run only while it is still QUEUED *and* local, so a run that left the queue — or was handed
+ off to cloud (handoff keeps status QUEUED) — between the candidate scan and this call is
+ skipped rather than terminalized under its just-dispatched workflow. The winner finalizes
+ via ``mark_completed`` (``completed_at``, stream + analytics). Intentionally cross-team
+ (janitor sweep).
+ """
+ claimed = TaskRun.objects.filter(
+ pk=run_id, status=TaskRun.Status.QUEUED, environment=TaskRun.Environment.LOCAL
+ ).update(status=TaskRun.Status.COMPLETED) # nosemgrep: celery-task-team-scope-audit
+ if not claimed:
+ return False
+ run = TaskRun.objects.filter(pk=run_id).first() # nosemgrep: celery-task-team-scope-audit
+ if run is not None:
+ run.mark_completed(notify=False, analytics_properties={"finalized_by": "stale_local_queued_sweep"})
+ return True
+
+
def claim_and_fail_stale_run(run_id: str | UUID, error: str) -> bool:
"""Compare-and-set reap of a stranded run. Returns whether this caller won the claim.
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index db4c1e21ca66..7418aeed9ac6 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -1414,16 +1414,24 @@ class TaskRun(models.Model):
return round((self.completed_at - self.created_at).total_seconds(), 1)
return 0.0
- def mark_completed(self):
- """Mark the progress as completed."""
+ def mark_completed(self, *, notify: bool = True, analytics_properties: dict | None = None) -> None:
+ """Mark the progress as completed.
+
+ ``notify=False`` skips the push notification — for janitor-style finalization of a run
+ the user is no longer watching, where a "finished" ping long after the fact is noise.
+ ``analytics_properties`` are merged into the ``task_run_completed`` capture so swept
+ completions stay distinguishable from organic ones.
+ """
self.status = self.Status.COMPLETED
self.completed_at = django_timezone.now()
self.save(update_fields=["status", "completed_at"])
self.publish_stream_state_event()
self.capture_event(
"task_run_completed",
- {"duration_seconds": self._duration_seconds()},
+ {"duration_seconds": self._duration_seconds(), **(analytics_properties or {})},
)
+ if not notify:
+ return
from products.tasks.backend.push_dispatcher import notify_task_run_completed
notify_task_run_completed(self)
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index 409eb2ff5ded..c961ee2a2eac 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -358,7 +358,7 @@ def redispatch_orphaned_task_run(run_id: str) -> str:
# Local (desktop) runs idle in QUEUED while the user's local agent drives them — there is no
# lost dispatch to recover. Starting a cloud workflow here would hijack the live session: the
# sandbox boots without the repo ever being cloned, burns its retries, and marks the user's
- # run FAILED. The sweep already filters these out (cloud_only); this guards direct callers.
+ # run FAILED. The sweep already filters these out (environment=CLOUD); this guards direct callers.
if task_run.environment == TaskRun.Environment.LOCAL:
return "skipped_local"
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index e9f0a38c7aa7..b0048467d089 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -216,16 +216,25 @@ class TestFacadeReadsAndMappers(TestCase):
stale_ids = facade.get_stale_queued_task_run_ids(older_than=timedelta(hours=24), limit=100)
self.assertIn(stale.id, stale_ids)
- # The unrestricted sweep (24h killer) still reaps abandoned local runs.
+ # Unfiltered, the query returns stale runs of every environment.
self.assertIn(stale_local.id, stale_ids)
self.assertNotIn(fresh.id, stale_ids)
- # The dispatch reconciler must never see local (desktop-driven) runs — re-dispatching
- # one starts a cloud workflow that hijacks and eventually fails the live local session.
- cloud_ids = facade.get_stale_queued_task_run_ids(older_than=timedelta(hours=24), limit=100, cloud_only=True)
+ # The dispatch reconciler and the 24h fail sweep must never see local (desktop-driven)
+ # runs — re-dispatching one starts a cloud workflow that hijacks the live local session,
+ # and failing one turns an idle desktop session into a bogus failure.
+ cloud_ids = facade.get_stale_queued_task_run_ids(
+ older_than=timedelta(hours=24), limit=100, environment=TaskRun.Environment.CLOUD
+ )
self.assertIn(stale.id, cloud_ids)
self.assertNotIn(stale_local.id, cloud_ids)
+ local_ids = facade.get_stale_queued_task_run_ids(
+ older_than=timedelta(hours=24), limit=100, environment=TaskRun.Environment.LOCAL
+ )
+ self.assertIn(stale_local.id, local_ids)
+ self.assertNotIn(stale.id, local_ids)
+
with patch("products.tasks.backend.push_dispatcher.notify_task_run_failed"):
self.assertTrue(facade.fail_task_run(stale.id, "boom"))
# already-failed run is no longer QUEUED -> no-op
@@ -234,6 +243,29 @@ class TestFacadeReadsAndMappers(TestCase):
self.assertEqual(stale.status, TaskRun.Status.FAILED.value)
self.assertEqual(stale.error_message, "boom")
+ def test_complete_idle_local_task_run_skips_run_handed_off_to_cloud(self):
+ task = self._make_task()
+ idle_local = TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.QUEUED, environment=TaskRun.Environment.LOCAL
+ )
+ # Between the janitor's candidate scan and the finalize call, a user can resume the run
+ # into cloud (environment flips to CLOUD, workflow dispatched) — completing it then
+ # would kill a just-started cloud run.
+ handed_off = TaskRun.objects.create(
+ task=task, team=self.team, status=TaskRun.Status.QUEUED, environment=TaskRun.Environment.CLOUD
+ )
+
+ with patch("products.tasks.backend.push_dispatcher.notify_task_run_completed") as mock_notify:
+ self.assertTrue(facade.complete_idle_local_task_run(idle_local.id))
+ self.assertFalse(facade.complete_idle_local_task_run(handed_off.id))
+
+ idle_local.refresh_from_db()
+ self.assertEqual(idle_local.status, TaskRun.Status.COMPLETED.value)
+ self.assertIsNone(idle_local.error_message)
+ mock_notify.assert_not_called()
+ handed_off.refresh_from_db()
+ self.assertEqual(handed_off.status, TaskRun.Status.QUEUED.value)
+
@parameterized.expand(
[
# A directory snapshot captured at a still-allowed path is carried into the new run.