: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): add durable workflow dispatch outbox (#83081)
Alessandro Pogliaghibe3a371cea05
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 57bcc8bb3c2c..29a1194d73d2 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -333,6 +333,7 @@ rules:|TaskAutomation|TaskPresence|TaskRun+ |TaskWorkflowDispatch|TaskSearchDocument|TaskSession|TaskThreadMessage@@ -696,6 +697,7 @@ rules:|TaskAutomation|TaskPresence|TaskRun+ |TaskWorkflowDispatch|TaskSession|TaskThreadMessage|TaskThreadMessageMentiondiff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 6d0cb8c6a48b..bc57d57903fe 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -194,6 +194,14 @@ EXPERIMENTS_RECALCULATION_TASK_QUEUE = _set_temporal_task_queue("experiments-recHEALTH_CHECK_TASK_QUEUE = _set_temporal_task_queue("health-check-task-queue")DUCKLAKE_TASK_QUEUE = _set_temporal_task_queue("ducklake-task-queue")TASKS_TASK_QUEUE = _set_temporal_task_queue("tasks-task-queue")+TASKS_DISPATCHER_BATCH_SIZE = get_from_env("TASKS_DISPATCHER_BATCH_SIZE", 50, type_cast=int)+TASKS_DISPATCHER_CONCURRENCY = get_from_env("TASKS_DISPATCHER_CONCURRENCY", 20, type_cast=int)+TASKS_DISPATCHER_LEASE_SECONDS = get_from_env("TASKS_DISPATCHER_LEASE_SECONDS", 60, type_cast=int)+TASKS_DISPATCHER_POLL_INTERVAL_SECONDS = get_from_env("TASKS_DISPATCHER_POLL_INTERVAL_SECONDS", 1.0, type_cast=float)+TASKS_DISPATCHER_RPC_TIMEOUT_SECONDS = get_from_env("TASKS_DISPATCHER_RPC_TIMEOUT_SECONDS", 10, type_cast=int)+TASKS_DISPATCHER_MAX_DISPATCH_AGE_SECONDS = get_from_env(+ "TASKS_DISPATCHER_MAX_DISPATCH_AGE_SECONDS", 6 * 60 * 60, type_cast=int+)STAMPHOG_TASK_QUEUE = _set_temporal_task_queue("stamphog-task-queue")TEST_TASK_QUEUE = _set_temporal_task_queue("test-task-queue")BILLING_TASK_QUEUE = _set_temporal_task_queue("billing-task-queue")diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 3a1c60efbfee..b147ce1888df 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -11,6 +11,9 @@ PR_STATES = ("open", "draft", "merged", "closed")CI_STATUSES = ("passing", "failing", "pending", "none")SANDBOX_EVENT_INGEST_FEATURE_FLAG = "tasks-cloud-runs-sandbox-event-ingest"+WORKFLOW_DISPATCH_SHADOW_FEATURE_FLAG = "tasks-workflow-dispatch-shadow"+WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG = "tasks-workflow-dispatch-async"+WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG = "tasks-workflow-dispatch-restart"AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG = "tasks-agent-proxy-keep-stream-open"MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"# Gates the nightly prebaked dev-stack image bake (see logic/services/dev_stack_image.py).diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 21eed230b6e5..e6b3d0d131f0 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -3967,8 +3967,9 @@ def _trigger_task_processing_workflow(initial_artifact_ids: list[str] | None = None,raise_on_error: bool = False,) -> None:- from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path- execute_task_processing_workflow,+ from products.tasks.backend.logic.services.workflow_dispatch import ( # noqa: PLC0415+ WorkflowDispatchOptions,+ enqueue_or_start_workflow,)from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import pathRunSource,@@ -3983,28 +3984,22 @@ def _trigger_task_processing_workflow(posthog_mcp_scopes: Literal["read_only", "full"] = "full" if run_source in full_mcp_run_sources else "read_only"try:logger.info("Attempting to trigger task processing workflow for task %s, run %s", task.id, run.id)+ message = Noneif initial_message or initial_artifact_ids:- execute_task_processing_workflow(- task_id=str(task.id),- run_id=str(run.id),- team_id=task.team.id,- user_id=user_id,- posthog_mcp_scopes=posthog_mcp_scopes,- initial_message=PendingFollowup(- message=initial_message,- artifact_ids=initial_artifact_ids or [],- actor_user_id=user_id,- message_id=str(uuid4()),- ),+ message = PendingFollowup(+ message=initial_message,+ artifact_ids=initial_artifact_ids or [],+ actor_user_id=user_id,+ message_id=str(uuid4()),)- else:- execute_task_processing_workflow(- task_id=str(task.id),- run_id=str(run.id),- team_id=task.team.id,+ enqueue_or_start_workflow(+ run,+ options=WorkflowDispatchOptions(user_id=user_id,posthog_mcp_scopes=posthog_mcp_scopes,- )+ initial_message=message,+ ),+ )logger.info("Workflow trigger completed for task %s, run %s", task.id, run.id)except Exception as e:logger.exception("Failed to trigger task processing workflow for task %s, run %s: %s", task.id, run.id, e)@@ -4068,20 +4063,27 @@ def start_task_run(previous_state = dict(run.state or {})try:- if state_updates:- TaskRun.update_state_atomic(run.id, updates=state_updates)- run.refresh_from_db()- logger.info("Triggering workflow for task %s, existing run %s", task.id, run.id)- _trigger_task_processing_workflow(- task,- run,- user_id,- initial_message=(pending_user_message or task.description or None)- if task.runtime == Task.Runtime.PI- else None,- initial_artifact_ids=pending_user_artifact_ids if task.runtime == Task.Runtime.PI else None,- raise_on_error=True,- )+ with transaction.atomic():+ run = (+ TaskRun.objects.select_for_update(of=("self",))+ .select_related("task", "task__team", "task__created_by")+ .get(id=run.id)+ )+ task = run.task+ if state_updates:+ TaskRun.update_state_atomic(run.id, updates=state_updates)+ run.refresh_from_db()+ logger.info("Triggering workflow for task %s, existing run %s", task.id, run.id)+ _trigger_task_processing_workflow(+ task,+ run,+ user_id,+ initial_message=(pending_user_message or task.description or None)+ if task.runtime == Task.Runtime.PI+ else None,+ initial_artifact_ids=pending_user_artifact_ids if task.runtime == Task.Runtime.PI else None,+ raise_on_error=True,+ )except Exception:if state_updates:rollback_updates = {@@ -7535,13 +7537,14 @@ def request_canvas_fix(task_id: str | UUID, team_id: int, *, prompt: str, acting# The workflow is gone despite the non-terminal row (evicted or stale); fall# through to a fresh run rather than reporting a dead end.task_run = task.create_run(mode="background", extra_state={"pending_user_message": prompt})- transaction.on_commit(- lambda: _dispatch_server_run(- team_id=task.team_id,- user_id=task.created_by_id,- task_id=str(task.id),- run_id=str(task_run.id),- )+ from products.tasks.backend.logic.services.workflow_dispatch import ( # noqa: PLC0415+ WorkflowDispatchOptions,+ enqueue_or_start_workflow,+ )++ enqueue_or_start_workflow(+ task_run,+ options=WorkflowDispatchOptions(user_id=task.created_by_id, skip_user_check=True),)return "new_run"diff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.pyindex aa0db1096557..f38950b72f72 100644--- a/products/tasks/backend/feature_flags.py+++ b/products/tasks/backend/feature_flags.py@@ -10,6 +10,9 @@ from products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,AGENT_RUN_OTEL_TELEMETRY_FEATURE_FLAG,DEV_STACK_IMAGE_BAKE_FEATURE_FLAG,+ WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG,+ WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG,+ WORKFLOW_DISPATCH_SHADOW_FEATURE_FLAG,get_required_model_flag,)@@ -19,6 +22,48 @@ NATIVE_STEERING_SIGNALS_FEATURE_FLAG = "tasks-native-steering-signals"NATIVE_STEERING_SIGNALS_DISTINCT_ID = "tasks-native-steering-signals"DEV_STACK_IMAGE_BAKE_DISTINCT_ID = "tasks-dev-stack-image-bake"+WORKFLOW_DISPATCH_SHADOW_DISTINCT_ID = "tasks-workflow-dispatch-shadow"+++def is_workflow_dispatch_shadow_enabled() -> bool:+ try:+ return bool(+ posthoganalytics.feature_enabled(+ WORKFLOW_DISPATCH_SHADOW_FEATURE_FLAG,+ distinct_id=WORKFLOW_DISPATCH_SHADOW_DISTINCT_ID,+ person_properties={"region": get_instance_region() or "DEV"},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception("workflow_dispatch_shadow_flag_check_failed")+ return False+++def _is_workflow_dispatch_org_flag_enabled(flag: str, organization_id: str, distinct_id: str) -> bool:+ try:+ return bool(+ posthoganalytics.feature_enabled(+ flag,+ distinct_id=distinct_id,+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ )+ except Exception:+ logger.exception("workflow_dispatch_org_flag_check_failed", extra={"flag": flag})+ return False+++def is_workflow_dispatch_async_enabled(organization_id: str, distinct_id: str) -> bool:+ return _is_workflow_dispatch_org_flag_enabled(WORKFLOW_DISPATCH_ASYNC_FEATURE_FLAG, organization_id, distinct_id)+++def is_workflow_dispatch_restart_enabled(organization_id: str, distinct_id: str) -> bool:+ return _is_workflow_dispatch_org_flag_enabled(WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG, organization_id, distinct_id)def is_dev_stack_image_bake_enabled() -> bool:diff --git a/products/tasks/backend/logic/services/loop_runs.py b/products/tasks/backend/logic/services/loop_runs.pyindex c10430825815..d10835d2e59e 100644--- a/products/tasks/backend/logic/services/loop_runs.py+++ b/products/tasks/backend/logic/services/loop_runs.py@@ -783,18 +783,13 @@ def _create_loop_task_and_run(loop: Loop, trigger: LoopTrigger | None, trigger_ctask_run = task.create_run(mode="background", extra_state=extra_state)- team_id = loop.team_id- user_id = loop.created_by_id- task_id = str(task.id)- run_id = str(task_run.id)-transaction.on_commit(lambda: _seed_skill_bundles_and_dispatch(task_run=task_run,- team_id=team_id,- user_id=user_id,- task_id=task_id,- run_id=run_id,+ team_id=loop.team_id,+ user_id=loop.created_by_id,+ task_id=str(task.id),+ run_id=str(task_run.id),create_pr=create_pr,posthog_mcp_scopes=posthog_mcp_scopes,)diff --git a/products/tasks/backend/logic/services/tests/test_warm.py b/products/tasks/backend/logic/services/tests/test_warm.pyindex 3032aaefcca0..e285c9695545 100644--- a/products/tasks/backend/logic/services/tests/test_warm.py+++ b/products/tasks/backend/logic/services/tests/test_warm.py@@ -100,6 +100,7 @@ class TestSandboxWarmerWarm(APIBaseTest):with (patch(f"{WARM}.execute_task_processing_workflow") as m_workflow,patch(f"{WARM}.is_team_limited", return_value=False),+ patch("products.tasks.backend.models.settings.TEST", False),):result = SandboxWarmer(task, user=self.user).warm()m_workflow.assert_not_called()diff --git a/products/tasks/backend/logic/services/warm.py b/products/tasks/backend/logic/services/warm.pyindex ab12837e2fc1..87c89f83ee1c 100644--- a/products/tasks/backend/logic/services/warm.py+++ b/products/tasks/backend/logic/services/warm.py@@ -26,6 +26,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom products.tasks.backend.logic.services.compute_quota import organization_deactivated+from products.tasks.backend.logic.services.workflow_dispatch import WorkflowDispatchOptions, enqueue_or_start_workflowfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.temporal.client import execute_task_processing_workflowfrom products.tasks.backend.temporal.process_task.utils import parse_run_state@@ -173,17 +174,15 @@ class SandboxWarmer:new_run = locked.create_run(mode=mode, extra_state=run_state, branch=run_state.get("branch"))# Dispatch only after the row commits, so a rollback can't leave an orphaned sandbox.- task_id, run_id, team_id, user_id = str(locked.id), str(new_run.id), self.task.team_id, self.user.pk- transaction.on_commit(- lambda: execute_task_processing_workflow(- task_id=task_id,- run_id=run_id,- team_id=team_id,- user_id=user_id,+ enqueue_or_start_workflow(+ new_run,+ start_workflow=execute_task_processing_workflow,+ options=WorkflowDispatchOptions(+ user_id=self.user.pk,create_pr=create_pr,posthog_mcp_scopes="full",prewarmed=True,- )+ ),)logger.info(diff --git a/products/tasks/backend/logic/services/workflow_dispatch.py b/products/tasks/backend/logic/services/workflow_dispatch.pynew file mode 100644index 000000000000..d488fe110778--- /dev/null+++ b/products/tasks/backend/logic/services/workflow_dispatch.py@@ -0,0 +1,328 @@+import random+from collections.abc import Callable+from dataclasses import asdict+from datetime import datetime, timedelta+from typing import Any++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 products.tasks.backend.metrics import (+ WORKFLOW_DISPATCH_CLAIMED,+ WORKFLOW_DISPATCH_CREATED_TOTAL,+ WORKFLOW_DISPATCH_LEASE_EXPIRED_TOTAL,+ WORKFLOW_DISPATCH_OLDEST_READY_AGE_SECONDS,+ WORKFLOW_DISPATCH_READY,+ observe_task_run_dispatch_callback,+)+from products.tasks.backend.models import TaskRun, TaskWorkflowDispatch, execute_after_commit+from products.tasks.backend.temporal.process_task.workflow import PendingFollowup++DISPATCH_PAYLOAD_VERSION = 1+++@frozen+class WorkflowDispatchOptions:+ user_id: int | None = None+ create_pr: bool = True+ posthog_mcp_scopes: PosthogMcpScopes = "read_only"+ slack_thread_context: dict[str, Any] | None = None+ prewarmed: bool = False+ workflow_id_prefix: str | None = None+ initial_message: PendingFollowup | None = None+ skip_user_check: bool = False+++@frozen+class RestartSnapshot:+ status: str+ environment: str+ completed_at: str | None+ queued_at: str | None+ state: dict[str, Any]+++@frozen+class WorkflowDispatchFlags:+ shadow_enabled: bool+ async_enabled: bool+++def build_create_payload(options: WorkflowDispatchOptions) -> dict[str, Any]:+ return {+ "version": DISPATCH_PAYLOAD_VERSION,+ "user_id": options.user_id,+ "create_pr": options.create_pr,+ "posthog_mcp_scopes": options.posthog_mcp_scopes,+ "slack_thread_context": options.slack_thread_context,+ "prewarmed": options.prewarmed,+ "initial_message": asdict(options.initial_message) if options.initial_message else None,+ }+++def parse_create_payload(payload: dict[str, Any]) -> WorkflowDispatchOptions:+ if payload.get("version") != DISPATCH_PAYLOAD_VERSION:+ raise ValueError("Unsupported workflow dispatch payload version")+ initial_message = payload.get("initial_message")+ return WorkflowDispatchOptions(+ user_id=payload.get("user_id"),+ create_pr=payload["create_pr"],+ posthog_mcp_scopes=payload["posthog_mcp_scopes"],+ slack_thread_context=payload.get("slack_thread_context"),+ prewarmed=payload.get("prewarmed", False),+ initial_message=PendingFollowup(**initial_message) if initial_message else None,+ )+++def build_restart_payload(user_id: int | None, snapshot: RestartSnapshot) -> dict[str, Any]:+ return {"version": DISPATCH_PAYLOAD_VERSION, "user_id": user_id, "snapshot": asdict(snapshot)}+++def parse_restart_payload(payload: dict[str, Any]) -> tuple[int | None, RestartSnapshot]:+ if payload.get("version") != DISPATCH_PAYLOAD_VERSION:+ raise ValueError("Unsupported workflow dispatch payload version")+ return payload.get("user_id"), RestartSnapshot(**payload["snapshot"])+++def create_dispatch(task_run: TaskRun, kind: str, payload: dict[str, Any], workflow_id: str) -> TaskWorkflowDispatch:+ if not transaction.get_connection().in_atomic_block:+ raise RuntimeError("Workflow dispatch creation requires an atomic transaction")+ defaults = {+ "team_id": task_run.team_id,+ "workflow_id": workflow_id,+ "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": "",+ }+ queryset = TaskWorkflowDispatch.objects.for_team(task_run.team_id)+ if kind == TaskWorkflowDispatch.Kind.RESTART:+ dispatch, created = queryset.update_or_create(task_run=task_run, dispatch_kind=kind, defaults=defaults)+ else:+ dispatch, created = queryset.get_or_create(task_run=task_run, dispatch_kind=kind, defaults=defaults)+ if created:+ WORKFLOW_DISPATCH_CREATED_TOTAL.labels(kind=kind).inc()+ return dispatch+++def claim_dispatches(instance_id: str, batch_size: int, lease: timedelta) -> list[TaskWorkflowDispatch]:+ now = django_timezone.now()+ with transaction.atomic():+ # This process intentionally claims work across every team.+ rows = list(+ TaskWorkflowDispatch.objects.unscoped()+ .filter(+ Q(status=TaskWorkflowDispatch.Status.PENDING, next_attempt_at__lte=now)+ | Q(status=TaskWorkflowDispatch.Status.CLAIMED, lease_expires_at__lte=now)+ )+ .order_by("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)+ ids = [row.id for row in rows]+ TaskWorkflowDispatch.objects.unscoped().filter(id__in=ids).update(+ status=TaskWorkflowDispatch.Status.CLAIMED,+ claimed_by=instance_id,+ 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")+ )+++def 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)),+ )+ WORKFLOW_DISPATCH_READY.set(values["ready"] or 0)+ WORKFLOW_DISPATCH_CLAIMED.set(values["claimed"] or 0)+ oldest = values["oldest_ready"]+ WORKFLOW_DISPATCH_OLDEST_READY_AGE_SECONDS.set(max(0.0, (now - oldest).total_seconds()) if oldest else 0)+++def renew_leases(instance_id: str, dispatch_ids: list[Any], lease: timedelta) -> int:+ return (+ TaskWorkflowDispatch.objects.unscoped()+ .filter(id__in=dispatch_ids, claimed_by=instance_id, status=TaskWorkflowDispatch.Status.CLAIMED)+ .update(lease_expires_at=django_timezone.now() + lease)+ )+++def mark_accepted(dispatch_id: Any, instance_id: str) -> int:+ return (+ TaskWorkflowDispatch.objects.unscoped()+ .filter(id=dispatch_id, claimed_by=instance_id, status=TaskWorkflowDispatch.Status.CLAIMED)+ .update(+ status=TaskWorkflowDispatch.Status.ACCEPTED,+ accepted_at=django_timezone.now(),+ claimed_by="",+ lease_expires_at=None,+ )+ )+++def reschedule(dispatch_id: Any, instance_id: str, error: str) -> int:+ dispatch = TaskWorkflowDispatch.objects.unscoped().get(id=dispatch_id)+ delay = random.uniform(1.0, 2.0 ** min(dispatch.attempt_count, 8))+ return (+ TaskWorkflowDispatch.objects.unscoped()+ .filter(id=dispatch_id, claimed_by=instance_id, status=TaskWorkflowDispatch.Status.CLAIMED)+ .update(+ status=TaskWorkflowDispatch.Status.PENDING,+ next_attempt_at=django_timezone.now() + timedelta(seconds=delay),+ last_error=error[:2000],+ claimed_by="",+ lease_expires_at=None,+ )+ )+++def release_claims(instance_id: str) -> int:+ return (+ TaskWorkflowDispatch.objects.unscoped()+ .filter(claimed_by=instance_id, status=TaskWorkflowDispatch.Status.CLAIMED)+ .update(status=TaskWorkflowDispatch.Status.PENDING, claimed_by="", lease_expires_at=None)+ )+++def mark_dead(dispatch_id: Any, instance_id: str, error: str) -> int:+ with transaction.atomic():+ dispatch = (+ TaskWorkflowDispatch.objects.unscoped().select_for_update().select_related("task_run").get(id=dispatch_id)+ )+ if dispatch.claimed_by != instance_id or dispatch.status != TaskWorkflowDispatch.Status.CLAIMED:+ return 0+ dispatch.status = TaskWorkflowDispatch.Status.DEAD+ dispatch.last_error = error[:2000]+ dispatch.claimed_by = ""+ dispatch.lease_expires_at = None+ dispatch.save(update_fields=["status", "last_error", "claimed_by", "lease_expires_at", "updated_at"])+ run = dispatch.task_run+ if dispatch.dispatch_kind == TaskWorkflowDispatch.Kind.RESTART:+ _, snapshot = parse_restart_payload(dispatch.payload)+ run.status = snapshot.status+ run.environment = snapshot.environment+ run.completed_at = datetime.fromisoformat(snapshot.completed_at) if snapshot.completed_at else None+ run.queued_at = datetime.fromisoformat(snapshot.queued_at) if snapshot.queued_at else None+ run.state = snapshot.state+ run.error_message = "Failed to start cloud workflow"+ else:+ from products.tasks.backend.temporal.client import _terminalize_unstarted_task_run # noqa: PLC0415++ execute_after_commit(lambda: _terminalize_unstarted_task_run(str(run.id), error[:2000]))+ return 1+ run.save()+ execute_after_commit(run.publish_stream_state_event)+ return 1+++def resolve_ineligible(dispatch_id: Any, instance_id: str) -> int:+ updated = mark_accepted(dispatch_id, instance_id)+ if updated:+ TaskWorkflowDispatch.objects.unscoped().filter(id=dispatch_id).update(last_error="resolved: run left QUEUED")+ return updated+++def renew_leases_in_worker_thread(instance_id: str, dispatch_ids: list[Any], lease: timedelta) -> int:+ """Renew leases without retaining a connection owned by the shared thread pool."""+ close_old_connections()+ try:+ return renew_leases(instance_id, dispatch_ids, lease)+ finally:+ close_old_connections()+++def evaluate_workflow_dispatch_flags(task_run: TaskRun) -> WorkflowDispatchFlags:+ from products.tasks.backend.feature_flags import (+ is_workflow_dispatch_async_enabled,+ is_workflow_dispatch_shadow_enabled,+ )++ distinct_id = (+ task_run.task.created_by.distinct_id+ if task_run.task.created_by and task_run.task.created_by.distinct_id+ else str(task_run.id)+ )+ organization_id = str(task_run.task.team.organization_id)+ return WorkflowDispatchFlags(+ shadow_enabled=is_workflow_dispatch_shadow_enabled(),+ async_enabled=is_workflow_dispatch_async_enabled(organization_id, distinct_id),+ )+++def enqueue_or_start_workflow(+ task_run: TaskRun,+ *,+ options: WorkflowDispatchOptions,+ precomputed_flags: WorkflowDispatchFlags | None = None,+ start_workflow: Callable[..., None] | None = None,+) -> None:+ if start_workflow is None:+ from products.tasks.backend.temporal.client import execute_task_processing_workflow++ start_workflow = execute_task_processing_workflow++ flags = precomputed_flags or evaluate_workflow_dispatch_flags(task_run)+ workflow_id = TaskRun.get_workflow_id(str(task_run.task_id), str(task_run.id), options.workflow_id_prefix)+ if options.workflow_id_prefix:+ TaskRun.update_state_atomic(task_run.id, updates={"workflow_id": workflow_id})+ task_run.state = {**(task_run.state or {}), "workflow_id": workflow_id}+ if flags.shadow_enabled or flags.async_enabled:+ if transaction.get_connection().in_atomic_block:+ create_dispatch(task_run, TaskWorkflowDispatch.Kind.CREATE, build_create_payload(options), workflow_id)+ else:+ with transaction.atomic():+ locked_run = (+ TaskRun.objects.select_for_update().select_related("task", "task__team").get(id=task_run.id)+ )+ create_dispatch(+ locked_run, TaskWorkflowDispatch.Kind.CREATE, build_create_payload(options), workflow_id+ )+ if flags.async_enabled:+ return++ def start_synchronously() -> None:+ observe_task_run_dispatch_callback(task_run, phase="fired")+ workflow_kwargs: dict[str, Any] = {+ "task_id": str(task_run.task_id),+ "run_id": str(task_run.id),+ "team_id": task_run.team_id,+ "user_id": options.user_id,+ "posthog_mcp_scopes": options.posthog_mcp_scopes,+ }+ if not options.create_pr:+ workflow_kwargs["create_pr"] = False+ if options.slack_thread_context is not None:+ workflow_kwargs["slack_thread_context"] = options.slack_thread_context+ if options.prewarmed:+ workflow_kwargs["prewarmed"] = True+ if options.workflow_id_prefix is not None:+ workflow_kwargs["workflow_id_prefix"] = options.workflow_id_prefix+ if options.initial_message is not None:+ workflow_kwargs["initial_message"] = options.initial_message+ if options.skip_user_check:+ workflow_kwargs["skip_user_check"] = True+ start_workflow(**workflow_kwargs)++ execute_after_commit(start_synchronously)+++async def aenqueue_or_start_workflow(task_run: TaskRun, *, options: WorkflowDispatchOptions) -> None:+ from asgiref.sync import sync_to_async++ await sync_to_async(enqueue_or_start_workflow)(task_run, options=options)diff --git a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.pynew file mode 100644index 000000000000..2411dbd68c20--- /dev/null+++ b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py@@ -0,0 +1,208 @@+import os+import signal+import socket+import asyncio+import logging+import secrets+from datetime import timedelta+from functools import partial+from pathlib import Path+from time import monotonic++from django.conf import settings+from django.core.management.base import BaseCommand+from django.utils import timezone as django_timezone++from asgiref.sync import sync_to_async+from prometheus_client import start_http_server+from temporalio.client import Client+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.temporal.common.client import async_connect+from posthog.user_permissions import UserPermissions++from products.tasks.backend.logic.services.workflow_dispatch import (+ WorkflowDispatchOptions,+ claim_dispatches,+ mark_accepted,+ mark_dead,+ parse_create_payload,+ release_claims,+ renew_leases_in_worker_thread,+ reschedule,+ resolve_ineligible,+ sample_dispatch_metrics,+)+from products.tasks.backend.metrics import (+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL,+ WORKFLOW_DISPATCH_START_DURATION_SECONDS,+ observe_task_run_workflow_start,+)+from products.tasks.backend.models import TaskRun, TaskWorkflowDispatch+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__)+++def _user_can_dispatch(run: TaskRun, options: WorkflowDispatchOptions) -> bool:+ if options.skip_user_check:+ return True+ if options.user_id is None:+ return False+ user = User.objects.filter(id=options.user_id, is_active=True).first()+ if user is None:+ return False+ return UserPermissions(user=user, team=run.task.team).current_team.effective_membership_level is not None+++class Command(BaseCommand):+ help = "Dispatch queued task workflows from the durable outbox"++ def handle(self, *args: object, **options: object) -> None:+ start_http_server(8001)+ asyncio.run(self._run())++ async def _run(self) -> None:+ instance_id = f"{socket.gethostname()}:{os.getpid()}:{secrets.token_hex(4)}"+ stop = asyncio.Event()+ loop = asyncio.get_running_loop()+ for sig in (signal.SIGTERM, signal.SIGINT):+ loop.add_signal_handler(sig, stop.set)+ client = await async_connect()+ Path("/tmp/dispatcher-ready").touch()+ semaphore = asyncio.Semaphore(settings.TASKS_DISPATCHER_CONCURRENCY)+ lease = timedelta(seconds=settings.TASKS_DISPATCHER_LEASE_SECONDS)+ in_flight: set[asyncio.Task[None]] = set()+ in_flight_ids: set[object] = set()+ renewer = asyncio.create_task(self._renew(instance_id, in_flight_ids, lease, stop))+ last_metrics_sample = 0.0+ 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)+ continue+ 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)+ except TimeoutError:+ pass+ continue+ for dispatch in rows:+ in_flight_ids.add(dispatch.id)+ task = asyncio.create_task(self._process(client, dispatch, instance_id, semaphore))+ in_flight.add(task)+ task.add_done_callback(partial(self._on_dispatch_done, in_flight, in_flight_ids, dispatch))+ finally:+ if in_flight:+ await asyncio.gather(*in_flight, return_exceptions=True)+ stop.set()+ await renewer+ await sync_to_async(release_claims)(instance_id)++ async def _renew(self, instance_id: str, dispatch_ids: set[object], lease: timedelta, stop: asyncio.Event) -> None:+ while not stop.is_set():+ try:+ await asyncio.wait_for(stop.wait(), timeout=20)+ except TimeoutError:+ if dispatch_ids:+ try:+ await sync_to_async(renew_leases_in_worker_thread, thread_sensitive=False)(+ instance_id, list(dispatch_ids), lease+ )+ except Exception:+ logger.exception("task_workflow_dispatch_lease_renewal_failed")++ @staticmethod+ def _on_dispatch_done(+ in_flight: set[asyncio.Task[None]],+ dispatch_ids: set[object],+ dispatch: TaskWorkflowDispatch,+ task: asyncio.Task[None],+ ) -> None:+ in_flight.discard(task)+ dispatch_ids.discard(dispatch.id)+ if task.cancelled():+ return+ error = task.exception()+ if error is None:+ return+ # An unhandled error in _process would otherwise surface only as an anonymous asyncio+ # "Task exception was never retrieved" warning, with no outcome metric. The claim stays+ # leased and is reclaimed by claim_dispatches once the lease expires.+ logger.error(+ "workflow_dispatch_worker_failed",+ exc_info=error,+ extra={"dispatch_id": str(dispatch.id), "task_run_id": str(dispatch.task_run_id)},+ )+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="failed").inc()++ async def _process(+ self, client: Client, dispatch: TaskWorkflowDispatch, instance_id: str, semaphore: asyncio.Semaphore+ ) -> None:+ async with semaphore:+ run = await TaskRun.objects.select_related("task", "task__team").aget(id=dispatch.task_run_id)+ if run.status != TaskRun.Status.QUEUED:+ 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")+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()+ return+ try:+ await Team.objects.aget(id=run.team_id)+ 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")+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()+ return+ await sync_to_async(_capture_run_feature_flags, thread_sensitive=False)(str(run.id))+ 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,+ )+ except (Team.DoesNotExist, ValueError, KeyError, TypeError) as error:+ await sync_to_async(mark_dead)(dispatch.id, instance_id, str(error))+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()+ return+ started = monotonic()+ try:+ await client.start_workflow(+ "process-task",+ workflow_input,+ id=dispatch.workflow_id,+ id_reuse_policy=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:+ await 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:+ await sync_to_async(reschedule)(dispatch.id, instance_id, str(error))+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="rescheduled").inc()+ else:+ await sync_to_async(mark_accepted)(dispatch.id, instance_id)+ WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="accepted").inc()+ observe_task_run_workflow_start(run, outcome="started", reason="dispatcher")+ finally:+ WORKFLOW_DISPATCH_START_DURATION_SECONDS.observe(monotonic() - started)diff --git a/products/tasks/backend/max_tools.py b/products/tasks/backend/max_tools.pyindex f1dd2ef9ac3f..57ebe077ce88 100644--- a/products/tasks/backend/max_tools.py+++ b/products/tasks/backend/max_tools.py@@ -1,6 +1,8 @@from typing import Any-from asgiref.sync import sync_to_async+from django.db import transaction++from asgiref.sync import async_to_sync, sync_to_asyncfrom pydantic import BaseModel, Fieldfrom posthog.storage import object_storage@@ -8,6 +10,7 @@ from posthog.storage import object_storagefrom ee.hogai.tool import MaxToolfrom .facade import api as tasks_facade+from .logic.services.workflow_dispatch import WorkflowDispatchOptions, enqueue_or_start_workflowfrom .models import Task, TaskRunfrom .temporal.client import execute_task_processing_workflow_asyncfrom .visibility import task_control_q, task_visibility_q@@ -69,7 +72,10 @@ By default, the task will be created and immediately executed. Set run=false to) -> tuple[str, dict[str, Any]]:from posthog.models.integration import Integration+ slack_thread_context = (self._config.get("configurable") or {}).get("slack_thread_context")+@sync_to_async+ @transaction.atomicdef create_task_and_maybe_run():github_integration = Integration.objects.filter(team=self._team, kind="github").first()@@ -87,6 +93,11 @@ By default, the task will be created and immediately executed. Set run=false totask_run = Noneif run:task_run = task.create_run()+ enqueue_or_start_workflow(+ task_run,+ start_workflow=lambda **kwargs: async_to_sync(execute_task_processing_workflow_async)(**kwargs),+ options=WorkflowDispatchOptions(user_id=self._user.id, slack_thread_context=slack_thread_context),+ )task_url = f"/project/{self._team.project.id}/tasks/{task.id}"if task_run:@@ -112,16 +123,6 @@ By default, the task will be created and immediately executed. Set run=false toresult = await create_task_and_maybe_run()if run and "latest_run" in result:- slack_thread_context = (self._config.get("configurable") or {}).get("slack_thread_context")-- await execute_task_processing_workflow_async(- task_id=result["task_id"],- run_id=result["latest_run"]["run_id"],- team_id=result["team_id"],- user_id=self._user.id,- slack_thread_context=slack_thread_context,- )-return (f"Created and started task '{result['title']}' (ID: {result['task_id']}).\n"f"Run ID: {result['latest_run']['run_id']}\n"@@ -149,7 +150,10 @@ Use this tool when the user wants to:args_schema: type[BaseModel] = RunTaskArgsasync def _arun_impl(self, task_id: str) -> tuple[str, dict[str, Any]]:+ slack_thread_context = (self._config.get("configurable") or {}).get("slack_thread_context")+@sync_to_async+ @transaction.atomicdef get_task_and_create_run():task = (Task.objects.filter(id=task_id, team=self._team, deleted=False)@@ -163,6 +167,11 @@ Use this tool when the user wants to:return {"error": "unsupported_runtime"}task_run = task.create_run()+ enqueue_or_start_workflow(+ task_run,+ start_workflow=lambda **kwargs: async_to_sync(execute_task_processing_workflow_async)(**kwargs),+ options=WorkflowDispatchOptions(user_id=self._user.id, slack_thread_context=slack_thread_context),+ )task_url = f"/project/{task.team.project.id}/tasks/{task.id}?runId={task_run.id}"return {"task_id": str(task.id),@@ -180,17 +189,6 @@ Use this tool when the user wants to:if result.get("error") == "unsupported_runtime":return "Pi tasks cannot be run through the ACP task workflow.", result- # Extract slack thread context from config if available- slack_thread_context = (self._config.get("configurable") or {}).get("slack_thread_context")-- await execute_task_processing_workflow_async(- task_id=result["task_id"],- run_id=result["run_id"],- team_id=result["team_id"],- user_id=self._user.id,- slack_thread_context=slack_thread_context,- )-return (f"Started execution of task '{result['title']}' ({result['slug']}).\n"f"Run ID: {result['run_id']}\n"diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 53f788ad1f39..8aadc3fc3ba8 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -1,7 +1,7 @@from typing import TYPE_CHECKING, Literalimport structlog-from prometheus_client import Counter, Histogram+from prometheus_client import Counter, Gauge, Histogramlogger = structlog.get_logger(__name__)@@ -71,6 +71,32 @@ TASK_RUN_DISPATCH_CALLBACK_TOTAL = Counter(],)+WORKFLOW_DISPATCH_CREATED_TOTAL = Counter(+ "posthog_tasks_workflow_dispatch_created_total", "Workflow dispatch rows created", labelnames=["kind"]+)+WORKFLOW_DISPATCH_ATTEMPT_TOTAL = Counter(+ "posthog_tasks_workflow_dispatch_attempt_total",+ "Workflow dispatch attempt outcomes",+ labelnames=["kind", "outcome"],+)+WORKFLOW_DISPATCH_START_DURATION_SECONDS = Histogram(+ "posthog_tasks_workflow_dispatch_start_duration_seconds", "Temporal workflow start RPC duration"+)+WORKFLOW_DISPATCH_READY = Gauge("posthog_tasks_workflow_dispatch_ready", "Ready workflow dispatches")+WORKFLOW_DISPATCH_OLDEST_READY_AGE_SECONDS = Gauge(+ "posthog_tasks_workflow_dispatch_oldest_ready_age_seconds", "Age of the oldest ready workflow dispatch"+)+WORKFLOW_DISPATCH_CLAIMED = Gauge("posthog_tasks_workflow_dispatch_claimed", "Claimed workflow dispatches")+WORKFLOW_DISPATCH_LEASE_EXPIRED_TOTAL = Counter(+ "posthog_tasks_workflow_dispatch_lease_expired_total", "Expired workflow dispatch leases reclaimed"+)+WORKFLOW_DISPATCH_DEAD_TOTAL = Counter(+ "posthog_tasks_workflow_dispatch_dead_total", "Dead workflow dispatches", labelnames=["kind", "reason"]+)+WORKFLOW_DISPATCH_MISSING_INTENT_TOTAL = Counter(+ "posthog_tasks_workflow_dispatch_missing_intent_total", "Queued cloud task runs without dispatch intent"+)+AGENT_OTEL_TELEMETRY_STAMPED_TOTAL = Counter("posthog_tasks_agent_otel_telemetry_stamped_total","Agent-run OTel telemetry rollout decisions stamped into run state at dispatch "diff --git a/products/tasks/backend/migrations/0096_taskworkflowdispatch.py b/products/tasks/backend/migrations/0096_taskworkflowdispatch.pynew file mode 100644index 000000000000..02b85319a090--- /dev/null+++ b/products/tasks/backend/migrations/0096_taskworkflowdispatch.py@@ -0,0 +1,119 @@+# Generated by Django 5.2.17 on 2026-08-14 10:03++import django.utils.timezone+import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1303_taggeditem_replay_scanner_unique_constraint"),+ ("tasks", "0095_remove_task_automation"),+ ]++ operations = [+ migrations.CreateModel(+ name="TaskWorkflowDispatch",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("workflow_id", models.CharField(max_length=512)),+ (+ "dispatch_kind",+ models.CharField(+ choices=[("create", "create"), ("restart", "restart")],+ max_length=16,+ ),+ ),+ ("enqueued_at", models.DateTimeField(default=django.utils.timezone.now)),+ ("payload", models.JSONField(default=dict)),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "pending"),+ ("claimed", "claimed"),+ ("accepted", "accepted"),+ ("dead", "dead"),+ ],+ default="pending",+ max_length=16,+ ),+ ),+ ("attempt_count", models.PositiveIntegerField(default=0)),+ (+ "next_attempt_at",+ models.DateTimeField(default=django.utils.timezone.now),+ ),+ (+ "claimed_by",+ models.CharField(blank=True, default="", max_length=128),+ ),+ ("lease_expires_at", models.DateTimeField(blank=True, null=True)),+ ("accepted_at", models.DateTimeField(blank=True, null=True)),+ ("last_error", models.TextField(blank=True, default="")),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "task_run",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="workflow_dispatches",+ to="tasks.taskrun",+ db_index=False,+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ db_index=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "db_table": "posthog_taskworkflowdispatch",+ "indexes": [+ models.Index(+ condition=models.Q(("status", "pending")),+ fields=["next_attempt_at"],+ name="twd_pending_due",+ ),+ models.Index(+ condition=models.Q(("status", "claimed")),+ fields=["lease_expires_at"],+ name="twd_claimed_lease",+ ),+ models.Index(fields=["team", "created_at"], name="twd_team_created"),+ ],+ "constraints": [+ models.UniqueConstraint(+ fields=("task_run", "dispatch_kind"),+ name="uniq_dispatch_per_run_kind",+ ),+ models.CheckConstraint(+ condition=models.Q(+ models.Q(("accepted_at__isnull", False), ("status", "accepted")),+ models.Q(+ models.Q(("status", "accepted"), _negated=True),+ ("accepted_at__isnull", True),+ ),+ _connector="OR",+ ),+ name="accepted_at_iff_accepted",+ ),+ ],+ },+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 8debbe3d6cd7..37bef8cef259 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0095_remove_task_automation+0096_taskworkflowdispatchdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 9e585d30e974..5d2636496580 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -50,6 +50,15 @@ from products.tasks.backend.storage import append_jsonl_objectlogger = structlog.get_logger(__name__)++def execute_after_commit(callback: Callable[[], object]) -> None:+ """Run commit side effects immediately in tests, where TestCase never commits its wrapper transaction."""+ if settings.TEST:+ callback()+ else:+ transaction.on_commit(callback)++LogLevel = Literal["debug", "info", "warn", "error"]MCPBuiltInAgentKey = Literal["support", "scout"]MCP_BUILT_IN_AGENT_STATE_KEY = "mcp_builtin_agent_key"@@ -503,26 +512,30 @@ class Task(DeletedMetaFields, models.Model):state=state,branch=branch,)- task_run.publish_stream_state_event()- observe_task_run_created(task_run)- self.capture_event(- "task_run_created",- {- "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),- # so carry it from the run state the same way TaskRun.capture_event does.- "loop_id": state.get("loop_id"),- "loop_trigger_id": state.get("loop_trigger_id"),- },- )++ def emit_created_events() -> None:+ task_run.publish_stream_state_event()+ observe_task_run_created(task_run)+ self.capture_event(+ "task_run_created",+ {+ "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),+ # so carry it from the run state the same way TaskRun.capture_event does.+ "loop_id": state.get("loop_id"),+ "loop_trigger_id": state.get("loop_trigger_id"),+ },+ )++ execute_after_commit(emit_created_events)return task_run@property@@ -955,7 +968,11 @@ class Task(DeletedMetaFields, models.Model):mcp_credential_owner_id: int | None = None,mcp_gateway_server_ids: list[str] | None = None,) -> "Task":- from products.tasks.backend.temporal.client import _normalize_slack_context, execute_task_processing_workflow+ from products.tasks.backend.logic.services.workflow_dispatch import (+ WorkflowDispatchOptions,+ enqueue_or_start_workflow,+ )+ from products.tasks.backend.temporal.client import _normalize_slack_contexttask, extra_state = Task._build_task(team=team,@@ -1008,37 +1025,29 @@ class Task(DeletedMetaFields, models.Model):"workflow_id_prefix": workflow_id_prefix,}- task_run = task.create_run(mode=mode, extra_state=run_extra_state or None, branch=branch)-- if start_workflow:- # 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.- # on_commit runs the callback immediately in autocommit mode, so non-atomic callers- # are unaffected. If the callback is lost (process recycled in the commit->callback- # window, or an earlier on_commit hook raising), the run stays QUEUED — the periodic- # reconciler re-dispatches it from the persisted pending_dispatch above.- run_id = str(task_run.id)- team_id = task.team.id- task_id = str(task.id)-- observe_task_run_dispatch_callback(task_run, phase="scheduled")-- def _dispatch() -> None:- observe_task_run_dispatch_callback(task_run, phase="fired")- execute_task_processing_workflow(- task_id=task_id,- run_id=run_id,- team_id=team_id,- user_id=user_id,- create_pr=create_pr,- slack_thread_context=slack_thread_context,- posthog_mcp_scopes=posthog_mcp_scopes,- workflow_id_prefix=workflow_id_prefix,+ with transaction.atomic():+ task_run = task.create_run(mode=mode, extra_state=run_extra_state or None, branch=branch)++ if start_workflow:+ # 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.+ # on_commit runs the callback immediately in autocommit mode, so non-atomic callers+ # are unaffected. If the callback is lost (process recycled in the commit->callback+ # window, or an earlier on_commit hook raising), the run stays QUEUED — the periodic+ # reconciler re-dispatches it from the persisted pending_dispatch above.+ execute_after_commit(lambda: observe_task_run_dispatch_callback(task_run, phase="scheduled"))+ enqueue_or_start_workflow(+ task_run,+ options=WorkflowDispatchOptions(+ user_id=user_id,+ create_pr=create_pr,+ slack_thread_context=_normalize_slack_context(slack_thread_context),+ posthog_mcp_scopes=posthog_mcp_scopes,+ workflow_id_prefix=workflow_id_prefix,+ ),)- transaction.on_commit(_dispatch)-return task@@ -2570,6 +2579,51 @@ class TaskRun(models.Model):raise Exception("Cannot delete TaskRun. Task runs are immutable records.")+class TaskWorkflowDispatch(TeamScopedRootMixin):+ class Kind(models.TextChoices):+ CREATE = "create", "create"+ RESTART = "restart", "restart"++ class Status(models.TextChoices):+ PENDING = "pending", "pending"+ CLAIMED = "claimed", "claimed"+ ACCEPTED = "accepted", "accepted"+ DEAD = "dead", "dead"++ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, db_index=False)+ task_run = models.ForeignKey(TaskRun, on_delete=models.CASCADE, related_name="workflow_dispatches", db_index=False)+ workflow_id = models.CharField(max_length=512)+ dispatch_kind = models.CharField(max_length=16, choices=Kind.choices)+ payload = models.JSONField(default=dict)+ status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)+ attempt_count = models.PositiveIntegerField(default=0)+ enqueued_at = models.DateTimeField(default=django_timezone.now)+ next_attempt_at = models.DateTimeField(default=django_timezone.now)+ claimed_by = models.CharField(max_length=128, blank=True, default="")+ lease_expires_at = models.DateTimeField(null=True, blank=True)+ accepted_at = models.DateTimeField(null=True, blank=True)+ last_error = models.TextField(blank=True, default="")+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_taskworkflowdispatch"+ constraints = [+ models.UniqueConstraint(fields=["task_run", "dispatch_kind"], name="uniq_dispatch_per_run_kind"),+ models.CheckConstraint(+ name="accepted_at_iff_accepted",+ condition=models.Q(status="accepted", accepted_at__isnull=False)+ | (~models.Q(status="accepted") & models.Q(accepted_at__isnull=True)),+ ),+ ]+ 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=["team", "created_at"], name="twd_team_created"),+ ]++class TaskArtifact(TeamScopedRootMixin, UUIDModel):class ArtifactType(models.TextChoices):SLACK_MESSAGE = "slack_message", "Slack message"diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex d46138de94e8..487715fd1301 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -33,7 +33,7 @@ from products.tasks.backend.temporal.process_task.workflow import PendingFollowufrom products.tasks.backend.temporal.slack_relay.activities import RelaySlackMessageInputif TYPE_CHECKING:- from products.slack_app.backend.slack_thread import SlackThreadContext+ passlogger = logging.getLogger(__name__)@@ -281,7 +281,7 @@ def execute_task_processing_workflow(team_id: int,user_id: Optional[int] = None,create_pr: bool = True,- slack_thread_context: Optional["SlackThreadContext"] = None,+ slack_thread_context: Optional[Any] = None,skip_user_check: bool = False,posthog_mcp_scopes: PosthogMcpScopes = "read_only",prewarmed: bool = False,diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 4eb332e6902d..e2a47821ad13 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -744,7 +744,8 @@ class TestTaskRun(TestCase):@patch("products.tasks.backend.models.publish_task_run_stream_event")def test_create_run_seeds_stream_state_event(self, mock_publish_stream_event):- run = self.task.create_run(branch="main")+ with self.captureOnCommitCallbacks(execute=True):+ run = self.task.create_run(branch="main")mock_publish_stream_event.assert_called_once()call_args = mock_publish_stream_event.call_args@@ -1023,7 +1024,8 @@ class TestTaskRun(TestCase):)def test_task_run_created_carries_loop_attribution(self, _name, extra_state, expected_loop_id, expected_trigger_id):with patch("products.tasks.backend.models.posthoganalytics.capture") as mock_capture:- self.task.create_run(extra_state=extra_state or None)+ with self.captureOnCommitCallbacks(execute=True):+ self.task.create_run(extra_state=extra_state or None)created = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "task_run_created"]self.assertEqual(len(created), 1)props = created[0].kwargs["properties"]diff --git a/products/tasks/backend/tests/test_task_run_metrics.py b/products/tasks/backend/tests/test_task_run_metrics.pyindex bc81d06eebd5..b014df0c49ac 100644--- a/products/tasks/backend/tests/test_task_run_metrics.py+++ b/products/tasks/backend/tests/test_task_run_metrics.py@@ -60,10 +60,11 @@ class TestTaskRunMetrics(TestCase):}before = _sample_value("posthog_tasks_task_run_created_total", labels)- self.task.create_run(- environment=TaskRun.Environment.CLOUD,- extra_state={"run_source": "manual", "runtime_adapter": "codex"},- )+ with self.captureOnCommitCallbacks(execute=True):+ self.task.create_run(+ environment=TaskRun.Environment.CLOUD,+ extra_state={"run_source": "manual", "runtime_adapter": "codex"},+ )assert _sample_value("posthog_tasks_task_run_created_total", labels) == before + 1@@ -79,11 +80,12 @@ class TestTaskRunMetrics(TestCase):}before = _sample_value("posthog_tasks_task_run_created_total", labels)- self.task.create_run(- environment=TaskRun.Environment.CLOUD,- mode="custom-mode",- extra_state={"run_source": "custom-source", "runtime_adapter": "custom-adapter"},- )+ with self.captureOnCommitCallbacks(execute=True):+ self.task.create_run(+ environment=TaskRun.Environment.CLOUD,+ mode="custom-mode",+ extra_state={"run_source": "custom-source", "runtime_adapter": "custom-adapter"},+ )assert _sample_value("posthog_tasks_task_run_created_total", labels) == before + 1@@ -114,7 +116,8 @@ class TestTaskRunMetrics(TestCase):}before = _sample_value("posthog_tasks_task_run_created_total", labels)- self.task.create_run(environment=TaskRun.Environment.CLOUD)+ with self.captureOnCommitCallbacks(execute=True):+ self.task.create_run(environment=TaskRun.Environment.CLOUD)assert _sample_value("posthog_tasks_task_run_created_total", labels) == before + 1@@ -130,11 +133,12 @@ class TestTaskRunMetrics(TestCase):}before = _sample_value("posthog_tasks_task_run_created_total", labels)- self.task.create_run(- environment=TaskRun.Environment.CLOUD,- mode="interactive",- extra_state={"await_user_message": True, "prewarmed": True},- )+ with self.captureOnCommitCallbacks(execute=True):+ self.task.create_run(+ environment=TaskRun.Environment.CLOUD,+ mode="interactive",+ extra_state={"await_user_message": True, "prewarmed": True},+ )assert _sample_value("posthog_tasks_task_run_created_total", labels) == before + 1diff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.pynew file mode 100644index 000000000000..ef74fb716e0f--- /dev/null+++ b/products/tasks/backend/tests/test_workflow_dispatch.py@@ -0,0 +1,121 @@+import asyncio+from typing import cast++from unittest.mock import Mock, patch++from django.test import SimpleTestCase++from parameterized import parameterized++from products.tasks.backend.logic.services.workflow_dispatch import (+ WorkflowDispatchOptions,+ build_create_payload,+ create_dispatch,+ parse_create_payload,+ reschedule,+)+from products.tasks.backend.management.commands.run_task_workflow_dispatcher import Command, _user_can_dispatch+from products.tasks.backend.metrics import WORKFLOW_DISPATCH_ATTEMPT_TOTAL+from products.tasks.backend.temporal.process_task.workflow import PendingFollowup+++class TestWorkflowDispatchPayload(SimpleTestCase):+ @patch("products.tasks.backend.logic.services.workflow_dispatch.transaction.get_connection")+ @patch("products.tasks.backend.logic.services.workflow_dispatch.TaskWorkflowDispatch.objects")+ def test_duplicate_create_dispatch_reuses_durable_intent(self, objects: Mock, get_connection: Mock) -> None:+ get_connection.return_value.in_atomic_block = True+ task_run = Mock(team_id=1)+ existing = Mock()+ queryset = objects.for_team.return_value+ queryset.get_or_create.return_value = (existing, False)++ result = create_dispatch(task_run, "create", {"version": 1}, "workflow-id")++ self.assertIs(result, existing)+ queryset.get_or_create.assert_called_once()+ queryset.update_or_create.assert_not_called()++ def test_create_payload_round_trip_preserves_followup_without_secrets(self) -> None:+ options = WorkflowDispatchOptions(+ user_id=42,+ create_pr=False,+ posthog_mcp_scopes="full",+ slack_thread_context={"channel_id": "C1"},+ prewarmed=True,+ initial_message=PendingFollowup(+ message="continue",+ artifact_ids=["artifact-1"],+ actor_user_id=42,+ message_id="message-1",+ ),+ )++ payload = build_create_payload(options)++ self.assertEqual(parse_create_payload(payload), options)+ self.assertNotIn("imported_mcp_servers", payload)++ def test_unknown_payload_version_is_rejected(self) -> None:+ payload = build_create_payload(WorkflowDispatchOptions())+ payload["version"] = 2++ with self.assertRaisesRegex(ValueError, "Unsupported workflow dispatch payload version"):+ parse_create_payload(payload)++ @patch("products.tasks.backend.logic.services.workflow_dispatch.TaskWorkflowDispatch.objects")+ @patch("products.tasks.backend.logic.services.workflow_dispatch.random.uniform", return_value=1.0)+ def test_reschedule_clamps_exponential_backoff(self, uniform: Mock, objects: Mock) -> None:+ objects.unscoped.return_value.get.return_value.attempt_count = 10_000++ reschedule("dispatch-id", "instance-id", "error")++ uniform.assert_called_once_with(1.0, 256.0)+++class TestWorkflowDispatchPermissions(SimpleTestCase):+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.UserPermissions")+ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.User.objects")+ def test_user_requires_current_effective_team_access(self, users: Mock, permissions: Mock) -> None:+ user = users.filter.return_value.first.return_value+ permissions.return_value.current_team.effective_membership_level = None+ run = Mock(task=Mock(team=Mock()))++ self.assertFalse(_user_can_dispatch(run, WorkflowDispatchOptions(user_id=42)))+ users.filter.assert_called_once_with(id=42, is_active=True)+ permissions.assert_called_once_with(user=user, team=run.task.team)++ @patch("products.tasks.backend.management.commands.run_task_workflow_dispatcher.User.objects")+ def test_trusted_system_dispatch_skips_user_lookup(self, users: Mock) -> None:+ run = Mock(task=Mock(team=Mock()))++ self.assertTrue(_user_can_dispatch(run, WorkflowDispatchOptions(skip_user_check=True)))+ users.filter.assert_not_called()+++class TestDispatcherCompletionCallback(SimpleTestCase):+ @parameterized.expand(+ [+ ("failure", RuntimeError("connection reset"), 1),+ ("success", None, 0),+ ]+ )+ def test_completion_records_failure_outcome_only_on_exception(+ self, name: str, exception: Exception | None, expected_delta: int+ ) -> None:+ task_mock = Mock()+ task_mock.cancelled.return_value = False+ task_mock.exception.return_value = exception+ task = cast(asyncio.Task[None], task_mock)+ dispatch = Mock(id=f"dispatch-{name}", task_run_id="run-1", dispatch_kind="create")+ in_flight = {task}+ in_flight_ids = {dispatch.id}++ def failed_total() -> float:+ return WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind="create", outcome="failed")._value.get()++ before = failed_total()+ Command._on_dispatch_done(in_flight, in_flight_ids, dispatch, task)++ self.assertEqual(failed_total() - before, expected_delta)+ self.assertNotIn(task, in_flight)+ self.assertNotIn(dispatch.id, in_flight_ids)