: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): measure queued TaskRun age from queue entry (#81308)
Alessandro Pogliaghiaa5f3696088b
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex e5ab0030db34..a12487d459ca 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -809,7 +809,9 @@ def capture_task_run_state_metrics() -> None:)oldest_age_gauge = Gauge("posthog_tasks_oldest_open_run_age_seconds",- "Age (seconds) of the oldest TaskRun still in a given non-terminal status, by origin_product and run_environment.",+ "Age (seconds) of the oldest TaskRun still in a given non-terminal status, by origin_product and "+ "run_environment. For `queued` this is time spent waiting in the queue, so a re-queued run counts "+ "from its re-queue rather than from row creation.",registry=registry,labelnames=["status", "origin_product", "run_environment"],)diff --git a/posthog/tasks/test/test_task_run_state_metrics.py b/posthog/tasks/test/test_task_run_state_metrics.pyindex d74d00f7b378..c0249a1e4c76 100644--- a/posthog/tasks/test/test_task_run_state_metrics.py+++ b/posthog/tasks/test/test_task_run_state_metrics.py@@ -34,6 +34,8 @@ class TestCaptureTaskRunStateMetrics(TestCase):status: "TaskRun.Status",environment: "Optional[TaskRun.Environment]" = None,created_at: Optional[datetime] = None,+ updated_at: Optional[datetime] = None,+ queued_at: Optional[datetime] = None,) -> "TaskRun":Task = apps.get_model("tasks", "Task")TaskRun = apps.get_model("tasks", "TaskRun")@@ -51,8 +53,14 @@ class TestCaptureTaskRunStateMetrics(TestCase):status=status,environment=environment,)- if created_at is not None:- TaskRun.objects.filter(pk=run.pk).update(created_at=created_at)+ # .update() bypasses auto_now, so an explicit updated_at sticks.+ overrides = {+ field: value+ for field, value in (("created_at", created_at), ("updated_at", updated_at), ("queued_at", queued_at))+ if value is not None+ }+ if overrides:+ TaskRun.objects.filter(pk=run.pk).update(**overrides)run.refresh_from_db()return run@@ -143,6 +151,41 @@ class TestCaptureTaskRunStateMetrics(TestCase):# Oldest run was ~30 minutes ago; allow generous slack for test timing.assert 1500 < age < 2400+ @parameterized.expand(+ [+ # A cloud handoff re-queues an existing run without resetting created_at, so anchoring+ # the queue wait on created_at would report the whole pre-handoff lifetime as backlog.+ ("requeued_by_handoff", apps.get_model("tasks", "TaskRun").Status.QUEUED, 30, 1500, 2400),+ # An unrelated write to a still-queued run advances updated_at, so anchoring on+ # updated_at would make a genuinely stranded run look newly queued.+ ("written_while_still_queued", apps.get_model("tasks", "TaskRun").Status.QUEUED, 360, 20000, 23000),+ # Rows queued before queued_at existed fall back to created_at.+ ("queued_before_the_field_existed", apps.get_model("tasks", "TaskRun").Status.QUEUED, None, 20000, 23000),+ ("in_progress_reports_lifetime", apps.get_model("tasks", "TaskRun").Status.IN_PROGRESS, 30, 20000, 23000),+ ]+ )+ def test_oldest_age_anchors_queued_runs_on_queued_at(+ self, _name: str, status: "TaskRun.Status", queued_minutes_ago: Optional[int], low: int, high: int+ ) -> None:+ Task = apps.get_model("tasks", "Task")+ now = timezone.now()+ self._make_task_run(+ origin=Task.OriginProduct.SLACK,+ status=status,+ created_at=now - timedelta(hours=6),+ updated_at=now - timedelta(minutes=30),+ queued_at=None if queued_minutes_ago is None else now - timedelta(minutes=queued_minutes_ago),+ )++ registry = self._run_with_registry()++ age = registry.get_sample_value(+ "posthog_tasks_oldest_open_run_age_seconds",+ {"status": status.value, "origin_product": "slack", "run_environment": "cloud"},+ )+ assert age is not None+ assert low < age < high+def test_emits_runs_created_1h_by_origin_and_environment(self) -> None:Task = apps.get_model("tasks", "Task")TaskRun = apps.get_model("tasks", "TaskRun")diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex a46011a9d337..876a78554276 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -33,6 +33,7 @@ from django.db.models import (Case,CharField,Count,+ DateTimeField,Exists,F,Func,@@ -46,6 +47,7 @@ from django.db.models import (When,)from django.db.models.fields.json import KeyTextTransform+from django.db.models.functions import Coalescefrom django.utils import timezone as django_timezonefrom django.utils.http import content_disposition_header@@ -1046,9 +1048,21 @@ def collect_task_run_state_metrics(The caller (a core celery task) owns which statuses count as open/age/terminal and therecency window; this returns the raw numbers grouped by (status, environment,parent origin_product) so no ORM leaks across the boundary.++ A QUEUED run's age counts from ``queued_at``, not from row creation:+ ``prepare_for_cloud_handoff`` re-queues an existing run without resetting ``created_at``,+ so a desktop-to-cloud handoff would otherwise report the whole prior run's lifetime as+ queue wait. Rows queued before ``queued_at`` existed fall back to ``created_at``, which is+ exact for a run that was only ever queued once. Every other non-terminal status counts+ from creation, where elapsed lifetime is the useful age."""now = django_timezone.now()window_start = now - timedelta(seconds=window_seconds)+ age_anchor = Case(+ When(status=TaskRun.Status.QUEUED, then=Coalesce(F("queued_at"), F("created_at"))),+ default=F("created_at"),+ output_field=DateTimeField(),+ )return contracts.TaskRunStateMetricsDTO(runs_in_status=_gauge_rows(TaskRun.objects.filter(status__in=open_statuses)@@ -1060,8 +1074,8 @@ def collect_task_run_state_metrics(oldest_open_age_seconds=_gauge_rows(TaskRun.objects.filter(status__in=age_statuses).values("status", "environment", "task__origin_product")- .annotate(oldest_created_at=Min("created_at")),- "oldest_created_at",+ .annotate(oldest_waiting_since=Min(age_anchor)),+ "oldest_waiting_since",with_status=True,now=now,),@@ -4128,6 +4142,7 @@ def resume_task_run_in_cloud(prior_status = run.statusprior_environment = run.environmentprior_completed_at = run.completed_at+ prior_queued_at = run.queued_atprior_state = dict(run.state or {})run.prepare_for_cloud_handoff()@@ -4147,9 +4162,20 @@ def resume_task_run_in_cloud(run.status = prior_statusrun.environment = prior_environmentrun.completed_at = prior_completed_at+ run.queued_at = prior_queued_atrun.state = prior_staterun.error_message = "Failed to start cloud workflow"- run.save(update_fields=["status", "environment", "completed_at", "state", "error_message", "updated_at"])+ run.save(+ update_fields=[+ "status",+ "environment",+ "completed_at",+ "queued_at",+ "state",+ "error_message",+ "updated_at",+ ]+ )run.publish_stream_state_event()return "workflow_failed", None, Nonediff --git a/products/tasks/backend/migrations/0089_taskrun_queued_at.py b/products/tasks/backend/migrations/0089_taskrun_queued_at.pynew file mode 100644index 000000000000..15d9463dafa2--- /dev/null+++ b/products/tasks/backend/migrations/0089_taskrun_queued_at.py@@ -0,0 +1,15 @@+# Generated by Django 5.2.17 on 2026-08-11 16:03++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("tasks", "0088_backfill_task_search_documents")]++ operations = [+ migrations.AddField(+ model_name="taskrun",+ name="queued_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex cf6892a4e9b6..78d36976b40e 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0088_backfill_task_search_documents+0089_taskrun_queued_atdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex b28bf89b1262..8f88652d0c36 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -454,6 +454,7 @@ class Task(DeletedMetaFields, models.Model):task=self,team=self.team,status=TaskRun.Status.QUEUED,+ queued_at=django_timezone.now(),**({"environment": environment} if environment else {}),state=state,branch=branch,@@ -466,6 +467,10 @@ class Task(DeletedMetaFields, models.Model):"run_id": str(task_run.id),"mode": mode,"environment": task_run.environment,+ # The bare `environment` property gets clobbered by the analytics client's+ # deployment-environment super-property, so ship the run's local/cloud value+ # under an unclobbered name too — as TaskRun.capture_event already does.+ "run_environment": task_run.environment,"is_resume": is_resume,"has_pending_message": has_pending,# Loop attribution: this event uses Task.capture_event (not TaskRun's),@@ -1872,6 +1877,12 @@ class TaskRun(models.Model):created_at = models.DateTimeField(default=django_timezone.now)updated_at = models.DateTimeField(auto_now=True)completed_at = models.DateTimeField(null=True, blank=True)+ # When the run last entered QUEUED. `created_at` can't stand in for it because+ # `prepare_for_cloud_handoff` re-queues an existing run without resetting it, and+ # `updated_at` can't either because any unrelated write to a still-queued run would+ # move it. Null on rows queued before this field existed; readers fall back to+ # `created_at`, which is exact for a run that was only ever queued once.+ queued_at = models.DateTimeField(null=True, blank=True)class Meta:db_table = "posthog_task_run"@@ -1948,6 +1959,7 @@ class TaskRun(models.Model):"""self.status = self.Status.QUEUEDself.environment = self.Environment.CLOUD+ self.queued_at = django_timezone.now()self.completed_at = Noneself.error_message = None@@ -1978,6 +1990,7 @@ class TaskRun(models.Model):update_fields=["status","environment",+ "queued_at","completed_at","error_message","state",