:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): give every workflow start durable dispatch intent (#86255)
Alessandro Pogliaghi688e97c254ba
diff --git a/ee/hogai/sandbox/executor.py b/ee/hogai/sandbox/executor.pyindex 5decdbc73d6c..890d3385926f 100644--- a/ee/hogai/sandbox/executor.py+++ b/ee/hogai/sandbox/executor.py@@ -24,7 +24,7 @@ from posthog.temporal.common.client import sync_connectfrom products.posthog_ai.backend.models.assistant import Conversationfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.streams import TaskRunRedisStream, TaskRunStreamError, get_task_run_stream_key-from products.tasks.backend.facade.temporal import ProcessTaskWorkflow, execute_task_processing_workflow+from products.tasks.backend.facade.temporal import ProcessTaskWorkflow, dispatch_task_processing_workflowfrom ee.hogai.api.serializers import ConversationMinimalSerializerfrom ee.hogai.sandbox.mapping import get_sandbox_mapping, set_sandbox_mapping@@ -102,7 +102,7 @@ def handle_sandbox_message(set_sandbox_mapping(conversation_id, str(task_run.task_id), run_id)- execute_task_processing_workflow(+ dispatch_task_processing_workflow(task_id=str(task_run.task_id),run_id=run_id,team_id=task_run.team_id,diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex 780d5424a242..60750ca01d66 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -507,7 +507,7 @@ def create_posthog_code_task_for_repo_activity(from products.slack_app.backend.models import SlackThreadTaskMappingfrom products.slack_app.backend.slack_thread import SlackThreadContextfrom products.tasks.backend.facade import api as tasks_facade- from products.tasks.backend.facade.temporal import execute_task_processing_workflow+ from products.tasks.backend.facade.temporal import dispatch_task_processing_workflowintegration = Integration.objects.select_related("team", "team__organization").get(id=inputs.integration_id,@@ -746,7 +746,7 @@ def create_posthog_code_task_for_repo_activity(# 3. Now start the workflowif task_run:- execute_task_processing_workflow(+ dispatch_task_processing_workflow(task_id=str(created.task_id),run_id=str(task_run.id),team_id=created.team_id,@@ -1087,7 +1087,7 @@ def _resume_task_with_new_run(from products.slack_app.backend.services.slack_messages import decode_slack_event_text # noqa: PLC0415from products.slack_app.backend.slack_thread import SlackThreadContextfrom products.tasks.backend.facade import api as tasks_facade- from products.tasks.backend.facade.temporal import execute_task_processing_workflow+ from products.tasks.backend.facade.temporal import dispatch_task_processing_workflowintegration = slack.integrationuser_text = decode_slack_event_text(slack, integration, event_text)@@ -1222,7 +1222,7 @@ def _resume_task_with_new_run()try:- execute_task_processing_workflow(+ dispatch_task_processing_workflow(task_id=str(mapping.task_id),run_id=str(new_run.id),team_id=new_run.team_id,diff --git a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.pyindex b8b054609836..19e68197abe7 100644--- a/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py+++ b/posthog/temporal/ai/slack_app/eval_slack_repo_selection.py@@ -64,10 +64,10 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Literal-# Must run as `python posthog/temporal/ai/eval_slack_repo_selection.py` (not `python -m ...`):+# Must run as `python posthog/temporal/ai/slack_app/eval_slack_repo_selection.py` (not `python -m ...`):# `python -m` would import `posthog/temporal/ai/__init__.py` first, which loads workflows that# reference Django models before django.setup() has a chance to fire.-_repo_root = Path(__file__).resolve().parents[3]+_repo_root = Path(__file__).resolve().parents[4]if str(_repo_root) not in sys.path:sys.path.insert(0, str(_repo_root))diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.pyindex 4a9eeeea6e28..3c25ebfdba37 100644--- a/posthog/test/test_middleware.py+++ b/posthog/test/test_middleware.py@@ -2059,9 +2059,11 @@ def test_chqueries_middleware_tags_source(user_agent, expected_source):from django.http import HttpResponsefrom django.test import RequestFactory- from posthog.clickhouse.query_tagging import get_query_tags+ from posthog.clickhouse.query_tagging import get_query_tags, reset_query_tagsfrom posthog.middleware import CHQueries+ reset_query_tags()+captured: dict = {}def get_response(req):diff --git a/products/posthog_ai/backend/message_routing.py b/products/posthog_ai/backend/message_routing.pyindex 9ddccf1277d7..1ac5ec8c5e1f 100644--- a/products/posthog_ai/backend/message_routing.py+++ b/products/posthog_ai/backend/message_routing.py@@ -40,7 +40,7 @@ from products.tasks.backend.facade import (warm as warm_facade,)from products.tasks.backend.facade.run_config import INITIAL_PERMISSION_MODE_CHOICES, InitialPermissionMode-from products.tasks.backend.facade.temporal import execute_task_processing_workflow, signal_task_followup_message+from products.tasks.backend.facade.temporal import dispatch_task_processing_workflow, signal_task_followup_messageif TYPE_CHECKING:from products.tasks.backend.models import TaskRun@@ -333,7 +333,7 @@ class SandboxSession(BaseSandboxService):# rather than a follow-up onto a run that never started; on a conversion, also revert the# runtime flip so the user is left on a clean idle LangGraph conversation.try:- execute_task_processing_workflow(+ dispatch_task_processing_workflow(task_id=str(created.task_id),run_id=str(run_dto.id),team_id=self.team.id,@@ -468,7 +468,7 @@ class SandboxSession(BaseSandboxService):# Same write scopes as the first message — the resumed agent keeps creating# insights/dashboards/notebooks on follow-up turns.- execute_task_processing_workflow(+ dispatch_task_processing_workflow(task_id=str(task.id),run_id=str(new_run.id),team_id=self.team.id,diff --git a/products/posthog_ai/backend/tests/test_message_routing.py b/products/posthog_ai/backend/tests/test_message_routing.pyindex 8bdb871812de..3a5b74a84a3f 100644--- a/products/posthog_ai/backend/tests/test_message_routing.py+++ b/products/posthog_ai/backend/tests/test_message_routing.py@@ -51,7 +51,7 @@ class TestOpenSandboxMessage(APIBaseTest):def _patches(self, task: Task):return (patch.object(Task, "create_and_run", return_value=task),- patch(f"{ROUTING}.execute_task_processing_workflow"),+ patch(f"{ROUTING}.dispatch_task_processing_workflow"),patch.object(PromptService, "build", return_value=SYS_PROMPT),)@@ -263,7 +263,7 @@ class TestOpenSandboxMessage(APIBaseTest):self._attach_task(task)with (- patch(f"{ROUTING}.execute_task_processing_workflow") as m_workflow,+ patch(f"{ROUTING}.dispatch_task_processing_workflow") as m_workflow,patch.object(PromptService, "build", return_value=SYS_PROMPT),):result = self._service().open({"content": "resume please", "trace_id": "trace-3"})@@ -299,7 +299,7 @@ class TestOpenSandboxMessage(APIBaseTest):self._attach_task(task)with (- patch(f"{ROUTING}.execute_task_processing_workflow"),+ patch(f"{ROUTING}.dispatch_task_processing_workflow"),patch.object(PromptService, "build", return_value=SYS_PROMPT),patch(f"{ROUTING}.object_storage.read", return_value=""),):@@ -350,7 +350,7 @@ class TestOpenSandboxMessage(APIBaseTest):with (patch(f"{ROUTING}.lock_conversation_for_followup", side_effect=lock_granted_after_concurrent_winner),- patch(f"{ROUTING}.execute_task_processing_workflow") as m_workflow,+ patch(f"{ROUTING}.dispatch_task_processing_workflow") as m_workflow,patch.object(PromptService, "build", return_value=SYS_PROMPT),):with self.assertRaises(Conflict):@@ -378,7 +378,7 @@ class TestOpenSandboxMessage(APIBaseTest):with (patch(f"{ROUTING}.lock_conversation_for_followup", side_effect=lock_granted_after_winner_finished),- patch(f"{ROUTING}.execute_task_processing_workflow"),+ patch(f"{ROUTING}.dispatch_task_processing_workflow"),patch.object(PromptService, "build", return_value=SYS_PROMPT),):result = self._service().open({"content": "resume please"})@@ -676,7 +676,7 @@ class TestSandboxFirstMessageConversion(APIBaseTest):return "<posthog_context>This session was resumed from the legacy implementation.\nUser: hi</posthog_context>"def _open(self, *, resumed_context=None, convert_to_acp=False, content="continue here"):- with patch(f"{ROUTING}.execute_task_processing_workflow") as m_workflow:+ with patch(f"{ROUTING}.dispatch_task_processing_workflow") as m_workflow:result = SandboxSession(self.conversation, self.user).open({"content": content, "trace_id": "t"},resumed_context=resumed_context,@@ -739,7 +739,7 @@ class TestSandboxFirstMessageConversion(APIBaseTest):assert self.conversation.task_id == other_task.iddef test_first_message_conversion_reverts_on_workflow_start_failure(self):- with patch(f"{ROUTING}.execute_task_processing_workflow", side_effect=RuntimeError("boom")):+ with patch(f"{ROUTING}.dispatch_task_processing_workflow", side_effect=RuntimeError("boom")):with self.assertRaises(RuntimeError):SandboxSession(self.conversation, self.user).open({"content": "continue here", "trace_id": "t"},diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.pyindex c700801ed30e..34a224f34cbd 100644--- a/products/slack_app/backend/tests/test_followup_forwarding.py+++ b/products/slack_app/backend/tests/test_followup_forwarding.py@@ -197,7 +197,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):bot_id_patcher.start()self.addCleanup(bot_id_patcher.stop)- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_no_repo_task_starts_with_pr_creation_enabled(self, mock_slack_cls, mock_execute_workflow):mock_slack_instance = MagicMock()@@ -242,7 +242,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert mapping.task_id == task.idassert mapping.task_run_id == task.latest_run.id- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_initial_task_uploads_slack_attachment_to_pending_prompt(self, mock_slack_cls, mock_execute_workflow@@ -301,7 +301,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert mock_write.call_args.args[1] == b"log bytes"mock_execute_workflow.assert_called_once()- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_existing_mapping_skips_duplicate_task_creation(self, mock_slack_cls, mock_execute_workflow):"""A retried activity (or a concurrent duplicate mention) must not create a@@ -348,7 +348,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert mapping.task_run_id == existing_run.idmock_execute_workflow.assert_not_called()- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_persists_explicit_event_id_in_workflow_id(self, mock_slack_cls, mock_execute_workflow):mock_slack_instance = MagicMock()@@ -379,7 +379,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):task = self.Task.objects.get(team=self.team)assert task.latest_run.state["slack_mention_workflow_id"] == "posthog-code-mention-T_SLACK:Ev01234567"- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_persists_repo_research_ids_when_provided(self, mock_slack_cls, mock_execute_workflow):mock_slack_instance = MagicMock()@@ -408,7 +408,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert state["repo_research_task_id"] == "11111111-1111-1111-1111-111111111111"assert state["repo_research_run_id"] == "22222222-2222-2222-2222-222222222222"- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_no_repo_research_ids_when_not_provided(self, mock_slack_cls, mock_execute_workflow):# The unambiguous path (explicit mention / cascade auto) never runs the@@ -436,7 +436,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert "repo_research_task_id" not in task.latest_run.stateassert "repo_research_run_id" not in task.latest_run.state- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_no_repo_task_falls_back_to_team_github_integration(self, mock_slack_cls, mock_execute_workflow):Integration.objects.create(team=self.team, kind="github", integration_id="12345", config={})@@ -466,7 +466,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert task.latest_run.state["pr_authorship_mode"] == "bot"mock_execute_workflow.assert_called_once()- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_no_repo_task_falls_back_to_team_github_integration_when_user_token_unusable(self, mock_slack_cls, mock_execute_workflow@@ -505,7 +505,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert task.latest_run.state["pr_authorship_mode"] == "bot"mock_execute_workflow.assert_called_once()- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_no_repo_task_prefers_user_github_integration(self, mock_slack_cls, mock_execute_workflow):UserIntegration.objects.create(@@ -547,7 +547,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):# below cover the surrounding activity wiring: Slack permalink, mapping, workflow# start, quota blocking, etc.- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_description_is_wired_to_slack_thread_context_helper(self, mock_slack_cls, mock_execute_workflow):# Smoke-test that the activity calls into the helper and persists the result —@@ -580,7 +580,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):assert "</slack_thread_context>" in task.descriptionassert task.description.endswith("do something")- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")@patch("ee.billing.quota_limiting.is_team_limited", return_value=True)def test_quota_exceeded_blocks_task_creation_with_thread_message(@@ -683,7 +683,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert result is True_assert_quota_denial_posted(mock_slack_instance, "C123", "1234.5678")- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_terminal_run_resumes_same_task(self, mock_slack_cls, mock_execute_workflow):self.task_run.status = self.TaskRun.Status.COMPLETED@@ -727,7 +727,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):)mock_slack_instance.client.chat_postMessage.assert_not_called()- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_terminal_run_resumes_with_slack_attachment(self, mock_slack_cls, mock_execute_workflow) -> None:self.task_run.status = self.TaskRun.Status.COMPLETED@@ -774,7 +774,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert new_run.artifacts[0]["name"] == "resume.txt"assert new_run.artifacts[0]["source"] == "slack_user_attachment"- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_terminal_no_repo_run_resumes_with_pr_creation_enabled(self, mock_slack_cls, mock_execute_workflow):self.task.repository = None@@ -793,7 +793,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):mock_execute_workflow.assert_called_once()assert mock_execute_workflow.call_args.kwargs["create_pr"] is True- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_terminal_run_seeds_pr_context_into_new_run_prompt(self, mock_slack_cls, mock_execute_workflow):self.task_run.status = self.TaskRun.Status.COMPLETED@@ -816,7 +816,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert "slack_pr_opened_notified" not in new_run.stateassert "slack_notified_pr_url" not in new_run.state- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_terminal_failed_run_resumes_with_structured_recovery_prompt(self, mock_slack_cls, mock_execute_workflow):self.task_run.status = self.TaskRun.Status.FAILED@@ -885,7 +885,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):call_kwargs = mock_slack_instance.client.chat_postMessage.call_args.kwargsassert "original task creator" in call_kwargs["text"]- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow", side_effect=Exception("boom"))+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow", side_effect=Exception("boom"))@patch("posthog.models.integration.SlackIntegration")def test_terminal_run_workflow_start_failure_returns_true_with_error(self, mock_slack_cls, mock_execute_workflow):self.task_run.status = self.TaskRun.Status.COMPLETED@@ -993,7 +993,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):mock_resolve.assert_called_once_with(mock_slack_instance, self.integration, "U_BOB", "C123", "1234.5678")mock_slack_instance.client.chat_postMessage.assert_not_called()- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("products.slack_app.backend.api.resolve_slack_user")@patch("posthog.models.integration.SlackIntegration")def test_cross_user_terminal_run_resume_prefixes_actor_name(@@ -1023,7 +1023,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert new_run.state["slack_actor_user_id"] == bob.idassert new_run.state["slack_actor_slack_user_id"] == "U_BOB"- @patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow")+ @patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow")@patch("posthog.models.integration.SlackIntegration")def test_a_resumed_run_carries_the_model_the_workspace_would_pick(self, mock_slack_cls, mock_execute_workflow):# `create_run` builds a fresh state, so without this the follow-up reached the@@ -1185,7 +1185,7 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):with (patch("posthog.models.integration.SlackIntegration") as mock_slack_cls,- patch("products.tasks.backend.facade.temporal.execute_task_processing_workflow") as mock_execute_workflow,+ patch("products.tasks.backend.facade.temporal.dispatch_task_processing_workflow") as mock_execute_workflow,patch("products.tasks.backend.logic.services.agent_command.send_user_message") as mock_send,patch("posthog.storage.object_storage.write") as mock_write,):diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 3bb620482e58..cd5e3d4c36c4 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -1069,7 +1069,11 @@ def filter_uncovered_workflow_dispatch_run_ids(candidate_ids: list[UUID]) -> lisreturn uncovered_idsruns = {run.id: run- for run in TaskRun.objects.filter(id__in=uncovered_ids) # nosemgrep: celery-task-team-scope-audit+ for run in TaskRun.objects.filter(+ id__in=uncovered_ids+ ).select_related( # nosemgrep: celery-task-team-scope-audit+ "task"+ )}dispatch_run_ids = set(TaskWorkflowDispatch.objects.unscoped()@@ -1078,9 +1082,20 @@ def filter_uncovered_workflow_dispatch_run_ids(candidate_ids: list[UUID]) -> lis)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:+ state = run.state if run and isinstance(run.state, dict) else {}+ has_legacy_intent = bool(state.get("pending_dispatch"))+ awaiting_restart_rollout = bool(state.get("handoff_resumed"))+ if run_id not in dispatch_run_ids and not has_legacy_intent and not awaiting_restart_rollout:WORKFLOW_DISPATCH_MISSING_INTENT_TOTAL.inc()+ logger.warning(+ "workflow_dispatch_missing_intent",+ extra={+ "run_id": str(run_id),+ "task_id": str(run.task_id) if run else None,+ "team_id": run.team_id if run else None,+ "origin_product": run.task.origin_product if run else None,+ },+ )return uncovered_ids@@ -7899,25 +7914,6 @@ def request_canvas_change(return outcome-def _dispatch_server_run(*, team_id: int, user_id: int | None, task_id: str, run_id: str) -> None:- """Dispatch a server-originated run's processing workflow, bypassing the per-user check.-- Nothing canvas-specific: kept here because ``temporal.client`` puts temporalio on- its import path and this module must not.- """- from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path- execute_task_processing_workflow,- )-- execute_task_processing_workflow(- task_id=task_id,- run_id=run_id,- team_id=team_id,- user_id=user_id,- skip_user_check=True,- )--_GITHUB_PR_PATH_PATTERN = re.compile(r"/([^/]+)/([^/]+)/pull/(\d+)/?", re.IGNORECASE)# Characters that could break out of a markdown [label](url) token or smugglediff --git a/products/tasks/backend/facade/temporal.py b/products/tasks/backend/facade/temporal.pyindex 3caf36972471..3f52929d6f01 100644--- a/products/tasks/backend/facade/temporal.py+++ b/products/tasks/backend/facade/temporal.py@@ -7,6 +7,7 @@ metric config, and callers trigger a run via ``execute_task_processing_workflow`from ``facade/api.py`` so ``temporalio`` never lands on the light data-surface import path."""+from products.tasks.backend.logic.services.workflow_dispatch import dispatch_task_processing_workflowfrom products.tasks.backend.temporal import ACTIVITIES, WORKFLOWSfrom products.tasks.backend.temporal.client import (execute_posthog_code_agent_relay_workflow,@@ -36,6 +37,7 @@ __all__ = ["WORKFLOWS","PostSlackUpdateInput","ProcessTaskWorkflow",+ "dispatch_task_processing_workflow","execute_posthog_code_agent_relay_workflow","execute_task_processing_workflow","execute_task_processing_workflow_async",diff --git a/products/tasks/backend/logic/services/workflow_dispatch.py b/products/tasks/backend/logic/services/workflow_dispatch.pyindex 20aa203f6e75..e6ddda8c3b41 100644--- a/products/tasks/backend/logic/services/workflow_dispatch.py+++ b/products/tasks/backend/logic/services/workflow_dispatch.py@@ -2,7 +2,7 @@ import randomfrom collections.abc import Callablefrom dataclasses import asdictfrom datetime import datetime, timedelta-from typing import Any+from typing import Any, Protocolfrom django.db import close_old_connections, transactionfrom django.db.models import Count, F, Min, Q@@ -53,6 +53,10 @@ class WorkflowDispatchFlags:async_enabled: bool+class SlackThreadContextLike(Protocol):+ def to_dict(self) -> dict[str, Any]: ...++def build_create_payload(options: WorkflowDispatchOptions) -> dict[str, Any]:return {"version": DISPATCH_PAYLOAD_VERSION,@@ -61,6 +65,7 @@ def build_create_payload(options: WorkflowDispatchOptions) -> dict[str, Any]:"posthog_mcp_scopes": options.posthog_mcp_scopes,"slack_thread_context": options.slack_thread_context,"prewarmed": options.prewarmed,+ "skip_user_check": options.skip_user_check,"initial_message": asdict(options.initial_message) if options.initial_message else None,}@@ -75,6 +80,7 @@ def parse_create_payload(payload: dict[str, Any]) -> WorkflowDispatchOptions:posthog_mcp_scopes=payload["posthog_mcp_scopes"],slack_thread_context=payload.get("slack_thread_context"),prewarmed=payload.get("prewarmed", False),+ skip_user_check=payload.get("skip_user_check", False),initial_message=PendingFollowup(**initial_message) if initial_message else None,)@@ -313,6 +319,7 @@ def enqueue_or_start_workflow(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}+ dispatch_written = Falseif 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)@@ -324,6 +331,7 @@ def enqueue_or_start_workflow(create_dispatch(locked_run, TaskWorkflowDispatch.Kind.CREATE, build_create_payload(options), workflow_id)+ dispatch_written = Trueif flags.async_enabled:return@@ -348,6 +356,8 @@ def enqueue_or_start_workflow(workflow_kwargs["initial_message"] = options.initial_messageif options.skip_user_check:workflow_kwargs["skip_user_check"] = True+ if dispatch_written:+ workflow_kwargs["durable_dispatch"] = Truestart_workflow(**workflow_kwargs)execute_after_commit(start_synchronously)@@ -357,3 +367,33 @@ async def aenqueue_or_start_workflow(task_run: TaskRun, *, options: WorkflowDispfrom asgiref.sync import sync_to_asyncawait sync_to_async(enqueue_or_start_workflow)(task_run, options=options)+++def dispatch_task_processing_workflow(+ task_id: str,+ run_id: str,+ team_id: int,+ user_id: int | None = None,+ create_pr: bool = True,+ slack_thread_context: "SlackThreadContextLike | dict[str, Any] | None" = None,+ skip_user_check: bool = False,+ posthog_mcp_scopes: PosthogMcpScopes = "read_only",+) -> None:+ """Outbox-aware drop-in for ``execute_task_processing_workflow`` when the caller did not create the run itself."""+ if slack_thread_context is None or isinstance(slack_thread_context, dict):+ normalized_context = slack_thread_context+ else:+ normalized_context = slack_thread_context.to_dict()+ task_run = TaskRun.objects.select_related("task", "task__team", "task__created_by").get(+ id=run_id, task_id=task_id, team_id=team_id+ )+ enqueue_or_start_workflow(+ task_run,+ options=WorkflowDispatchOptions(+ user_id=user_id,+ create_pr=create_pr,+ slack_thread_context=normalized_context,+ posthog_mcp_scopes=posthog_mcp_scopes,+ skip_user_check=skip_user_check,+ ),+ )diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex e723d68a9fbd..987095e30a05 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -1056,16 +1056,15 @@ class Task(DeletedMetaFields, models.Model):# Read by TaskProcessingContext.github_read_access: provisioning injects a read-only# GitHub token into the (repo-less) sandbox instead of the full credential path.run_extra_state["github_read_access"] = True- if start_workflow:- # Persist everything the dispatch needs alongside the row, in the same INSERT, so a- # reconciler can re-dispatch faithfully if the on_commit callback below is ever lost.- run_extra_state["pending_dispatch"] = {- "create_pr": create_pr,- "posthog_mcp_scopes": posthog_mcp_scopes,- "user_id": user_id,- "slack_thread_context": _normalize_slack_context(slack_thread_context),- "workflow_id_prefix": workflow_id_prefix,- }+ # Persist everything the dispatch needs alongside the row, in the same INSERT, so a+ # reconciler can re-dispatch faithfully if the workflow start is ever lost.+ run_extra_state["pending_dispatch"] = {+ "create_pr": create_pr,+ "posthog_mcp_scopes": posthog_mcp_scopes,+ "user_id": user_id,+ "slack_thread_context": _normalize_slack_context(slack_thread_context),+ "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)diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex 487715fd1301..125f7059716d 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -10,6 +10,7 @@ from django.utils import timezone as django_timezoneimport posthoganalyticsfrom asgiref.sync import sync_to_asyncfrom temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.models.team.team import Teamfrom posthog.temporal.common.client import async_connect, sync_connect@@ -201,10 +202,14 @@ async def execute_task_processing_workflow_async(prewarmed: bool = False,workflow_id_prefix: Optional[str] = None,initial_message: PendingFollowup | None = None,+ durable_dispatch: bool = False,) -> None:"""Start the task processing workflow asynchronously. Fire-and-forget.Use this from async contexts (e.g., within Temporal activities).++ ``durable_dispatch`` means an outbox row already covers this run, so a failed start+ leaves the run QUEUED for the dispatcher to retry instead of terminalizing it."""logger.info("execute_task_processing_workflow_async_called",@@ -263,12 +268,20 @@ async def execute_task_processing_workflow_async(run_id,f"Failed to start task workflow: permission validation failed: {e}",)+ except WorkflowAlreadyStartedError:+ observe_task_run_workflow_start(task_run_for_metrics, outcome="blocked", reason="already_running")+ logger.info(+ "task_processing_workflow_already_running",+ extra={"task_id": task_id, "run_id": run_id},+ )except Exception as e:observe_task_run_workflow_start(task_run_for_metrics, outcome="failed", reason="temporal_start")logger.exception("task_processing_workflow_start_failed",extra={"task_id": task_id, "run_id": run_id, "error": str(e)},)+ if durable_dispatch:+ returnawait _terminalize_unstarted_task_run_async(run_id,f"Failed to start task workflow: {e}",@@ -287,10 +300,14 @@ def execute_task_processing_workflow(prewarmed: bool = False,workflow_id_prefix: Optional[str] = None,initial_message: PendingFollowup | None = None,+ durable_dispatch: bool = False,) -> None:"""Start the task processing workflow synchronously. Fire-and-forget.Use this from sync contexts (e.g., API endpoints).++ ``durable_dispatch`` means an outbox row already covers this run, so a failed start+ leaves the run QUEUED for the dispatcher to retry instead of terminalizing it."""# Metrics lookups stay inside the try so a failure here can't bypass terminalization and# leave the run orphaned in QUEUED (see the async variant above).@@ -356,12 +373,20 @@ def execute_task_processing_workflow(run_id,f"Failed to start task workflow: permission validation failed: {e}",)+ except WorkflowAlreadyStartedError:+ observe_task_run_workflow_start(task_run_for_metrics, outcome="blocked", reason="already_running")+ logger.info(+ "task_processing_workflow_already_running",+ extra={"task_id": task_id, "run_id": run_id},+ )except Exception as e:observe_task_run_workflow_start(task_run_for_metrics, outcome="failed", reason="temporal_start")logger.exception("task_processing_workflow_start_failed",extra={"task_id": task_id, "run_id": run_id, "error": str(e)},)+ if durable_dispatch:+ return_terminalize_unstarted_task_run(run_id,f"Failed to start task workflow: {e}",diff --git a/products/tasks/backend/tests/test_workflow_dispatch.py b/products/tasks/backend/tests/test_workflow_dispatch.pyindex c4604f77ac94..16dba0e6a4da 100644--- a/products/tasks/backend/tests/test_workflow_dispatch.py+++ b/products/tasks/backend/tests/test_workflow_dispatch.py@@ -11,11 +11,13 @@ from django.utils import timezone as django_timezonefrom parameterized import parameterizedfrom temporalio.client import WorkflowExecutionStatus+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.models import Organization, Teamfrom posthog.models.user import Userfrom products.tasks.backend.facade.api import (+ create_and_run_task,filter_uncovered_workflow_dispatch_run_ids,get_stale_queued_task_run_ids,maintain_workflow_dispatch_outbox,@@ -23,11 +25,13 @@ from products.tasks.backend.facade.api import ()from products.tasks.backend.logic.services.workflow_dispatch import (RestartSnapshot,+ WorkflowDispatchFlags,WorkflowDispatchOptions,build_create_payload,build_restart_payload,create_dispatch,dispatch_exceeded_max_age,+ dispatch_task_processing_workflow,mark_dead,parse_create_payload,parse_restart_payload,@@ -41,6 +45,7 @@ from products.tasks.backend.management.commands.run_task_workflow_dispatcher imp)from products.tasks.backend.metrics import WORKFLOW_DISPATCH_ATTEMPT_TOTALfrom products.tasks.backend.models import Task, TaskRun, TaskWorkflowDispatch+from products.tasks.backend.temporal.client import execute_task_processing_workflowfrom products.tasks.backend.temporal.process_task.workflow import PendingFollowup@@ -80,6 +85,7 @@ class TestWorkflowDispatchPayload(SimpleTestCase):posthog_mcp_scopes="full",slack_thread_context={"channel_id": "C1"},prewarmed=True,+ skip_user_check=True,initial_message=PendingFollowup(message="continue",artifact_ids=["artifact-1"],@@ -255,6 +261,91 @@ class TestWorkflowDispatchPersistence(TestCase):self.assertEqual(uncovered, [self.task_run.id])increment_missing_intent.assert_not_called()+ @patch("products.tasks.backend.metrics.WORKFLOW_DISPATCH_MISSING_INTENT_TOTAL.inc")+ @patch("products.tasks.backend.facade.api.is_workflow_dispatch_shadow_enabled", return_value=True)+ def test_missing_intent_counts_bare_runs_but_not_restart_rollout_gaps(+ self, _shadow_enabled: Mock, increment_missing_intent: Mock+ ) -> None:+ resumed_run = TaskRun.objects.create(+ task=self.task_run.task, team=self.team, status=TaskRun.Status.QUEUED, state={"handoff_resumed": True}+ )++ uncovered = filter_uncovered_workflow_dispatch_run_ids([self.task_run.id, resumed_run.id])++ self.assertEqual(uncovered, [self.task_run.id, resumed_run.id])+ increment_missing_intent.assert_called_once()++ def test_deferred_start_create_and_run_persists_dispatch_marker(self) -> None:+ creator_id = self.task_run.task.created_by_id+ assert creator_id is not None+ created = create_and_run_task(+ team=self.team,+ title="Deferred start",+ description="Created without starting the workflow",+ origin_product=Task.OriginProduct.SLACK,+ user_id=creator_id,+ create_pr=False,+ mode="interactive",+ start_workflow=False,+ posthog_mcp_scopes="full",+ )++ assert created.latest_run is not None+ run = TaskRun.objects.get(id=created.latest_run.id)+ marker = run.state["pending_dispatch"]+ self.assertFalse(marker["create_pr"])+ self.assertEqual(marker["posthog_mcp_scopes"], "full")++ @parameterized.expand(+ [+ ("already_started_keeps_run_alive", WorkflowAlreadyStartedError("wf", "process-task"), False, "queued"),+ ("durable_dispatch_leaves_retry_to_dispatcher", RuntimeError("temporal down"), True, "queued"),+ ("no_durable_dispatch_terminalizes", RuntimeError("temporal down"), False, "failed"),+ ]+ )+ @patch("products.tasks.backend.temporal.client.sync_connect")+ def test_sync_start_failure_only_terminalizes_without_durable_dispatch(+ self, _name: str, error: Exception, durable_dispatch: bool, expected_status: str, connect: Mock+ ) -> None:+ connect.side_effect = error++ with self.captureOnCommitCallbacks(execute=True):+ execute_task_processing_workflow(+ task_id=str(self.task_run.task_id),+ run_id=str(self.task_run.id),+ team_id=self.team.id,+ durable_dispatch=durable_dispatch,+ )++ self.task_run.refresh_from_db()+ self.assertEqual(self.task_run.status, expected_status)++ def test_dispatch_facade_normalizes_slack_context_into_shadow_row(self) -> None:+ class Context:+ def to_dict(self) -> dict:+ return {"channel": "C1", "thread_ts": "123.45"}++ with (+ patch(+ "products.tasks.backend.logic.services.workflow_dispatch.evaluate_workflow_dispatch_flags",+ return_value=WorkflowDispatchFlags(shadow_enabled=True, async_enabled=False),+ ),+ patch("products.tasks.backend.temporal.client.execute_task_processing_workflow") as start,+ self.captureOnCommitCallbacks(execute=True),+ ):+ dispatch_task_processing_workflow(+ task_id=str(self.task_run.task_id),+ run_id=str(self.task_run.id),+ team_id=self.team.id,+ user_id=self.task_run.task.created_by_id,+ slack_thread_context=Context(),+ posthog_mcp_scopes="full",+ )++ row = TaskWorkflowDispatch.objects.unscoped().get(task_run=self.task_run)+ self.assertEqual(row.payload["slack_thread_context"], {"channel": "C1", "thread_ts": "123.45"})+ start.assert_called_once()+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(