: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
feat(tasks): dispatch workflow restarts through outbox (#83085)
Alessandro Pogliaghica294c049ef8
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 100822a80dab..eaabe56033af 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -340,8 +340,13 @@ def redispatch_orphaned_queued_task_runs() -> None:# 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, environment=tasks_facade.TaskRunEnvironment.CLOUD+ RECONCILE_AFTER,+ BATCH_SIZE,+ environment=tasks_facade.TaskRunEnvironment.CLOUD,+ exclude_covered_dispatches=True,)+ saturated = len(candidate_ids) >= BATCH_SIZE+ candidate_ids = tasks_facade.filter_uncovered_workflow_dispatch_run_ids(candidate_ids)outcomes: dict[str, int] = {}for run_id in candidate_ids:try:@@ -352,7 +357,6 @@ def redispatch_orphaned_queued_task_runs() -> None:outcomes[outcome] = outcomes.get(outcome, 0) + 1ORPHANED_QUEUED_TASK_RUN_RECONCILED_COUNTER.labels(outcome=outcome).inc()- saturated = len(candidate_ids) >= BATCH_SIZElog = logger.warning if saturated else logger.infolog("redispatch_orphaned_queued_task_runs.sweep_done",@@ -366,6 +370,8 @@ def redispatch_orphaned_queued_task_runs() -> None:saturated=saturated,)+ tasks_facade.maintain_workflow_dispatch_outbox()+@shared_task(ignore_result=True)@skip_team_scope_auditdiff --git a/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py b/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.pyindex 59c032c1797b..5a7c03fddfc5 100644--- a/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py+++ b/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py@@ -79,6 +79,25 @@ class TestRedispatchOrphanedQueuedTaskRuns(TestCase):mock_redispatch.assert_called_once_with(cloud_run.id)+ def test_covered_runs_do_not_crowd_orphans_out_of_the_batch(self) -> None:+ TaskWorkflowDispatch = apps.get_model("tasks", "TaskWorkflowDispatch")+ covered = self._queued_run(datetime.timedelta(days=1))+ orphan = self._queued_run(datetime.timedelta(minutes=10))+ TaskWorkflowDispatch.objects.for_team(self.team.id).create(+ team=self.team,+ task_run=covered,+ workflow_id=f"task-{covered.id}",+ dispatch_kind=TaskWorkflowDispatch.Kind.CREATE,+ status=TaskWorkflowDispatch.Status.PENDING,+ )++ with patch(+ "products.tasks.backend.facade.api.redispatch_task_run", return_value="recovered"+ ) as mock_redispatch:+ redispatch_orphaned_queued_task_runs()++ mock_redispatch.assert_called_once_with(orphan.id)+def test_one_failure_does_not_block_the_sweep(self) -> None:self._queued_run(datetime.timedelta(minutes=10))self._queued_run(datetime.timedelta(minutes=11))diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex e6b3d0d131f0..101b8449c2ec 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -72,7 +72,7 @@ from products.tasks.backend.constants import (is_blocked_sandbox_env_key,)from products.tasks.backend.error_telemetry import truncate_error_message-from products.tasks.backend.feature_flags import get_model_access_error+from products.tasks.backend.feature_flags import get_model_access_error, is_workflow_dispatch_shadow_enabledfrom products.tasks.backend.github_repository_access import (inaccessible_repositories_via_integration as _inaccessible_repositories_via_integration,)@@ -110,6 +110,7 @@ from products.tasks.backend.models import (TaskSession,TaskThreadMessage,TaskThreadMessageMention,+ TaskWorkflowDispatch,)from products.tasks.backend.pr_urls import merge_pr_outputfrom products.tasks.backend.prompts import build_wizard_pr_agent_prompt, generate_wizard_head_branch@@ -209,6 +210,8 @@ __all__ = ["get_stale_prewarmed_queued_task_run_ids","get_stale_terminal_prewarmed_task_run_ids","get_stale_queued_task_run_ids",+ "filter_uncovered_workflow_dispatch_run_ids",+ "maintain_workflow_dispatch_outbox","get_task_detail","get_task_id_for_run","get_task_run",@@ -1012,6 +1015,7 @@ def get_stale_queued_task_run_ids(created_hard_cap: timedelta | None = None,hard_cap_min_queued: timedelta = timedelta(hours=1),environment: str | None = None,+ exclude_covered_dispatches: bool = False,) -> list[UUID]:"""Ids of runs stuck in QUEUED, by ``updated_at`` age or an optional ``created_at`` backstop.@@ -1031,9 +1035,84 @@ def get_stale_queued_task_run_ids(queryset = TaskRun.objects.filter(status=TaskRun.Status.QUEUED) # nosemgrep: celery-task-team-scope-auditif environment is not None:queryset = queryset.filter(environment=environment)+ if exclude_covered_dispatches:+ queryset = queryset.exclude(+ workflow_dispatches__status__in=(TaskWorkflowDispatch.Status.PENDING, TaskWorkflowDispatch.Status.CLAIMED)+ )+ elif environment == TaskRun.Environment.CLOUD:+ queryset = queryset.exclude(+ workflow_dispatches__status__in=("pending", "claimed"),+ workflow_dispatches__enqueued_at__gte=now+ - timedelta(seconds=settings.TASKS_DISPATCHER_MAX_DISPATCH_AGE_SECONDS),+ )return list(queryset.filter(stale).order_by("updated_at").values_list("id", flat=True)[:limit])+def filter_uncovered_workflow_dispatch_run_ids(candidate_ids: list[UUID]) -> list[UUID]:+ from products.tasks.backend.metrics import WORKFLOW_DISPATCH_MISSING_INTENT_TOTAL # noqa: PLC0415++ live_dispatch_run_ids = set(+ TaskWorkflowDispatch.objects.unscoped()+ .filter(+ task_run_id__in=candidate_ids,+ status__in=(TaskWorkflowDispatch.Status.PENDING, TaskWorkflowDispatch.Status.CLAIMED),+ )+ .values_list("task_run_id", flat=True)+ )+ uncovered_ids = [run_id for run_id in candidate_ids if run_id not in live_dispatch_run_ids]+ if not is_workflow_dispatch_shadow_enabled():+ return uncovered_ids+ runs = {+ run.id: run+ for run in TaskRun.objects.filter(id__in=uncovered_ids) # nosemgrep: celery-task-team-scope-audit+ }+ dispatch_run_ids = set(+ TaskWorkflowDispatch.objects.unscoped()+ .filter(task_run_id__in=uncovered_ids)+ .values_list("task_run_id", flat=True)+ )+ for run_id in uncovered_ids:+ run = runs.get(run_id)+ has_legacy_intent = bool(run and isinstance(run.state, dict) and run.state.get("pending_dispatch"))+ if run_id not in dispatch_run_ids and not has_legacy_intent:+ WORKFLOW_DISPATCH_MISSING_INTENT_TOTAL.inc()+ return uncovered_ids+++def maintain_workflow_dispatch_outbox() -> None:+ now = django_timezone.now()+ TaskWorkflowDispatch.objects.unscoped().filter(+ status=TaskWorkflowDispatch.Status.PENDING,+ ).exclude(task_run__status=TaskRun.Status.QUEUED).update(+ status=TaskWorkflowDispatch.Status.ACCEPTED,+ accepted_at=now,+ last_error="resolved: run left QUEUED",+ )+ TaskWorkflowDispatch.objects.unscoped().filter(+ status=TaskWorkflowDispatch.Status.CLAIMED,+ lease_expires_at__lt=now - timedelta(minutes=10),+ ).update(+ status=TaskWorkflowDispatch.Status.PENDING,+ claimed_by="",+ lease_expires_at=None,+ next_attempt_at=now,+ )+ accepted_ids = list(+ TaskWorkflowDispatch.objects.unscoped()+ .filter(status=TaskWorkflowDispatch.Status.ACCEPTED, accepted_at__lt=now - timedelta(days=14))+ .order_by("accepted_at")+ .values_list("id", flat=True)[:1000]+ )+ TaskWorkflowDispatch.objects.unscoped().filter(id__in=accepted_ids).delete()+ dead_ids = list(+ TaskWorkflowDispatch.objects.unscoped()+ .filter(status=TaskWorkflowDispatch.Status.DEAD, updated_at__lt=now - timedelta(days=30))+ .order_by("updated_at")+ .values_list("id", flat=True)[:1000]+ )+ TaskWorkflowDispatch.objects.unscoped().filter(id__in=dead_ids).delete()++def get_stale_prewarmed_queued_task_run_ids(older_than: timedelta, limit: int) -> list[UUID]:"""Ids of prewarmed runs orphaned in QUEUED — their processing workflow never started, so thein-workflow ``WARM_IDLE_TIMEOUT`` (10m) never armed to finalize them.@@ -4118,6 +4197,19 @@ def resume_task_run_in_cloud(run = _get_visible_run(run_id, task_id, team_id)if run is None:return "not_found", None, None++ from products.tasks.backend.feature_flags import is_workflow_dispatch_restart_enabled # noqa: PLC0415+ from products.tasks.backend.logic.services.workflow_dispatch import ( # noqa: PLC0415+ RestartSnapshot,+ build_restart_payload,+ create_dispatch,+ )+ from products.tasks.backend.models import TaskWorkflowDispatch # noqa: PLC0415++ distinct_id = run.task.created_by.distinct_id if run.task.created_by else str(run.id)+ restart_dispatch_enabled = is_workflow_dispatch_restart_enabled(+ str(run.task.team.organization_id), distinct_id or str(run.id)+ )logger.info("resume_in_cloud_called",extra={@@ -4170,6 +4262,24 @@ def resume_task_run_in_cloud(prior_state = dict(run.state or {})run.prepare_for_cloud_handoff()+ if restart_dispatch_enabled:+ snapshot = RestartSnapshot(+ status=prior_status,+ environment=prior_environment,+ completed_at=prior_completed_at.isoformat() if prior_completed_at else None,+ queued_at=prior_queued_at.isoformat() if prior_queued_at else None,+ state=prior_state,+ )+ create_dispatch(+ run,+ TaskWorkflowDispatch.Kind.RESTART,+ build_restart_payload(user_id, snapshot),+ run.workflow_id,+ )++ if restart_dispatch_enabled:+ return "resumed", _task_run_detail_to_dto(_task_run_queryset().get(pk=run.pk)), None+logger.info("Resuming task run in cloud", extra={"task_run_id": str(run.id), "task_id": str(run.task_id)})try:diff --git a/products/tasks/backend/logic/services/workflow_dispatch.py b/products/tasks/backend/logic/services/workflow_dispatch.pyindex d488fe110778..20aa203f6e75 100644--- a/products/tasks/backend/logic/services/workflow_dispatch.py+++ b/products/tasks/backend/logic/services/workflow_dispatch.py@@ -14,6 +14,7 @@ from posthog.temporal.oauth import PosthogMcpScopesfrom products.tasks.backend.metrics import (WORKFLOW_DISPATCH_CLAIMED,WORKFLOW_DISPATCH_CREATED_TOTAL,+ WORKFLOW_DISPATCH_DEAD_TOTAL,WORKFLOW_DISPATCH_LEASE_EXPIRED_TOTAL,WORKFLOW_DISPATCH_OLDEST_READY_AGE_SECONDS,WORKFLOW_DISPATCH_READY,@@ -97,12 +98,12 @@ def create_dispatch(task_run: TaskRun, kind: str, payload: dict[str, Any], workf"payload": payload,"status": TaskWorkflowDispatch.Status.PENDING,"attempt_count": 0,- "enqueued_at": django_timezone.now(),"next_attempt_at": django_timezone.now(),"claimed_by": "","lease_expires_at": None,"accepted_at": None,"last_error": "",+ "enqueued_at": django_timezone.now(),}queryset = TaskWorkflowDispatch.objects.for_team(task_run.team_id)if kind == TaskWorkflowDispatch.Kind.RESTART:@@ -144,10 +145,16 @@ def claim_dispatches(instance_id: str, batch_size: int, lease: timedelta) -> lisdef sample_dispatch_metrics() -> None:now = django_timezone.now()- values = TaskWorkflowDispatch.objects.unscoped().aggregate(- ready=Count("id", filter=Q(status=TaskWorkflowDispatch.Status.PENDING, next_attempt_at__lte=now)),- claimed=Count("id", filter=Q(status=TaskWorkflowDispatch.Status.CLAIMED)),- oldest_ready=Min("created_at", filter=Q(status=TaskWorkflowDispatch.Status.PENDING, next_attempt_at__lte=now)),+ values = (+ TaskWorkflowDispatch.objects.unscoped()+ .filter(status__in=[TaskWorkflowDispatch.Status.PENDING, TaskWorkflowDispatch.Status.CLAIMED])+ .aggregate(+ ready=Count("id", filter=Q(status=TaskWorkflowDispatch.Status.PENDING, next_attempt_at__lte=now)),+ claimed=Count("id", filter=Q(status=TaskWorkflowDispatch.Status.CLAIMED)),+ oldest_ready=Min(+ "enqueued_at", filter=Q(status=TaskWorkflowDispatch.Status.PENDING, next_attempt_at__lte=now)+ ),+ ))WORKFLOW_DISPATCH_READY.set(values["ready"] or 0)WORKFLOW_DISPATCH_CLAIMED.set(values["claimed"] or 0)@@ -155,6 +162,13 @@ def sample_dispatch_metrics() -> None:WORKFLOW_DISPATCH_OLDEST_READY_AGE_SECONDS.set(max(0.0, (now - oldest).total_seconds()) if oldest else 0)+def dispatch_exceeded_max_age(+ dispatch: TaskWorkflowDispatch, max_age_seconds: int, *, now: datetime | None = None+) -> bool:+ current_time = now or django_timezone.now()+ return current_time - dispatch.enqueued_at > timedelta(seconds=max_age_seconds)++def renew_leases(instance_id: str, dispatch_ids: list[Any], lease: timedelta) -> int:return (TaskWorkflowDispatch.objects.unscoped()@@ -200,7 +214,7 @@ def release_claims(instance_id: str) -> int:)-def mark_dead(dispatch_id: Any, instance_id: str, error: str) -> int:+def mark_dead(dispatch_id: Any, instance_id: str, error: str, reason: str = "payload") -> int:with transaction.atomic():dispatch = (TaskWorkflowDispatch.objects.unscoped().select_for_update().select_related("task_run").get(id=dispatch_id)@@ -212,9 +226,16 @@ def mark_dead(dispatch_id: Any, instance_id: str, error: str) -> int:dispatch.claimed_by = ""dispatch.lease_expires_at = Nonedispatch.save(update_fields=["status", "last_error", "claimed_by", "lease_expires_at", "updated_at"])+ WORKFLOW_DISPATCH_DEAD_TOTAL.labels(kind=dispatch.dispatch_kind, reason=reason).inc()run = dispatch.task_runif dispatch.dispatch_kind == TaskWorkflowDispatch.Kind.RESTART:- _, snapshot = parse_restart_payload(dispatch.payload)+ try:+ _, snapshot = parse_restart_payload(dispatch.payload)+ except (KeyError, TypeError, ValueError):+ from products.tasks.backend.temporal.client import _terminalize_unstarted_task_run # noqa: PLC0415++ transaction.on_commit(lambda: _terminalize_unstarted_task_run(str(run.id), error[:2000]))+ return 1run.status = snapshot.statusrun.environment = snapshot.environmentrun.completed_at = datetime.fromisoformat(snapshot.completed_at) if snapshot.completed_at else None@@ -226,7 +247,17 @@ def mark_dead(dispatch_id: Any, instance_id: str, error: str) -> int:execute_after_commit(lambda: _terminalize_unstarted_task_run(str(run.id), error[:2000]))return 1- run.save()+ run.save(+ update_fields=[+ "status",+ "environment",+ "completed_at",+ "queued_at",+ "state",+ "error_message",+ "updated_at",+ ]+ )execute_after_commit(run.publish_stream_state_event)return 1diff --git a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.pyindex 2411dbd68c20..5a08968d96ce 100644--- a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py+++ b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py@@ -11,13 +11,14 @@ from time import monotonicfrom django.conf import settingsfrom django.core.management.base import BaseCommand-from django.utils import timezone as django_timezone+from django.db import DatabaseErrorfrom asgiref.sync import sync_to_asyncfrom prometheus_client import start_http_server-from temporalio.client import Client+from temporalio.client import Client, WorkflowExecutionStatusfrom temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.service import RPCError, RPCStatusCodefrom posthog.models.team.team import Teamfrom posthog.models.user import User@@ -27,9 +28,11 @@ from posthog.user_permissions import UserPermissionsfrom products.tasks.backend.logic.services.workflow_dispatch import (WorkflowDispatchOptions,claim_dispatches,+ dispatch_exceeded_max_age,mark_accepted,mark_dead,parse_create_payload,+ parse_restart_payload,release_claims,renew_leases_in_worker_thread,reschedule,@@ -48,17 +51,30 @@ from products.tasks.backend.temporal.process_task.workflow import ProcessTaskInplogger = logging.getLogger(__name__)-def _user_can_dispatch(run: TaskRun, options: WorkflowDispatchOptions) -> bool:- if options.skip_user_check:+def _user_can_dispatch(run: TaskRun, options: WorkflowDispatchOptions | None) -> bool:+ if options is not None and options.skip_user_check:return True- if options.user_id is None:+ user_id = options.user_id if options is not None else run.task.created_by_id+ if user_id is None:return False- user = User.objects.filter(id=options.user_id, is_active=True).first()+ user = User.objects.filter(id=user_id, is_active=True).first()if user is None:return Falsereturn UserPermissions(user=user, team=run.task.team).current_team.effective_membership_level is not None+async def restart_attempt_already_started(client: Client, dispatch: TaskWorkflowDispatch) -> bool:+ try:+ description = await client.get_workflow_handle(dispatch.workflow_id).describe(+ rpc_timeout=timedelta(seconds=settings.TASKS_DISPATCHER_RPC_TIMEOUT_SECONDS)+ )+ except RPCError as error:+ if error.status == RPCStatusCode.NOT_FOUND:+ return False+ raise+ return description.status == WorkflowExecutionStatus.RUNNING and description.start_time >= dispatch.enqueued_at++class Command(BaseCommand):help = "Dispatch queued task workflows from the durable outbox"@@ -83,16 +99,24 @@ class Command(BaseCommand):try:while not stop.is_set():Path("/tmp/dispatcher-heartbeat").touch()- if monotonic() - last_metrics_sample >= 15:- await sync_to_async(sample_dispatch_metrics)()- last_metrics_sample = monotonic()- available_capacity = settings.TASKS_DISPATCHER_CONCURRENCY - len(in_flight)- if available_capacity <= 0:- await asyncio.wait(in_flight, return_when=asyncio.FIRST_COMPLETED)+ try:+ if monotonic() - last_metrics_sample >= 15:+ await sync_to_async(sample_dispatch_metrics)()+ last_metrics_sample = monotonic()+ available_capacity = settings.TASKS_DISPATCHER_CONCURRENCY - len(in_flight)+ if available_capacity <= 0:+ await asyncio.wait(in_flight, return_when=asyncio.FIRST_COMPLETED)+ continue+ rows = await sync_to_async(claim_dispatches)(+ instance_id, min(settings.TASKS_DISPATCHER_BATCH_SIZE, available_capacity), lease+ )+ except DatabaseError:+ logger.exception("Task workflow dispatcher database poll failed")+ try:+ await asyncio.wait_for(stop.wait(), timeout=settings.TASKS_DISPATCHER_POLL_INTERVAL_SECONDS)+ except TimeoutError:+ passcontinue- rows = await sync_to_async(claim_dispatches)(- instance_id, min(settings.TASKS_DISPATCHER_BATCH_SIZE, available_capacity), lease- )if not rows:try:await asyncio.wait_for(stop.wait(), timeout=settings.TASKS_DISPATCHER_POLL_INTERVAL_SECONDS)@@ -157,44 +181,82 @@ class Command(BaseCommand):await sync_to_async(resolve_ineligible)(dispatch.id, instance_id)WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="resolved_ineligible").inc()return- if django_timezone.now() - dispatch.created_at > timedelta(- seconds=settings.TASKS_DISPATCHER_MAX_DISPATCH_AGE_SECONDS- ):- await sync_to_async(mark_dead)(dispatch.id, instance_id, "Workflow dispatch exceeded maximum age")+ if dispatch_exceeded_max_age(dispatch, settings.TASKS_DISPATCHER_MAX_DISPATCH_AGE_SECONDS):+ await sync_to_async(mark_dead)(+ dispatch.id, instance_id, "Workflow dispatch exceeded maximum age", "max_age"+ )WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()returntry:await Team.objects.aget(id=run.team_id)- options = parse_create_payload(dispatch.payload)+ is_restart = dispatch.dispatch_kind == TaskWorkflowDispatch.Kind.RESTART+ if is_restart:+ requester_id, _ = parse_restart_payload(dispatch.payload)+ options = WorkflowDispatchOptions(user_id=requester_id)+ if dispatch.attempt_count > 1 and await restart_attempt_already_started(client, dispatch):+ await sync_to_async(mark_accepted)(dispatch.id, instance_id)+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(+ kind=dispatch.dispatch_kind, outcome="already_started"+ ).inc()+ return+ else:+ options = parse_create_payload(dispatch.payload)if not await sync_to_async(_user_can_dispatch)(run, options):- await sync_to_async(mark_dead)(dispatch.id, instance_id, "User no longer has team access")+ await sync_to_async(mark_dead)(+ dispatch.id, instance_id, "User no longer has team access", "permission"+ )WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()returnawait sync_to_async(_capture_run_feature_flags, thread_sensitive=False)(str(run.id))+ if is_restart:+ from products.tasks.backend.facade.streams import reset_task_run_stream # noqa: PLC0415+ from products.tasks.backend.redis import run_uses_dedicated_stream # noqa: PLC0415++ reset = await sync_to_async(reset_task_run_stream)(+ str(run.id), use_dedicated=run_uses_dedicated_stream(run.state)+ )+ if not reset:+ raise RuntimeError("Failed to reset task run event stream")workflow_input = ProcessTaskInput(run_id=str(run.id),- create_pr=options.create_pr,- slack_thread_context=options.slack_thread_context,- posthog_mcp_scopes=options.posthog_mcp_scopes,- prewarmed=options.prewarmed,- initial_message=options.initial_message,+ create_pr=options.create_pr if options else True,+ slack_thread_context=options.slack_thread_context if options else None,+ posthog_mcp_scopes=options.posthog_mcp_scopes if options else "read_only",+ prewarmed=options.prewarmed if options else False,+ initial_message=options.initial_message if options else None,)- except (Team.DoesNotExist, ValueError, KeyError, TypeError) as error:- await sync_to_async(mark_dead)(dispatch.id, instance_id, str(error))+ except Team.DoesNotExist as error:+ await sync_to_async(mark_dead)(dispatch.id, instance_id, str(error), "permission")+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()+ return+ except (ValueError, KeyError, TypeError) as error:+ await sync_to_async(mark_dead)(dispatch.id, instance_id, str(error), "payload")WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()return+ except Exception as error:+ await sync_to_async(reschedule)(dispatch.id, instance_id, str(error))+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="rescheduled").inc()+ returnstarted = monotonic()try:await client.start_workflow("process-task",workflow_input,id=dispatch.workflow_id,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ id_reuse_policy=(+ WorkflowIDReusePolicy.TERMINATE_IF_RUNNING+ if is_restart+ else WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY+ ),task_queue=settings.TASKS_TASK_QUEUE,retry_policy=RetryPolicy(maximum_attempts=3),rpc_timeout=timedelta(seconds=settings.TASKS_DISPATCHER_RPC_TIMEOUT_SECONDS),)except WorkflowAlreadyStartedError:+ if is_restart:+ await sync_to_async(reschedule)(dispatch.id, instance_id, "Restart workflow is already running")+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="rescheduled").inc()+ returnawait sync_to_async(mark_accepted)(dispatch.id, instance_id)WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="already_started").inc()except Exception as error:diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 64fb635da621..a5285a5e8e81 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -19,7 +19,14 @@ from products.tasks.backend.facade import (contracts,warm as warm_facade,)-from products.tasks.backend.models import Channel, SandboxCustomImage, SandboxEnvironment, Task, TaskRun+from products.tasks.backend.models import (+ Channel,+ SandboxCustomImage,+ SandboxEnvironment,+ Task,+ TaskRun,+ TaskWorkflowDispatch,+)from products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PLACEHOLDER, build_wizard_pr_agent_promptFACADE_MODULES = [@@ -572,6 +579,39 @@ class TestFacadeReadsAndMappers(TestCase):self.assertIn(ancient.id, hard_capped)self.assertNotIn(resuming.id, hard_capped)+ def test_cloud_sweep_guard_uses_dispatch_enqueue_time(self):+ task = self._make_task()+ now = django_timezone.now()+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.QUEUED,+ environment=TaskRun.Environment.CLOUD,+ )+ TaskRun.objects.filter(pk=run.pk).update(+ created_at=now - timedelta(hours=50), updated_at=now - timedelta(hours=2)+ )+ dispatch = TaskWorkflowDispatch.objects.for_team(self.team.id).create(+ team=self.team,+ task_run=run,+ workflow_id=run.workflow_id,+ dispatch_kind=TaskWorkflowDispatch.Kind.RESTART,+ payload={},+ enqueued_at=now - timedelta(minutes=5),+ )+ TaskWorkflowDispatch.objects.for_team(self.team.id).filter(pk=dispatch.pk).update(+ created_at=now - timedelta(hours=50)+ )++ stale_ids = facade.get_stale_queued_task_run_ids(+ older_than=timedelta(hours=24),+ limit=100,+ created_hard_cap=timedelta(hours=48),+ environment=TaskRun.Environment.CLOUD,+ )++ self.assertNotIn(run.id, stale_ids)+def test_update_task_run_state(self):task = self._make_task()run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED, state={"mode": "bg"})diff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.pyindex ef74fb716e0f..c4604f77ac94 100644--- a/products/tasks/backend/tests/test_workflow_dispatch.py+++ b/products/tasks/backend/tests/test_workflow_dispatch.py@@ -1,21 +1,46 @@import asyncio+from datetime import timedeltafrom typing import cast-from unittest.mock import Mock, patch+from unittest.mock import AsyncMock, Mock, patch-from django.test import SimpleTestCase+from django.conf import settings+from django.db import transaction+from django.test import SimpleTestCase, TestCase+from django.utils import timezone as django_timezonefrom parameterized import parameterized+from temporalio.client import WorkflowExecutionStatus+from posthog.models import Organization, Team+from posthog.models.user import User++from products.tasks.backend.facade.api import (+ filter_uncovered_workflow_dispatch_run_ids,+ get_stale_queued_task_run_ids,+ maintain_workflow_dispatch_outbox,+ resume_task_run_in_cloud,+)from products.tasks.backend.logic.services.workflow_dispatch import (+ RestartSnapshot,WorkflowDispatchOptions,build_create_payload,+ build_restart_payload,create_dispatch,+ dispatch_exceeded_max_age,+ mark_dead,parse_create_payload,+ parse_restart_payload,reschedule,+ sample_dispatch_metrics,+)+from products.tasks.backend.management.commands.run_task_workflow_dispatcher import (+ Command,+ _user_can_dispatch,+ restart_attempt_already_started,)-from products.tasks.backend.management.commands.run_task_workflow_dispatcher import Command, _user_can_dispatchfrom products.tasks.backend.metrics import WORKFLOW_DISPATCH_ATTEMPT_TOTAL+from products.tasks.backend.models import Task, TaskRun, TaskWorkflowDispatchfrom products.tasks.backend.temporal.process_task.workflow import PendingFollowup@@ -35,6 +60,19 @@ class TestWorkflowDispatchPayload(SimpleTestCase):queryset.get_or_create.assert_called_once()queryset.update_or_create.assert_not_called()+ def test_restart_retry_recognizes_workflow_started_by_prior_attempt(self) -> None:+ enqueued_at = django_timezone.now()+ dispatch = Mock(workflow_id="workflow-id", enqueued_at=enqueued_at)+ description = Mock(status=WorkflowExecutionStatus.RUNNING, start_time=enqueued_at + timedelta(seconds=1))+ handle = Mock(describe=AsyncMock(return_value=description))+ client = Mock()+ client.get_workflow_handle.return_value = handle++ self.assertTrue(asyncio.run(restart_attempt_already_started(client, dispatch)))+ handle.describe.assert_awaited_once_with(+ rpc_timeout=timedelta(seconds=settings.TASKS_DISPATCHER_RPC_TIMEOUT_SECONDS)+ )+def test_create_payload_round_trip_preserves_followup_without_secrets(self) -> None:options = WorkflowDispatchOptions(user_id=42,@@ -71,6 +109,206 @@ class TestWorkflowDispatchPayload(SimpleTestCase):uniform.assert_called_once_with(1.0, 256.0)+ def test_restart_payload_round_trip_preserves_compensation_snapshot(self) -> None:+ snapshot = RestartSnapshot(+ status="failed",+ environment="local",+ completed_at="2026-08-14T10:00:00+00:00",+ queued_at=None,+ state={"snapshot_external_id": "snapshot-1"},+ )++ payload = build_restart_payload(42, snapshot)++ self.assertEqual(parse_restart_payload(payload), (42, snapshot))+++class TestWorkflowDispatchPersistence(TestCase):+ def setUp(self) -> None:+ organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=organization, name="Test Team")+ user = User.objects.create(email="[email protected]")+ task = Task.objects.create(+ team=self.team,+ created_by=user,+ title="Test Task",+ description="Test Description",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ self.task_run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.QUEUED)++ @patch("products.tasks.backend.temporal.client._terminalize_unstarted_task_run")+ def test_malformed_restart_payload_is_terminalized_after_marking_dispatch_dead(self, terminalize: Mock) -> None:+ dispatch = 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.RESTART,+ payload={"version": 999},+ status=TaskWorkflowDispatch.Status.CLAIMED,+ claimed_by="dispatcher-1",+ )++ with self.captureOnCommitCallbacks(execute=True):+ self.assertEqual(mark_dead(dispatch.id, "dispatcher-1", "invalid restart payload"), 1)++ dispatch.refresh_from_db()+ self.assertEqual(dispatch.status, TaskWorkflowDispatch.Status.DEAD)+ terminalize.assert_called_once_with(str(self.task_run.id), "invalid restart payload")++ @patch("products.tasks.backend.feature_flags.is_workflow_dispatch_restart_enabled")+ def test_restart_flag_is_evaluated_before_locking_run(self, restart_enabled: Mock) -> None:+ baseline_atomic_depth = len(transaction.get_connection().atomic_blocks)++ def assert_outside_transaction(*_args: object) -> bool:+ self.assertEqual(len(transaction.get_connection().atomic_blocks), baseline_atomic_depth)+ return True++ restart_enabled.side_effect = assert_outside_transaction++ outcome, _, _ = resume_task_run_in_cloud(self.task_run.id, self.task_run.task_id, self.team.id, None)++ self.assertEqual(outcome, "already_active")++ def test_reenqueuing_restart_resets_dispatch_age(self) -> None:+ snapshot = RestartSnapshot(+ status=TaskRun.Status.FAILED,+ environment=TaskRun.Environment.LOCAL,+ completed_at=None,+ queued_at=None,+ state={},+ )+ first_enqueued_at = django_timezone.now() - timedelta(days=1)+ with (+ patch(+ "products.tasks.backend.logic.services.workflow_dispatch.django_timezone.now",+ return_value=first_enqueued_at,+ ),+ transaction.atomic(),+ ):+ dispatch = create_dispatch(+ self.task_run,+ TaskWorkflowDispatch.Kind.RESTART,+ build_restart_payload(None, snapshot),+ self.task_run.workflow_id,+ )+ TaskWorkflowDispatch.objects.unscoped().filter(id=dispatch.id).update(created_at=first_enqueued_at)++ reenqueued_at = django_timezone.now()+ with (+ patch(+ "products.tasks.backend.logic.services.workflow_dispatch.django_timezone.now",+ return_value=reenqueued_at,+ ),+ transaction.atomic(),+ ):+ create_dispatch(+ self.task_run,+ TaskWorkflowDispatch.Kind.RESTART,+ build_restart_payload(None, snapshot),+ self.task_run.workflow_id,+ )++ dispatch.refresh_from_db()+ self.assertEqual(dispatch.enqueued_at, reenqueued_at)+ self.assertFalse(dispatch_exceeded_max_age(dispatch, 6 * 60 * 60, now=reenqueued_at))++ def test_oldest_ready_age_uses_latest_enqueue_time(self) -> None:+ now = django_timezone.now()+ snapshot = RestartSnapshot(+ status=TaskRun.Status.FAILED,+ environment=TaskRun.Environment.LOCAL,+ completed_at=None,+ queued_at=None,+ state={},+ )+ with transaction.atomic():+ dispatch = create_dispatch(+ self.task_run,+ TaskWorkflowDispatch.Kind.RESTART,+ build_restart_payload(None, snapshot),+ self.task_run.workflow_id,+ )+ TaskWorkflowDispatch.objects.unscoped().filter(id=dispatch.id).update(+ created_at=now - timedelta(days=1),+ enqueued_at=now - timedelta(minutes=5),+ next_attempt_at=now - timedelta(minutes=5),+ )++ with (+ patch("products.tasks.backend.logic.services.workflow_dispatch.django_timezone.now", return_value=now),+ patch(+ "products.tasks.backend.logic.services.workflow_dispatch.WORKFLOW_DISPATCH_OLDEST_READY_AGE_SECONDS.set"+ ) as set_oldest_age,+ ):+ sample_dispatch_metrics()++ set_oldest_age.assert_called_once_with(300.0)++ @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(+ self, _shadow_enabled: Mock, increment_missing_intent: Mock+ ) -> None:+ uncovered = filter_uncovered_workflow_dispatch_run_ids([self.task_run.id])++ self.assertEqual(uncovered, [self.task_run.id])+ increment_missing_intent.assert_not_called()++ def test_reconciler_excludes_covered_runs_at_any_age_unlike_the_killer_view(self) -> None:+ orphan_run = TaskRun.objects.create(task=self.task_run.task, team=self.team, status=TaskRun.Status.QUEUED)+ 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.PENDING,+ )+ # Age the covered run's dispatch past the killer's coverage window, and both runs past staleness.+ TaskWorkflowDispatch.objects.unscoped().filter(task_run=self.task_run).update(+ enqueued_at=django_timezone.now()+ - timedelta(seconds=settings.TASKS_DISPATCHER_MAX_DISPATCH_AGE_SECONDS + 3600)+ )+ TaskRun.objects.filter(id__in=[self.task_run.id, orphan_run.id]).update(+ updated_at=django_timezone.now() - timedelta(hours=1)+ )++ reconciler_view = get_stale_queued_task_run_ids(+ timedelta(minutes=5), 500, environment=TaskRun.Environment.CLOUD, exclude_covered_dispatches=True+ )+ killer_view = get_stale_queued_task_run_ids(timedelta(minutes=5), 500, environment=TaskRun.Environment.CLOUD)++ self.assertEqual(reconciler_view, [orphan_run.id])+ self.assertIn(self.task_run.id, killer_view)++ def test_outbox_maintenance_prunes_dead_rows_only_after_retention(self) -> None:+ second_run = TaskRun.objects.create(task=self.task_run.task, team=self.team, status=TaskRun.Status.QUEUED)+ old_dead = 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.DEAD,+ )+ fresh_dead = TaskWorkflowDispatch.objects.for_team(self.team.id).create(+ team=self.team,+ task_run=second_run,+ workflow_id=second_run.workflow_id,+ dispatch_kind=TaskWorkflowDispatch.Kind.CREATE,+ payload={"version": 1},+ status=TaskWorkflowDispatch.Status.DEAD,+ )+ TaskWorkflowDispatch.objects.unscoped().filter(id=old_dead.id).update(+ updated_at=django_timezone.now() - timedelta(days=31)+ )++ maintain_workflow_dispatch_outbox()++ remaining = set(TaskWorkflowDispatch.objects.unscoped().values_list("id", flat=True))+ self.assertEqual(remaining, {fresh_dead.id})+class TestWorkflowDispatchPermissions(SimpleTestCase):@patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.UserPermissions")@@ -78,7 +316,7 @@ class TestWorkflowDispatchPermissions(SimpleTestCase):def test_user_requires_current_effective_team_access(self, users: Mock, permissions: Mock) -> None:user = users.filter.return_value.first.return_valuepermissions.return_value.current_team.effective_membership_level = None- run = Mock(task=Mock(team=Mock()))+ run = Mock(task=Mock(team=Mock(), created_by_id=99))self.assertFalse(_user_can_dispatch(run, WorkflowDispatchOptions(user_id=42)))users.filter.assert_called_once_with(id=42, is_active=True)