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.

perf(tasks): denormalize origin_product onto TaskRun for state gauges (#92410)

posthog[bot]e795859e7907
diff --git a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
index e68a15b7e624..70eb2c7d47d8 100644
--- a/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
+++ b/posthog/management/migration_analysis/atomic_false_acknowledged_migrations.txt
@@ -19,6 +19,7 @@ replay_vision.0070_backfill_usage_scanner_id
tasks.0088_backfill_task_search_documents
tasks.0092_backfill_task_last_activity_at
signals.0099_backfill_first_visible_at
+tasks.0110_backfill_taskrun_origin_product
# Does run CONCURRENTLY, one index per sourcebatch partition, but from RunPython
# (the partition list is only known at runtime), which the type-based check can't see.
warehouse_sources_queue.0008_sourcebatch_superseded
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 1769f61c6cb6..498a32323936 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1269,7 +1269,7 @@ def _gauge_rows(values_qs, value_key: str, *, with_status: bool, now=None) -> li
rows.append(
contracts.TaskRunGaugeRow(
environment=row["environment"],
- origin_product=row["task__origin_product"] or "unknown",
+ origin_product=row["origin_product"] or "unknown",
value=value,
status=row["status"] if with_status else None,
)
@@ -1288,7 +1288,7 @@ def collect_task_run_state_metrics(
The caller (a core celery task) owns which statuses count as open/age/terminal and the
recency window; this returns the raw numbers grouped by (status, environment,
- parent origin_product) so no ORM leaks across the boundary.
+ 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_resume`` re-queues an existing run without resetting ``created_at``,
@@ -1307,14 +1307,14 @@ def collect_task_run_state_metrics(
return contracts.TaskRunStateMetricsDTO(
runs_in_status=_gauge_rows(
TaskRun.objects.filter(status__in=open_statuses)
- .values("status", "environment", "task__origin_product")
+ .values("status", "environment", "origin_product")
.annotate(count=Count("id")),
"count",
with_status=True,
),
oldest_open_age_seconds=_gauge_rows(
TaskRun.objects.filter(status__in=age_statuses)
- .values("status", "environment", "task__origin_product")
+ .values("status", "environment", "origin_product")
.annotate(oldest_waiting_since=Min(age_anchor)),
"oldest_waiting_since",
with_status=True,
@@ -1322,14 +1322,14 @@ def collect_task_run_state_metrics(
),
created_recently=_gauge_rows(
TaskRun.objects.filter(created_at__gte=window_start)
- .values("environment", "task__origin_product")
+ .values("environment", "origin_product")
.annotate(count=Count("id")),
"count",
with_status=False,
),
terminal_recently=_gauge_rows(
TaskRun.objects.filter(status__in=terminal_statuses, updated_at__gte=window_start)
- .values("status", "environment", "task__origin_product")
+ .values("status", "environment", "origin_product")
.annotate(count=Count("id")),
"count",
with_status=True,
diff --git a/products/tasks/backend/migrations/0109_taskrun_origin_product.py b/products/tasks/backend/migrations/0109_taskrun_origin_product.py
new file mode 100644
index 000000000000..f616eff9745e
--- /dev/null
+++ b/products/tasks/backend/migrations/0109_taskrun_origin_product.py
@@ -0,0 +1,23 @@
+from django.db import migrations, models
+
+import products.tasks.backend.models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0108_channel_auto_archive_after_days"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="taskrun",
+ name="origin_product",
+ field=models.CharField(
+ blank=True,
+ choices=products.tasks.backend.models.task_origin_product_choices,
+ default="",
+ db_default="",
+ max_length=20,
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/0110_backfill_taskrun_origin_product.py b/products/tasks/backend/migrations/0110_backfill_taskrun_origin_product.py
new file mode 100644
index 000000000000..9e7a6a5fd0e8
--- /dev/null
+++ b/products/tasks/backend/migrations/0110_backfill_taskrun_origin_product.py
@@ -0,0 +1,41 @@
+from django.db import migrations
+
+BATCH_SIZE = 2000
+
+
+def backfill_origin_product(apps, schema_editor):
+ # Copy each run's parent task origin_product onto the run. Keyset-paginate over the
+ # run id so the backfill runs in bounded batches and every row is visited once.
+ TaskRun = apps.get_model("tasks", "TaskRun")
+ last_id = None
+ with schema_editor.connection.cursor() as cursor:
+ while True:
+ qs = TaskRun.objects.order_by("id")
+ if last_id is not None:
+ qs = qs.filter(id__gt=last_id)
+ ids = list(qs.values_list("id", flat=True)[:BATCH_SIZE])
+ if not ids:
+ break
+ last_id = ids[-1]
+ cursor.execute(
+ """
+ UPDATE posthog_task_run tr
+ SET origin_product = t.origin_product
+ FROM posthog_task t
+ WHERE tr.task_id = t.id AND tr.id = ANY(%s) AND tr.origin_product = ''
+ """,
+ [ids],
+ )
+
+
+class Migration(migrations.Migration):
+ # Non-atomic so the backfill runs in bounded batches without one long transaction.
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0109_taskrun_origin_product"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_origin_product, migrations.RunPython.noop),
+ ]
diff --git a/products/tasks/backend/migrations/0111_taskrun_status_env_origin_idx.py b/products/tasks/backend/migrations/0111_taskrun_status_env_origin_idx.py
new file mode 100644
index 000000000000..a4e72521b72c
--- /dev/null
+++ b/products/tasks/backend/migrations/0111_taskrun_status_env_origin_idx.py
@@ -0,0 +1,24 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ # CONCURRENTLY so building the index does not take an ACCESS EXCLUSIVE lock on
+ # posthog_task_run. Concurrent builds cannot run in a transaction, so the migration
+ # is non-atomic.
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0110_backfill_taskrun_origin_product"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="taskrun",
+ index=models.Index(
+ fields=["status", "environment", "origin_product"],
+ name="task_run_status_env_origin_idx",
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/0112_taskrun_terminal_updated_idx.py b/products/tasks/backend/migrations/0112_taskrun_terminal_updated_idx.py
new file mode 100644
index 000000000000..562c688979df
--- /dev/null
+++ b/products/tasks/backend/migrations/0112_taskrun_terminal_updated_idx.py
@@ -0,0 +1,23 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0111_taskrun_status_env_origin_idx"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="taskrun",
+ index=models.Index(
+ fields=["updated_at"],
+ include=["status", "environment", "origin_product"],
+ name="task_run_terminal_updated_idx",
+ condition=models.Q(status__in=["completed", "failed", "cancelled"]),
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 4cb3616d51c0..3dfe9727367c 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0108_channel_auto_archive_after_days
+0112_taskrun_terminal_updated_idx
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 861b34b30893..fc84baa8ed44 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -1981,6 +1981,16 @@ class TaskRun(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="runs")
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)
+ # Copy of the parent task's origin_product, populated on creation and never changed.
+ # It lets the per-minute monitoring gauges group by origin_product without joining
+ # posthog_task on every run row. See `collect_task_run_state_metrics`.
+ origin_product = models.CharField(
+ max_length=20,
+ choices=task_origin_product_choices,
+ blank=True,
+ default="",
+ db_default="",
+ )
active_task_session = models.ForeignKey(
TaskSession,
on_delete=models.SET_NULL,
@@ -2109,11 +2119,30 @@ class TaskRun(models.Model):
name="task_run_team_stage_task_idx",
condition=models.Q(stage__isnull=False),
),
+ # Open statuses remain selective, so status leads the index for untimed gauges.
+ models.Index(
+ fields=["status", "environment", "origin_product"],
+ name="task_run_status_env_origin_idx",
+ ),
+ # Terminal rows dominate over time, so the recency range must lead this partial index.
+ models.Index(
+ fields=["updated_at"],
+ include=["status", "environment", "origin_product"],
+ name="task_run_terminal_updated_idx",
+ condition=models.Q(status__in=["completed", "failed", "cancelled"]),
+ ),
]
def __str__(self):
return f"Run for {self.task.title} - {self.get_status_display()}"
+ def save(self, *args, **kwargs):
+ # Mirror the parent task's origin_product onto the run once, at creation, so the
+ # monitoring gauges can group by it locally.
+ if self._state.adding and not self.origin_product and self.task_id:
+ self.origin_product = self.task.origin_product
+ super().save(*args, **kwargs)
+
@property
def mode(self) -> str:
"""Get the execution mode from state. Defaults to 'background'."""