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.

feat(tasks): schedule task runs for future dispatch (#102245)

Oliver Browne65b31a9068e5
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 036ae6de3429..056ea7bd7d35 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1599,6 +1599,7 @@ def create_and_run_task(
create_pr: bool = True,
mode: str = "background",
start_workflow: bool = True,
+ scheduled_at: datetime | None = None,
branch: str | None = None,
signal_report_id: str | None = None,
free_trial_enabled: bool | None = None,
@@ -1620,6 +1621,9 @@ def create_and_run_task(
``free_trial_enabled`` is a free-trial verdict the caller already resolved. Auto-start reads
that flag before it takes the report row lock, so handing the result over keeps the flag
request out of the lock. Left NULL, the gate reads the flag itself.
+
+ ``scheduled_at`` creates the run in NOT_STARTED and defers its workflow until the dispatcher
+ materializes it at or after that time. The run still stores its complete execution settings.
"""
# create_pr=False sessions (research, repo selection, custom agents) can never open the
# billable PR, so the quota gate must not block them.
@@ -1645,6 +1649,7 @@ def create_and_run_task(
create_pr=create_pr,
mode=mode,
start_workflow=start_workflow,
+ scheduled_at=scheduled_at,
branch=branch,
signal_report_id=signal_report_id,
internal=internal,
@@ -5262,8 +5267,9 @@ _STARTABLE_TASK_RUN_STATUSES = (TaskRun.Status.NOT_STARTED, TaskRun.Status.QUEUE
def check_task_run_startable(run_id: str | UUID, task_id: str | UUID, team_id: int) -> tuple[str, str | None]:
"""Whether a run can be started via the start endpoint.
- Returns ``"not_found"`` (run missing), ``"not_cloud"``, ``"bad_status:<current>"``, or
- ``"ok"``, together with the stored run source. The view applies the usage gate before ``start_task_run``.
+ Returns ``"not_found"`` (run missing), ``"not_cloud"``, ``"scheduled"``,
+ ``"bad_status:<current>"``, or ``"ok"``, together with the stored run source. The view
+ applies the usage gate before ``start_task_run``.
"""
run = _get_visible_run(run_id, task_id, team_id)
if run is None:
@@ -5271,6 +5277,8 @@ def check_task_run_startable(run_id: str | UUID, task_id: str | UUID, team_id: i
run_source = (run.state or {}).get("run_source")
if run.environment != TaskRun.Environment.CLOUD:
return "not_cloud", run_source
+ if run.status == TaskRun.Status.NOT_STARTED and run.scheduled_at is not None:
+ return "scheduled", run_source
if run.status not in _STARTABLE_TASK_RUN_STATUSES:
return f"bad_status:{run.status}", run_source
return "ok", run_source
diff --git a/products/tasks/backend/logic/services/workflow_dispatch.py b/products/tasks/backend/logic/services/workflow_dispatch.py
index e6ddda8c3b41..5912944aae07 100644
--- a/products/tasks/backend/logic/services/workflow_dispatch.py
+++ b/products/tasks/backend/logic/services/workflow_dispatch.py
@@ -2,16 +2,20 @@ import random
from collections.abc import Callable
from dataclasses import asdict
from datetime import datetime, timedelta
-from typing import Any, Protocol
+from typing import Any, Protocol, cast
+from uuid import UUID
from django.db import close_old_connections, transaction
from django.db.models import Count, F, Min, Q
from django.utils import timezone as django_timezone
from posthog.dataclasses import frozen
-from posthog.temporal.oauth import PosthogMcpScopes
+from posthog.temporal.oauth import MCP_SCOPE_PRESETS, SCOUT_SCOPE_PRESETS, PosthogMcpScopes
from products.tasks.backend.metrics import (
+ SCHEDULED_TASK_RUN_DUE,
+ SCHEDULED_TASK_RUN_MATERIALIZATION_TOTAL,
+ SCHEDULED_TASK_RUN_OLDEST_DUE_AGE_SECONDS,
WORKFLOW_DISPATCH_CLAIMED,
WORKFLOW_DISPATCH_CREATED_TOTAL,
WORKFLOW_DISPATCH_DEAD_TOTAL,
@@ -121,22 +125,191 @@ def create_dispatch(task_run: TaskRun, kind: str, payload: dict[str, Any], workf
return dispatch
-def claim_dispatches(instance_id: str, batch_size: int, lease: timedelta) -> list[TaskWorkflowDispatch]:
+def _validated_scheduled_mcp_scopes(value: object) -> PosthogMcpScopes | None:
+ if isinstance(value, str):
+ return cast(PosthogMcpScopes, value) if value in MCP_SCOPE_PRESETS else None
+ if isinstance(value, list) and all(isinstance(scope, str) for scope in value):
+ return cast(PosthogMcpScopes, value)
+ if isinstance(value, dict):
+ preset = value.get("preset")
+ extra_write_scopes = value.get("extra_write_scopes")
+ if (
+ preset in SCOUT_SCOPE_PRESETS
+ and isinstance(extra_write_scopes, list)
+ and all(isinstance(scope, str) for scope in extra_write_scopes)
+ ):
+ return cast(PosthogMcpScopes, value)
+ return None
+
+
+def _scheduled_dispatch_options(task_run: TaskRun) -> WorkflowDispatchOptions | None:
+ state = task_run.state if isinstance(task_run.state, dict) else {}
+ pending = state.get("pending_dispatch")
+ if not isinstance(pending, dict):
+ return None
+
+ user_id = pending.get("user_id")
+ create_pr = pending.get("create_pr")
+ posthog_mcp_scopes = _validated_scheduled_mcp_scopes(pending.get("posthog_mcp_scopes"))
+ workflow_id_prefix = pending.get("workflow_id_prefix")
+ slack_thread_context = pending.get("slack_thread_context")
+ if (
+ not isinstance(user_id, int)
+ or isinstance(user_id, bool)
+ or not isinstance(create_pr, bool)
+ or posthog_mcp_scopes is None
+ or (workflow_id_prefix is not None and not isinstance(workflow_id_prefix, str))
+ or (slack_thread_context is not None and not isinstance(slack_thread_context, dict))
+ ):
+ return None
+ return WorkflowDispatchOptions(
+ user_id=user_id,
+ create_pr=create_pr,
+ posthog_mcp_scopes=posthog_mcp_scopes,
+ slack_thread_context=slack_thread_context,
+ workflow_id_prefix=workflow_id_prefix,
+ )
+
+
+def _prepare_scheduled_dispatch(
+ task_run: TaskRun,
+ existing_dispatch: tuple[str, str] | None,
+ now: datetime,
+) -> TaskWorkflowDispatch | None:
+ options = _scheduled_dispatch_options(task_run)
+ if options is None:
+ raise ValueError("Invalid scheduled dispatch options")
+
+ default_workflow_id = TaskRun.get_workflow_id(task_run.task_id, task_run.id)
+ workflow_id = TaskRun.get_workflow_id(task_run.task_id, task_run.id, options.workflow_id_prefix)
+ max_length = TaskWorkflowDispatch._meta.get_field("workflow_id").max_length
+ if max_length is not None and len(workflow_id) > max_length:
+ raise ValueError("Scheduled workflow ID exceeds the dispatch field length")
+ if existing_dispatch is not None:
+ if existing_dispatch[1] == TaskWorkflowDispatch.Status.DEAD:
+ raise ValueError("Scheduled dispatch is already dead")
+ workflow_id = existing_dispatch[0]
+
+ if workflow_id != default_workflow_id:
+ task_run.state = {**task_run.state, "workflow_id": workflow_id}
+ task_run.updated_at = now
+ if existing_dispatch is not None:
+ return None
+ return TaskWorkflowDispatch(
+ team_id=task_run.team.parent_team_id or task_run.team_id,
+ task_run_id=task_run.id,
+ workflow_id=workflow_id,
+ dispatch_kind=TaskWorkflowDispatch.Kind.CREATE,
+ payload=build_create_payload(options),
+ status=TaskWorkflowDispatch.Status.PENDING,
+ enqueued_at=now,
+ next_attempt_at=now,
+ created_at=now,
+ updated_at=now,
+ )
+
+
+def materialize_due_scheduled_task_runs(batch_size: int) -> int:
+ if batch_size <= 0:
+ return 0
+
now = django_timezone.now()
with transaction.atomic():
- # This process intentionally claims work across every team.
- rows = list(
- TaskWorkflowDispatch.objects.unscoped()
+ # Rows stop matching this partial-index scan as soon as they become QUEUED. Repeated
+ # LIMIT queries therefore page through the due set without OFFSET, and SKIP LOCKED lets
+ # dispatcher replicas drain it concurrently without coordinating outside Postgres.
+ task_runs = list(
+ TaskRun.objects.filter(
+ status=TaskRun.Status.NOT_STARTED,
+ environment=TaskRun.Environment.CLOUD,
+ scheduled_at__lte=now,
+ task__deleted=False,
+ )
+ .select_related("team")
+ .only("id", "task_id", "team_id", "team__parent_team_id", "state", "scheduled_at")
+ .order_by("scheduled_at", "id")
+ .select_for_update(of=("self",), skip_locked=True)[:batch_size]
+ )
+ if not task_runs:
+ return 0
+
+ existing_dispatches = {
+ task_run_id: (workflow_id, status)
+ for task_run_id, workflow_id, status in TaskWorkflowDispatch.objects.unscoped()
.filter(
- Q(status=TaskWorkflowDispatch.Status.PENDING, next_attempt_at__lte=now)
- | Q(status=TaskWorkflowDispatch.Status.CLAIMED, lease_expires_at__lte=now)
+ task_run_id__in=[task_run.id for task_run in task_runs],
+ dispatch_kind=TaskWorkflowDispatch.Kind.CREATE,
)
- .order_by("next_attempt_at", "created_at")
+ .values_list("task_run_id", "workflow_id", "status")
+ }
+ dispatches: list[TaskWorkflowDispatch] = []
+ valid_run_ids: list[UUID] = []
+ invalid_run_ids: list[UUID] = []
+ prefixed_runs: list[TaskRun] = []
+ for task_run in task_runs:
+ try:
+ dispatch = _prepare_scheduled_dispatch(task_run, existing_dispatches.get(task_run.id), now)
+ except ValueError:
+ invalid_run_ids.append(task_run.id)
+ continue
+ if dispatch is not None:
+ dispatches.append(dispatch)
+ if task_run.workflow_id != TaskRun.get_workflow_id(task_run.task_id, task_run.id):
+ prefixed_runs.append(task_run)
+ valid_run_ids.append(task_run.id)
+
+ TaskRun.objects.bulk_update(prefixed_runs, ["state", "updated_at"], batch_size=batch_size)
+ TaskWorkflowDispatch.objects.unscoped().bulk_create(dispatches, batch_size=batch_size, ignore_conflicts=True)
+ TaskRun.objects.filter(id__in=valid_run_ids, status=TaskRun.Status.NOT_STARTED).update(
+ status=TaskRun.Status.QUEUED,
+ queued_at=now,
+ updated_at=now,
+ )
+ TaskRun.objects.filter(id__in=invalid_run_ids, status=TaskRun.Status.NOT_STARTED).update(
+ status=TaskRun.Status.FAILED,
+ completed_at=now,
+ error_message=(
+ "Couldn't start this scheduled task because its configuration is incomplete. "
+ "Create a new scheduled task, and contact support if this keeps happening."
+ ),
+ updated_at=now,
+ )
+
+ SCHEDULED_TASK_RUN_MATERIALIZATION_TOTAL.labels(outcome="materialized").inc(len(valid_run_ids))
+ WORKFLOW_DISPATCH_CREATED_TOTAL.labels(kind=TaskWorkflowDispatch.Kind.CREATE).inc(len(dispatches))
+ SCHEDULED_TASK_RUN_MATERIALIZATION_TOTAL.labels(outcome="invalid").inc(len(invalid_run_ids))
+ return len(valid_run_ids)
+
+
+def claim_dispatches(instance_id: str, batch_size: int, lease: timedelta) -> list[TaskWorkflowDispatch]:
+ if batch_size <= 0:
+ return []
+
+ now = django_timezone.now()
+ with transaction.atomic():
+ # Reclaim expired leases first so a sustained pending backlog cannot starve work
+ # whose previous dispatcher died. Separate scans let each status use its ordered
+ # partial index instead of scanning and sorting the whole ready outbox for an OR.
+ expired_rows = list(
+ TaskWorkflowDispatch.objects.unscoped()
+ .filter(status=TaskWorkflowDispatch.Status.CLAIMED, lease_expires_at__lte=now)
+ .order_by("lease_expires_at", "next_attempt_at", "created_at")
.select_for_update(skip_locked=True)[:batch_size]
)
- expired_count = sum(row.status == TaskWorkflowDispatch.Status.CLAIMED for row in rows)
- if expired_count:
- WORKFLOW_DISPATCH_LEASE_EXPIRED_TOTAL.inc(expired_count)
+ remaining = batch_size - len(expired_rows)
+ pending_rows = (
+ list(
+ TaskWorkflowDispatch.objects.unscoped()
+ .filter(status=TaskWorkflowDispatch.Status.PENDING, next_attempt_at__lte=now)
+ .order_by("next_attempt_at", "created_at")
+ .select_for_update(skip_locked=True)[:remaining]
+ )
+ if remaining
+ else []
+ )
+ rows = expired_rows + pending_rows
+ if expired_rows:
+ WORKFLOW_DISPATCH_LEASE_EXPIRED_TOTAL.inc(len(expired_rows))
ids = [row.id for row in rows]
TaskWorkflowDispatch.objects.unscoped().filter(id__in=ids).update(
status=TaskWorkflowDispatch.Status.CLAIMED,
@@ -144,9 +317,12 @@ def claim_dispatches(instance_id: str, batch_size: int, lease: timedelta) -> lis
lease_expires_at=now + lease,
attempt_count=F("attempt_count") + 1,
)
- return list(
- TaskWorkflowDispatch.objects.unscoped().filter(id__in=ids).order_by("next_attempt_at", "created_at")
- )
+ for row in rows:
+ row.status = TaskWorkflowDispatch.Status.CLAIMED
+ row.claimed_by = instance_id
+ row.lease_expires_at = now + lease
+ row.attempt_count += 1
+ return rows
def sample_dispatch_metrics() -> None:
@@ -167,6 +343,18 @@ def sample_dispatch_metrics() -> None:
oldest = values["oldest_ready"]
WORKFLOW_DISPATCH_OLDEST_READY_AGE_SECONDS.set(max(0.0, (now - oldest).total_seconds()) if oldest else 0)
+ scheduled_values = TaskRun.objects.filter(
+ status=TaskRun.Status.NOT_STARTED,
+ environment=TaskRun.Environment.CLOUD,
+ scheduled_at__lte=now,
+ task__deleted=False,
+ ).aggregate(ready=Count("id"), oldest_ready=Min("scheduled_at"))
+ SCHEDULED_TASK_RUN_DUE.set(scheduled_values["ready"] or 0)
+ oldest_scheduled = scheduled_values["oldest_ready"]
+ SCHEDULED_TASK_RUN_OLDEST_DUE_AGE_SECONDS.set(
+ max(0.0, (now - oldest_scheduled).total_seconds()) if oldest_scheduled else 0
+ )
+
def dispatch_exceeded_max_age(
dispatch: TaskWorkflowDispatch, max_age_seconds: int, *, now: datetime | None = None
diff --git a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
index ec1ef3ef0a65..e0027c0d13d2 100644
--- a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
+++ b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
@@ -31,6 +31,7 @@ from products.tasks.backend.logic.services.workflow_dispatch import (
dispatch_exceeded_max_age,
mark_accepted,
mark_dead,
+ materialize_due_scheduled_task_runs,
parse_create_payload,
parse_restart_payload,
release_claims,
@@ -50,6 +51,7 @@ from products.tasks.backend.temporal.client import _capture_run_feature_flags
from products.tasks.backend.temporal.process_task.workflow import ProcessTaskInput
logger = logging.getLogger(__name__)
+SCHEDULED_RUN_MATERIALIZATION_BATCH_SIZE = 500
def _user_can_dispatch(run: TaskRun, options: WorkflowDispatchOptions | None) -> bool:
@@ -101,6 +103,7 @@ class Command(BaseCommand):
while not stop.is_set():
Path("/tmp/dispatcher-heartbeat").touch()
try:
+ await sync_to_async(materialize_due_scheduled_task_runs)(SCHEDULED_RUN_MATERIALIZATION_BATCH_SIZE)
if monotonic() - last_metrics_sample >= 15:
await sync_to_async(sample_dispatch_metrics)()
last_metrics_sample = monotonic()
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 3ba1b80314b6..40d003e8b9bf 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -119,6 +119,19 @@ WORKFLOW_DISPATCH_DEAD_TOTAL = Counter(
WORKFLOW_DISPATCH_MISSING_INTENT_TOTAL = Counter(
"posthog_tasks_workflow_dispatch_missing_intent_total", "Queued cloud task runs without dispatch intent"
)
+SCHEDULED_TASK_RUN_MATERIALIZATION_TOTAL = Counter(
+ "posthog_tasks_scheduled_task_run_materialization_total",
+ "Scheduled task runs processed by the due-run materializer",
+ labelnames=["outcome"],
+)
+SCHEDULED_TASK_RUN_DUE = Gauge(
+ "posthog_tasks_scheduled_task_run_due",
+ "Scheduled task runs whose requested start time has passed",
+)
+SCHEDULED_TASK_RUN_OLDEST_DUE_AGE_SECONDS = Gauge(
+ "posthog_tasks_scheduled_task_run_oldest_due_age_seconds",
+ "Age of the oldest due scheduled task run",
+)
AGENT_OTEL_TELEMETRY_STAMPED_TOTAL = Counter(
"posthog_tasks_agent_otel_telemetry_stamped_total",
diff --git a/products/tasks/backend/migrations/0125_taskrun_scheduled_at.py b/products/tasks/backend/migrations/0125_taskrun_scheduled_at.py
new file mode 100644
index 000000000000..721ea57e0ac5
--- /dev/null
+++ b/products/tasks/backend/migrations/0125_taskrun_scheduled_at.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tasks", "0124_drop_retired_code_home_tables"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="taskrun",
+ name="scheduled_at",
+ field=models.DateTimeField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/0126_taskrun_scheduled_due_idx.py b/products/tasks/backend/migrations/0126_taskrun_scheduled_due_idx.py
new file mode 100644
index 000000000000..924f0723f064
--- /dev/null
+++ b/products/tasks/backend/migrations/0126_taskrun_scheduled_due_idx.py
@@ -0,0 +1,22 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0125_taskrun_scheduled_at"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="taskrun",
+ index=models.Index(
+ fields=["scheduled_at", "id"],
+ name="task_run_scheduled_due_idx",
+ condition=models.Q(status="not_started", environment="cloud", scheduled_at__isnull=False),
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/0127_add_twd_pending_due_order_idx.py b/products/tasks/backend/migrations/0127_add_twd_pending_due_order_idx.py
new file mode 100644
index 000000000000..39681fce2a23
--- /dev/null
+++ b/products/tasks/backend/migrations/0127_add_twd_pending_due_order_idx.py
@@ -0,0 +1,22 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0126_taskrun_scheduled_due_idx"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="taskworkflowdispatch",
+ index=models.Index(
+ fields=["next_attempt_at", "created_at"],
+ name="twd_pending_due_order",
+ condition=models.Q(status="pending"),
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/0128_add_twd_claimed_lease_order_idx.py b/products/tasks/backend/migrations/0128_add_twd_claimed_lease_order_idx.py
new file mode 100644
index 000000000000..83e99173384e
--- /dev/null
+++ b/products/tasks/backend/migrations/0128_add_twd_claimed_lease_order_idx.py
@@ -0,0 +1,22 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0127_add_twd_pending_due_order_idx"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="taskworkflowdispatch",
+ index=models.Index(
+ fields=["lease_expires_at", "next_attempt_at", "created_at"],
+ name="twd_claimed_lease_order",
+ condition=models.Q(status="claimed"),
+ ),
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/0129_remove_twd_pending_due_idx.py b/products/tasks/backend/migrations/0129_remove_twd_pending_due_idx.py
new file mode 100644
index 000000000000..ec906c2bf47b
--- /dev/null
+++ b/products/tasks/backend/migrations/0129_remove_twd_pending_due_idx.py
@@ -0,0 +1,18 @@
+from django.db import migrations
+
+from posthog.migration_helpers import SafeRemoveIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0128_add_twd_claimed_lease_order_idx"),
+ ]
+
+ operations = [
+ SafeRemoveIndexConcurrently(
+ model_name="taskworkflowdispatch",
+ name="twd_pending_due",
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/0130_remove_twd_claimed_lease_idx.py b/products/tasks/backend/migrations/0130_remove_twd_claimed_lease_idx.py
new file mode 100644
index 000000000000..9de4436a9b49
--- /dev/null
+++ b/products/tasks/backend/migrations/0130_remove_twd_claimed_lease_idx.py
@@ -0,0 +1,18 @@
+from django.db import migrations
+
+from posthog.migration_helpers import SafeRemoveIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("tasks", "0129_remove_twd_pending_due_idx"),
+ ]
+
+ operations = [
+ SafeRemoveIndexConcurrently(
+ model_name="taskworkflowdispatch",
+ name="twd_claimed_lease",
+ ),
+ ]
diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txt
index 1d9310d5e057..2f655a92bb54 100644
--- a/products/tasks/backend/migrations/max_migration.txt
+++ b/products/tasks/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0124_drop_retired_code_home_tables
+0130_remove_twd_claimed_lease_idx
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index a9050a7b0f91..0f75ef96828b 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -749,7 +749,11 @@ class Task(DeletedMetaFields, models.Model):
extra_state: dict | None = None,
branch: str | None = None,
acting_user_id: int | None = None,
+ scheduled_at: datetime | None = None,
) -> "TaskRun":
+ if scheduled_at is not None and django_timezone.is_naive(scheduled_at):
+ raise ValueError("scheduled_at must be timezone-aware")
+
expected_created_by_id = self.created_by_id
expected_ownership_version = self.ownership_version
dedicated_stream = (extra_state or {}).get("use_dedicated_stream")
@@ -827,8 +831,9 @@ class Task(DeletedMetaFields, models.Model):
task_run = TaskRun.objects.create(
task=task,
team=task.team,
- status=TaskRun.Status.QUEUED,
- queued_at=django_timezone.now(),
+ status=TaskRun.Status.NOT_STARTED if scheduled_at is not None else TaskRun.Status.QUEUED,
+ queued_at=None if scheduled_at is not None else django_timezone.now(),
+ scheduled_at=scheduled_at,
**({"environment": environment} if environment else {}),
state=state,
branch=branch,
@@ -906,12 +911,40 @@ class Task(DeletedMetaFields, models.Model):
self.state = state
def soft_delete(self, capture_fn: Callable[..., None] | None = None):
- self.deleted = True
- self.deleted_at = django_timezone.now()
- self.save()
+ deleted_at = django_timezone.now()
+ with transaction.atomic():
+ scheduled_run_ids = list(
+ TaskRun.objects.select_for_update()
+ .filter(
+ task_id=self.id,
+ scheduled_at__isnull=False,
+ status__in=[TaskRun.Status.NOT_STARTED, TaskRun.Status.QUEUED],
+ )
+ .values_list("id", flat=True)
+ )
+ if scheduled_run_ids:
+ TaskWorkflowDispatch.objects.unscoped().filter(
+ task_run_id__in=scheduled_run_ids,
+ status__in=[TaskWorkflowDispatch.Status.PENDING, TaskWorkflowDispatch.Status.CLAIMED],
+ ).update(
+ status=TaskWorkflowDispatch.Status.DEAD,
+ last_error="Task deleted before the scheduled run started",
+ claimed_by="",
+ lease_expires_at=None,
+ updated_at=deleted_at,
+ )
+ TaskRun.objects.filter(id__in=scheduled_run_ids).update(
+ status=TaskRun.Status.CANCELLED,
+ completed_at=deleted_at,
+ error_message="This scheduled run was canceled because the task was deleted.",
+ updated_at=deleted_at,
+ )
+ self.deleted = True
+ self.deleted_at = deleted_at
+ self.save(update_fields=["deleted", "deleted_at", "updated_at"])
self.capture_event(
"task_deleted",
- {"duration_seconds": round((django_timezone.now() - self.created_at).total_seconds(), 1)},
+ {"duration_seconds": round((deleted_at - self.created_at).total_seconds(), 1)},
capture_fn=capture_fn,
)
@@ -1340,6 +1373,7 @@ class Task(DeletedMetaFields, models.Model):
self_driving_head_branch: str | None = None,
pending_user_message: str | None = None,
workflow_id_prefix: str | None = None,
+ scheduled_at: datetime | None = None,
custom_image_builder_id: str | None = None,
custom_image_id: str | None = None,
github_read_access: bool = False,
@@ -1419,10 +1453,14 @@ class Task(DeletedMetaFields, models.Model):
with transaction.atomic():
task_run = task.create_run(
- mode=mode, extra_state=run_extra_state or None, branch=branch, acting_user_id=user_id
+ mode=mode,
+ extra_state=run_extra_state or None,
+ branch=branch,
+ acting_user_id=user_id,
+ scheduled_at=scheduled_at,
)
- if start_workflow:
+ if start_workflow and scheduled_at is None:
# Defer the fire-and-forget workflow start until the creating transaction commits.
# Otherwise, when create_and_run runs inside a transaction.atomic() block, the
# workflow's first activity can read the TaskRun before its row is visible and fail.
@@ -2268,6 +2306,9 @@ class TaskRun(models.Model):
# 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)
+ # The requested start time for a deferred run. It remains populated after dispatch so the
+ # actual queue/start timestamps can be compared with the requested time.
+ scheduled_at = models.DateTimeField(null=True, blank=True)
class Meta:
db_table = "posthog_task_run"
@@ -2325,6 +2366,11 @@ class TaskRun(models.Model):
fields=["status", "environment", "origin_product"],
name="task_run_status_env_origin_idx",
),
+ models.Index(
+ fields=["scheduled_at", "id"],
+ name="task_run_scheduled_due_idx",
+ condition=models.Q(status="not_started", environment="cloud", scheduled_at__isnull=False),
+ ),
# Terminal rows dominate over time, so the recency range must lead this partial index.
models.Index(
fields=["updated_at"],
@@ -3227,8 +3273,16 @@ class TaskWorkflowDispatch(TeamScopedRootMixin):
),
]
indexes = [
- models.Index(fields=["next_attempt_at"], condition=models.Q(status="pending"), name="twd_pending_due"),
- models.Index(fields=["lease_expires_at"], condition=models.Q(status="claimed"), name="twd_claimed_lease"),
+ models.Index(
+ fields=["next_attempt_at", "created_at"],
+ condition=models.Q(status="pending"),
+ name="twd_pending_due_order",
+ ),
+ models.Index(
+ fields=["lease_expires_at", "next_attempt_at", "created_at"],
+ condition=models.Q(status="claimed"),
+ name="twd_claimed_lease_order",
+ ),
models.Index(fields=["team", "created_at"], name="twd_team_created"),
]
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 825b839fd6e7..da781ba34a78 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -1832,6 +1832,15 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
TaskRunErrorResponseSerializer({"error": "Only cloud runs can be started via this endpoint"}).data,
status=status.HTTP_400_BAD_REQUEST,
)
+ if startable == "scheduled":
+ return Response(
+ TaskRunErrorResponseSerializer(
+ {
+ "error": "This run is scheduled to start automatically. Wait for it to start, or create a new run."
+ }
+ ).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
if startable.startswith("bad_status:"):
current_status = startable.split(":", 1)[1]
return Response(
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 90ebf197438c..5966e393d886 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -4055,6 +4055,23 @@ class TestTaskAPI(BaseTaskAPITest):
)
mock_workflow.assert_not_called()
+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
+ def test_start_run_endpoint_rejects_scheduled_run(self, mock_workflow):
+ task = self.create_task()
+ task_run = task.create_run(
+ environment=TaskRun.Environment.CLOUD,
+ scheduled_at=django_timezone.now() + timedelta(days=1),
+ )
+
+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/runs/{task_run.id}/start/")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(
+ response.json(),
+ {"error": "This run is scheduled to start automatically. Wait for it to start, or create a new run."},
+ )
+ mock_workflow.assert_not_called()
+
@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")
def test_start_run_endpoint_rolls_back_pending_state_when_workflow_trigger_fails(self, mock_workflow):
mock_workflow.side_effect = RuntimeError("workflow start failed")
diff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.py
index 19b27fb05a77..b4c06a924b69 100644
--- a/products/tasks/backend/tests/test_workflow_dispatch.py
+++ b/products/tasks/backend/tests/test_workflow_dispatch.py
@@ -29,10 +29,12 @@ from products.tasks.backend.logic.services.workflow_dispatch import (
WorkflowDispatchOptions,
build_create_payload,
build_restart_payload,
+ claim_dispatches,
create_dispatch,
dispatch_exceeded_max_age,
dispatch_task_processing_workflow,
mark_dead,
+ materialize_due_scheduled_task_runs,
parse_create_payload,
parse_restart_payload,
reschedule,
@@ -251,6 +253,46 @@ class TestWorkflowDispatchPersistence(TestCase):
set_oldest_age.assert_called_once_with(300.0)
+ def test_claims_expired_leases_before_pending_work_and_fills_the_batch(self) -> None:
+ now = django_timezone.now()
+ pending_runs = [
+ TaskRun.objects.create(task=self.task_run.task, team=self.team, status=TaskRun.Status.QUEUED)
+ for _ in range(2)
+ ]
+ pending = [
+ TaskWorkflowDispatch.objects.for_team(self.team.id).create(
+ team=self.team,
+ task_run=run,
+ workflow_id=run.workflow_id,
+ dispatch_kind=TaskWorkflowDispatch.Kind.CREATE,
+ payload={"version": 1},
+ status=TaskWorkflowDispatch.Status.PENDING,
+ next_attempt_at=now - timedelta(minutes=minutes),
+ )
+ for run, minutes in zip(pending_runs, (2, 1), strict=True)
+ ]
+ expired = TaskWorkflowDispatch.objects.for_team(self.team.id).create(
+ team=self.team,
+ task_run=self.task_run,
+ workflow_id=self.task_run.workflow_id,
+ dispatch_kind=TaskWorkflowDispatch.Kind.CREATE,
+ payload={"version": 1},
+ status=TaskWorkflowDispatch.Status.CLAIMED,
+ claimed_by="dead-dispatcher",
+ next_attempt_at=now - timedelta(minutes=1),
+ lease_expires_at=now - timedelta(seconds=1),
+ )
+
+ with patch("products.tasks.backend.logic.services.workflow_dispatch.django_timezone.now", return_value=now):
+ claimed = claim_dispatches("live-dispatcher", 2, timedelta(minutes=1))
+
+ self.assertEqual([row.id for row in claimed], [expired.id, pending[0].id])
+ self.assertTrue(all(row.status == TaskWorkflowDispatch.Status.CLAIMED for row in claimed))
+ self.assertTrue(all(row.claimed_by == "live-dispatcher" for row in claimed))
+ self.assertTrue(all(row.attempt_count == 1 for row in claimed))
+ pending[1].refresh_from_db()
+ self.assertEqual(pending[1].status, TaskWorkflowDispatch.Status.PENDING)
+
@patch("products.tasks.backend.metrics.WORKFLOW_DISPATCH_MISSING_INTENT_TOTAL.inc")
@patch("products.tasks.backend.facade.api.is_workflow_dispatch_shadow_enabled", return_value=False)
def test_missing_intent_metric_stays_quiet_before_shadow_rollout(
@@ -296,6 +338,293 @@ class TestWorkflowDispatchPersistence(TestCase):
self.assertFalse(marker["create_pr"])
self.assertEqual(marker["posthog_mcp_scopes"], "full")
+ @patch("products.tasks.backend.logic.services.workflow_dispatch.enqueue_or_start_workflow")
+ def test_scheduled_create_persists_full_run_without_dispatching_early(self, enqueue: Mock) -> None:
+ creator_id = self.task_run.task.created_by_id
+ assert creator_id is not None
+ scheduled_at = django_timezone.now() + timedelta(days=1)
+
+ created = create_and_run_task(
+ team=self.team,
+ title="Scheduled follow-up",
+ description="Review the report after more data arrives",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ user_id=creator_id,
+ create_pr=False,
+ scheduled_at=scheduled_at,
+ runtime_adapter="codex",
+ model="gpt-5.6-terra",
+ reasoning_effort="high",
+ pending_user_message="Revisit the report",
+ )
+
+ assert created.latest_run is not None
+ run = TaskRun.objects.get(id=created.latest_run.id)
+ self.assertEqual(run.status, TaskRun.Status.NOT_STARTED)
+ self.assertEqual(run.scheduled_at, scheduled_at)
+ self.assertIsNone(run.queued_at)
+ self.assertEqual(run.state["runtime_adapter"], "codex")
+ self.assertEqual(run.state["model"], "gpt-5.6-terra")
+ self.assertEqual(run.state["reasoning_effort"], "high")
+ self.assertEqual(run.state["pending_user_message"], "Revisit the report")
+ self.assertFalse(TaskWorkflowDispatch.objects.unscoped().filter(task_run=run).exists())
+ enqueue.assert_not_called()
+
+ def test_due_materializer_leaves_future_runs_dormant(self) -> None:
+ now = django_timezone.now()
+ state = {
+ "pending_dispatch": {
+ "user_id": self.task_run.task.created_by_id,
+ "create_pr": False,
+ "posthog_mcp_scopes": "full",
+ "slack_thread_context": None,
+ "workflow_id_prefix": "scheduled",
+ }
+ }
+ due = TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now - timedelta(minutes=1),
+ state=state,
+ )
+ future = TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now + timedelta(minutes=1),
+ state=state,
+ )
+ local = TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ environment=TaskRun.Environment.LOCAL,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now - timedelta(minutes=1),
+ state=state,
+ )
+
+ self.assertEqual(materialize_due_scheduled_task_runs(100), 1)
+
+ due.refresh_from_db()
+ future.refresh_from_db()
+ local.refresh_from_db()
+ dispatch = TaskWorkflowDispatch.objects.unscoped().get(task_run=due)
+ self.assertEqual(due.status, TaskRun.Status.QUEUED)
+ self.assertIsNotNone(due.queued_at)
+ self.assertEqual(dispatch.payload["create_pr"], False)
+ self.assertEqual(dispatch.payload["posthog_mcp_scopes"], "full")
+ self.assertEqual(dispatch.workflow_id, f"scheduled-{due.task_id}-{due.id}")
+ self.assertEqual(due.workflow_id, dispatch.workflow_id)
+ self.assertEqual(future.status, TaskRun.Status.NOT_STARTED)
+ self.assertFalse(TaskWorkflowDispatch.objects.unscoped().filter(task_run=future).exists())
+ self.assertEqual(local.status, TaskRun.Status.NOT_STARTED)
+ self.assertFalse(TaskWorkflowDispatch.objects.unscoped().filter(task_run=local).exists())
+
+ def test_due_materializer_pages_in_schedule_order_without_duplicates(self) -> None:
+ now = django_timezone.now()
+ state = {
+ "pending_dispatch": {
+ "user_id": self.task_run.task.created_by_id,
+ "create_pr": True,
+ "posthog_mcp_scopes": "read_only",
+ }
+ }
+ runs = [
+ TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now - timedelta(minutes=minutes),
+ state=state,
+ )
+ for minutes in (3, 2, 1)
+ ]
+
+ self.assertEqual(materialize_due_scheduled_task_runs(2), 2)
+ self.assertEqual(
+ set(TaskRun.objects.filter(status=TaskRun.Status.QUEUED).values_list("id", flat=True)),
+ {self.task_run.id, runs[0].id, runs[1].id},
+ )
+ self.assertEqual(materialize_due_scheduled_task_runs(2), 1)
+ self.assertEqual(materialize_due_scheduled_task_runs(2), 0)
+ self.assertEqual(
+ TaskWorkflowDispatch.objects.unscoped()
+ .filter(task_run_id__in=[run.id for run in runs], dispatch_kind=TaskWorkflowDispatch.Kind.CREATE)
+ .count(),
+ 3,
+ )
+
+ def test_invalid_due_run_does_not_block_later_scheduled_work(self) -> None:
+ now = django_timezone.now()
+ invalid_runs = [
+ TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now - timedelta(minutes=minutes),
+ state=state,
+ )
+ for minutes, state in [
+ (4, {}),
+ (3, {"pending_dispatch": {}}),
+ (
+ 2,
+ {
+ "pending_dispatch": {
+ "user_id": self.task_run.task.created_by_id,
+ "create_pr": False,
+ "posthog_mcp_scopes": "full",
+ "workflow_id_prefix": "x" * 500,
+ }
+ },
+ ),
+ ]
+ ]
+ valid = TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now - timedelta(minutes=1),
+ state={
+ "pending_dispatch": {
+ "user_id": self.task_run.task.created_by_id,
+ "create_pr": False,
+ "posthog_mcp_scopes": "full",
+ }
+ },
+ )
+
+ self.assertEqual(materialize_due_scheduled_task_runs(4), 1)
+
+ valid.refresh_from_db()
+ for invalid in invalid_runs:
+ invalid.refresh_from_db()
+ self.assertEqual(invalid.status, TaskRun.Status.FAILED)
+ self.assertIsNotNone(invalid.completed_at)
+ assert invalid.error_message is not None
+ self.assertIn("Create a new scheduled task", invalid.error_message)
+ self.assertEqual(valid.status, TaskRun.Status.QUEUED)
+ self.assertTrue(TaskWorkflowDispatch.objects.unscoped().filter(task_run=valid).exists())
+
+ def test_existing_dispatch_does_not_block_scheduled_batch(self) -> None:
+ now = django_timezone.now()
+ state = {
+ "pending_dispatch": {
+ "user_id": self.task_run.task.created_by_id,
+ "create_pr": False,
+ "posthog_mcp_scopes": "full",
+ }
+ }
+ runs = [
+ TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now - timedelta(minutes=minutes),
+ state=state,
+ )
+ for minutes in (2, 1)
+ ]
+ TaskWorkflowDispatch.objects.for_team(self.team.id).create(
+ team=self.team,
+ task_run=runs[0],
+ workflow_id=runs[0].workflow_id,
+ dispatch_kind=TaskWorkflowDispatch.Kind.CREATE,
+ payload=build_create_payload(
+ WorkflowDispatchOptions(
+ user_id=self.task_run.task.created_by_id,
+ create_pr=False,
+ posthog_mcp_scopes="full",
+ )
+ ),
+ )
+
+ self.assertEqual(materialize_due_scheduled_task_runs(2), 2)
+
+ self.assertEqual(
+ set(
+ TaskRun.objects.filter(id__in=[run.id for run in runs], status=TaskRun.Status.QUEUED).values_list(
+ "id", flat=True
+ )
+ ),
+ {run.id for run in runs},
+ )
+ self.assertEqual(
+ TaskWorkflowDispatch.objects.unscoped()
+ .filter(task_run_id__in=[run.id for run in runs], dispatch_kind=TaskWorkflowDispatch.Kind.CREATE)
+ .count(),
+ 2,
+ )
+
+ def test_scheduled_dispatch_uses_canonical_team(self) -> None:
+ child_team = Team.objects.create(
+ organization=self.team.organization,
+ name="Child environment",
+ parent_team=self.team,
+ )
+ task = Task.objects.create(
+ team=child_team,
+ created_by=self.task_run.task.created_by,
+ title="Child task",
+ description="Child task",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ )
+ run = TaskRun.objects.create(
+ task=task,
+ team=child_team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=django_timezone.now() - timedelta(minutes=1),
+ state={
+ "pending_dispatch": {
+ "user_id": self.task_run.task.created_by_id,
+ "create_pr": False,
+ "posthog_mcp_scopes": "full",
+ }
+ },
+ )
+
+ self.assertEqual(materialize_due_scheduled_task_runs(1), 1)
+
+ dispatch = TaskWorkflowDispatch.objects.unscoped().get(task_run=run)
+ self.assertEqual(dispatch.team_id, self.team.id)
+ self.assertEqual(TaskWorkflowDispatch.objects.for_team(child_team.id).get(task_run=run), dispatch)
+
+ def test_deleting_task_cancels_scheduled_runs(self) -> None:
+ now = django_timezone.now()
+ state = {
+ "pending_dispatch": {
+ "user_id": self.task_run.task.created_by_id,
+ "create_pr": False,
+ "posthog_mcp_scopes": "full",
+ }
+ }
+ due = TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now - timedelta(minutes=1),
+ state=state,
+ )
+ future = TaskRun.objects.create(
+ task=self.task_run.task,
+ team=self.team,
+ status=TaskRun.Status.NOT_STARTED,
+ scheduled_at=now + timedelta(days=1),
+ state=state,
+ )
+ self.assertEqual(materialize_due_scheduled_task_runs(1), 1)
+
+ due.task.soft_delete()
+
+ due.refresh_from_db()
+ future.refresh_from_db()
+ dispatch = TaskWorkflowDispatch.objects.unscoped().get(task_run=due)
+ self.assertEqual(due.status, TaskRun.Status.CANCELLED)
+ self.assertEqual(future.status, TaskRun.Status.CANCELLED)
+ self.assertEqual(dispatch.status, TaskWorkflowDispatch.Status.DEAD)
+ self.assertEqual(materialize_due_scheduled_task_runs(10), 0)
+
@parameterized.expand(
[
("already_started_keeps_run_alive", WorkflowAlreadyStartedError("wf", "process-task"), False, "queued"),