: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): recover orphaned QUEUED runs via dispatch reconciler (#67305)
Alessandro Pogliaghif8bdc5373ec3
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 43153dab0cd7..27ad81bab4e8 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -58,6 +58,7 @@ from posthog.tasks.tasks import (process_scheduled_changes,redis_celery_queue_depth,redis_heartbeat,+ redispatch_orphaned_queued_task_runs,refresh_activity_log_fields_cache,send_org_usage_reports,start_poll_query_performance,@@ -249,6 +250,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="kill stale queued task runs",)+ # Re-dispatch orphaned QUEUED task runs whose on_commit dispatch was lost - every 2 minutes+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="*/2"),+ redispatch_orphaned_queued_task_runs.s(),+ name="redispatch orphaned queued task runs",+ )+# Flags cache sync - hourlysender.add_periodic_task(crontab(hour="*", minute="15"),diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 6dee9fa31fc4..367d78ad9308 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -64,6 +64,12 @@ STALE_QUEUED_TASK_RUN_ERRORS_COUNTER = Counter("Errors raised while marking a TaskRun FAILED in the stale-queued cleanup sweep",)+ORPHANED_QUEUED_TASK_RUN_RECONCILED_COUNTER = Counter(+ "posthog_task_run_orphaned_queued_reconciled_total",+ "Orphaned QUEUED TaskRuns handled by the dispatch reconciler, by outcome",+ labelnames=["outcome"],+)+# Separate from the stale-queued counters above so the 24h sweep and the prewarmed fast-reap# stay distinguishable in Prometheus (dashboards/alerts on the 24h sweep shouldn't absorb the# prewarmed reap rate).@@ -213,6 +219,57 @@ def kill_stale_queued_task_runs() -> None:)+@shared_task(ignore_result=True, soft_time_limit=110, time_limit=170)+def redispatch_orphaned_queued_task_runs() -> None:+ """Re-dispatch TaskRuns stranded in QUEUED because their create-time workflow dispatch was lost.++ ``Task.create_and_run`` starts the Temporal ``process-task`` workflow from a+ ``transaction.on_commit`` callback. If that callback never fires (the web process is recycled+ in the commit->callback window, or an earlier on_commit hook raises and Django skips the rest),+ the run stays QUEUED with no workflow — invisible to the workflow-start metrics — until the 24h+ killer marks it FAILED. This sweep recovers those runs in minutes instead: it re-dispatches every+ run QUEUED past a short grace window, reading the persisted dispatch params off the row. Prewarmed+ runs are left alone (``redispatch_task_run`` skips them) — the prewarmed reaper owns them.++ Recovery is idempotent and safe: ``ALLOW_DUPLICATE_FAILED_ONLY`` starts a workflow only when none+ is live, so a run whose workflow already exists (slow queue, row not yet flipped to IN_PROGRESS)+ is skipped rather than double-run. The reconciler never fails a run — the killer stays the only+ terminal path — so a transient Temporal error simply retries next sweep.+ """+ from products.tasks.backend.facade import api as tasks_facade++ BATCH_SIZE = 500+ # Grace window: normal dispatch flips QUEUED->IN_PROGRESS in well under a second, so a run still+ # QUEUED after this almost certainly lost its callback. Anything already dispatched is skipped by+ # the reuse policy regardless, so the window only bounds churn, not correctness.+ RECONCILE_AFTER = datetime.timedelta(minutes=5)++ # Janitor sweep is intentionally cross-team — it runs without a team context.+ candidate_ids = tasks_facade.get_stale_queued_task_run_ids(RECONCILE_AFTER, BATCH_SIZE)+ outcomes: dict[str, int] = {}+ for run_id in candidate_ids:+ try:+ outcome = tasks_facade.redispatch_task_run(run_id)+ except Exception as exc: # noqa: BLE001 - one run must not block the sweep+ outcome = "error"+ capture_exception(exc)+ outcomes[outcome] = outcomes.get(outcome, 0) + 1+ ORPHANED_QUEUED_TASK_RUN_RECONCILED_COUNTER.labels(outcome=outcome).inc()++ saturated = len(candidate_ids) >= BATCH_SIZE+ log = logger.warning if saturated else logger.info+ log(+ "redispatch_orphaned_queued_task_runs.sweep_done",+ candidates=len(candidate_ids),+ recovered=outcomes.get("recovered", 0),+ already_running=outcomes.get("already_running", 0),+ left_queue=outcomes.get("left_queue", 0),+ errors=outcomes.get("error", 0),+ batch_size=BATCH_SIZE,+ saturated=saturated,+ )++@shared_task(ignore_result=True)@skip_team_scope_auditdef clear_expired_sessions() -> None:diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 14a70ba266a6..fe35e33822f5 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -120,6 +120,7 @@'posthog.tasks.tasks.process_scheduled_changes','posthog.tasks.tasks.redis_celery_queue_depth','posthog.tasks.tasks.redis_heartbeat',+ 'posthog.tasks.tasks.redispatch_orphaned_queued_task_runs','posthog.tasks.tasks.refresh_activity_log_fields_cache','posthog.tasks.tasks.send_org_usage_reports','posthog.tasks.tasks.start_poll_query_performance',diff --git a/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py b/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.pynew file mode 100644index 000000000000..6f917ce10fd4--- /dev/null+++ b/posthog/tasks/test/test_redispatch_orphaned_queued_task_runs.py@@ -0,0 +1,82 @@+import datetime+from typing import TYPE_CHECKING, ClassVar++from unittest.mock import patch++from django.apps import apps+from django.test import TestCase+from django.utils import timezone++from posthog.models import Organization, Team+from posthog.tasks.tasks import redispatch_orphaned_queued_task_runs++if TYPE_CHECKING:+ from products.tasks.backend.models import Task, TaskRun+++class TestRedispatchOrphanedQueuedTaskRuns(TestCase):+ organization: ClassVar[Organization]+ team: ClassVar[Team]+ task: ClassVar["Task"]++ @classmethod+ def setUpTestData(cls) -> None:+ Task = apps.get_model("tasks", "Task")+ cls.organization = Organization.objects.create(name="Test Org")+ cls.team = Team.objects.create(organization=cls.organization, name="Test Team")+ cls.task = Task.objects.create(+ team=cls.team,+ title="Test Task",+ description="Test Description",+ origin_product=Task.OriginProduct.USER_CREATED,+ )++ def _queued_run(self, updated_age: datetime.timedelta) -> "TaskRun":+ TaskRun = apps.get_model("tasks", "TaskRun")+ run = TaskRun.objects.create(task=self.task, team=self.team, status=TaskRun.Status.QUEUED)+ now = timezone.now()+ TaskRun.objects.filter(pk=run.pk).update(created_at=now - updated_age, updated_at=now - updated_age)+ return run++ def test_redispatches_run_queued_past_grace_window(self) -> None:+ run = self._queued_run(datetime.timedelta(minutes=10))++ with patch(+ "products.tasks.backend.facade.api.redispatch_task_run", return_value="recovered"+ ) as mock_redispatch:+ redispatch_orphaned_queued_task_runs()++ mock_redispatch.assert_called_once_with(run.id)++ def test_leaves_run_within_grace_window_for_normal_dispatch(self) -> None:+ # Normal dispatch flips QUEUED->IN_PROGRESS in under a second; the reconciler must not+ # race it. A regression widening the grace to the killer's 24h would make this useless.+ self._queued_run(datetime.timedelta(minutes=1))++ with patch(+ "products.tasks.backend.facade.api.redispatch_task_run", return_value="recovered"+ ) as mock_redispatch:+ redispatch_orphaned_queued_task_runs()++ mock_redispatch.assert_not_called()++ def test_one_failure_does_not_block_the_sweep(self) -> None:+ self._queued_run(datetime.timedelta(minutes=10))+ self._queued_run(datetime.timedelta(minutes=11))++ call_count = {"n": 0}++ def flaky_redispatch(run_id: object) -> str:+ call_count["n"] += 1+ if call_count["n"] == 1:+ raise RuntimeError("synthetic failure")+ return "recovered"++ with (+ patch("products.tasks.backend.facade.api.redispatch_task_run", side_effect=flaky_redispatch),+ patch("posthog.tasks.tasks.capture_exception") as mock_capture,+ ):+ redispatch_orphaned_queued_task_runs()++ mock_capture.assert_called_once()+ self.assertEqual(call_count["n"], 2)diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex ca21ec872f43..7f2c3074767a 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -152,6 +152,7 @@ __all__ = ["read_task_run_artifact","read_task_run_logs","redeem_code_invite",+ "redispatch_task_run","refresh_team_code_workstreams","relay_task_run_message","reset_code_workflow_bindings",@@ -809,6 +810,19 @@ def claim_and_fail_stale_run(run_id: str | UUID, error: str) -> bool:return True+def redispatch_task_run(run_id: str | UUID) -> str:+ """Re-dispatch a QUEUED run whose create-time workflow dispatch was lost. Cross-team janitor call.++ Idempotent recover-only wrapper over the temporal client — never fails the run. Returns the+ outcome (``recovered`` / ``already_running`` / ``left_queue`` / ``error``).+ """+ from products.tasks.backend.temporal.client import ( # noqa: PLC0415 — keep temporalio off the api import path+ redispatch_orphaned_task_run,+ )++ return redispatch_orphaned_task_run(str(run_id))++def upsert_internal_sandbox_env(team_id: int,name: str,diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 683da7ba15c4..b7ecf6bd175e 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -40,6 +40,21 @@ TASK_RUN_WORKFLOW_START_TOTAL = Counter(],)+TASK_RUN_DISPATCH_CALLBACK_TOTAL = Counter(+ "posthog_tasks_task_run_dispatch_callback_total",+ "on_commit workflow-dispatch callback lifecycle: 'scheduled' when registered, 'fired' when it runs. "+ "scheduled minus fired is the count of lost callbacks that strand a run in QUEUED.",+ labelnames=[+ "origin_product",+ "run_environment",+ "mode",+ "run_source",+ "runtime_adapter",+ "prewarmed",+ "phase",+ ],+)+PREWARMED_ACTIVATED_TOTAL = Counter("posthog_tasks_prewarmed_activated_total","Pre-warmed Runs that received their first user message (the warm sandbox got used, not reaped)",@@ -183,6 +198,10 @@ def observe_task_run_created(task_run: "TaskRun") -> None:TASK_RUN_CREATED_TOTAL.labels(**_task_run_labels(task_run)).inc()+def observe_task_run_dispatch_callback(task_run: "TaskRun | None", *, phase: Literal["scheduled", "fired"]) -> None:+ TASK_RUN_DISPATCH_CALLBACK_TOTAL.labels(**_task_run_labels(task_run), phase=phase).inc()++def observe_task_run_workflow_start(task_run: "TaskRun | None",*,diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex cb5f52d4fb8b..63fe17d36431 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -42,7 +42,7 @@ from posthog.temporal.oauth import PosthogMcpScopesfrom products.tasks.backend.constants import DEFAULT_TRUSTED_DOMAINSfrom products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_event-from products.tasks.backend.metrics import observe_task_run_created+from products.tasks.backend.metrics import observe_task_run_created, observe_task_run_dispatch_callbackfrom products.tasks.backend.redis import evaluate_dedicated_stream_flag, run_uses_dedicated_streamlogger = structlog.get_logger(__name__)@@ -584,7 +584,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):wizard_config: dict | None = None,pending_user_message: str | None = None,) -> "Task":- from products.tasks.backend.temporal.client import execute_task_processing_workflow+ from products.tasks.backend.temporal.client import _normalize_slack_context, execute_task_processing_workflowtask, extra_state = Task._build_task(team=team,@@ -613,19 +613,36 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):pending_user_message=pending_user_message,)- task_run = task.create_run(mode=mode, extra_state=extra_state or None, branch=branch)+ run_extra_state = dict(extra_state or {})+ 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),+ }++ 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.+ # 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.idtask_id = str(task.id)- transaction.on_commit(- lambda: execute_task_processing_workflow(++ 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,@@ -634,7 +651,8 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):slack_thread_context=slack_thread_context,posthog_mcp_scopes=posthog_mcp_scopes,)- )++ transaction.on_commit(_dispatch)return taskdiff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.pyindex a7fa8e694345..3195aa09e3dc 100644--- a/products/tasks/backend/temporal/client.py+++ b/products/tasks/backend/temporal/client.py@@ -305,6 +305,89 @@ def execute_task_processing_workflow()+def _resolve_mcp_scopes(task_run: TaskRun) -> PosthogMcpScopes:+ """Mirror ``_trigger_task_processing_workflow``: full scopes unless the run_source is scoped down."""+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — avoid an import cycle+ RunSource,+ parse_run_state,+ )++ run_source = parse_run_state(task_run.state).run_source+ return "full" if run_source in (None, RunSource.MANUAL, RunSource.SIGNAL_REPORT) else "read_only"+++def redispatch_orphaned_task_run(run_id: str) -> str:+ """Re-dispatch a run stuck in QUEUED whose create-time on_commit dispatch never fired.++ Idempotent and recover-only: ``ALLOW_DUPLICATE_FAILED_ONLY`` starts a workflow only when+ none is live for this run, so a run that is already running (row not yet flipped to+ IN_PROGRESS) is left untouched. Never terminalizes the run — a transient Temporal failure+ just retries on the next sweep, and the 24h killer remains the only path that fails a run.++ Returns an outcome for metrics/logs: ``recovered`` (workflow started), ``already_running``+ (a workflow already exists), ``left_queue`` (row is no longer QUEUED), ``skipped_prewarmed``+ (owned by the prewarmed reaper), ``error`` (transient).+ """+ from temporalio.exceptions import WorkflowAlreadyStartedError # noqa: PLC0415 — keep temporalio off the import path++ task_run = (+ TaskRun.objects.select_related("task") # nosemgrep: celery-task-team-scope-audit+ .filter(id=run_id, status=TaskRun.Status.QUEUED)+ .first()+ )+ if task_run is None:+ return "left_queue"++ # Prewarmed runs idle in QUEUED awaiting the user's first message; the dedicated prewarmed+ # reaper *kills* them if never activated. Recovering one would boot an agent with no prompt+ # (and re-dispatching without the prewarmed flag would change its boot behaviour), so skip.+ if isinstance(task_run.state, dict) and task_run.state.get("prewarmed"):+ return "skipped_prewarmed"++ task = task_run.task+ task_id = str(task.id)+ workflow_id = TaskRun.get_workflow_id(task_id, run_id)+ # create_and_run persists these on the row; the bootstrap/start path does not, so fall back to+ # deriving mcp scopes from run_source exactly as _trigger_task_processing_workflow does.+ pending = task_run.state.get("pending_dispatch") if isinstance(task_run.state, dict) else None+ dispatch_params = pending if isinstance(pending, dict) else {}+ workflow_input = ProcessTaskInput(+ run_id=run_id,+ create_pr=dispatch_params.get("create_pr", True),+ slack_thread_context=dispatch_params.get("slack_thread_context"),+ posthog_mcp_scopes=dispatch_params.get("posthog_mcp_scopes") or _resolve_mcp_scopes(task_run),+ )++ observe_task_run_workflow_start(task_run, outcome="attempted", reason="reconcile")+ _capture_sandbox_event_ingest_flag(run_id)+ try:+ client = sync_connect()+ asyncio.run(+ client.start_workflow(+ "process-task",+ workflow_input,+ id=workflow_id,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ task_queue=settings.TASKS_TASK_QUEUE,+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ )+ except WorkflowAlreadyStartedError:+ observe_task_run_workflow_start(task_run, outcome="blocked", reason="reconcile_already_running")+ return "already_running"+ except Exception as e:+ observe_task_run_workflow_start(task_run, outcome="failed", reason="reconcile_error")+ logger.warning(+ "task_run_reconcile_dispatch_failed",+ extra={"run_id": run_id, "task_id": task_id, "error": str(e)},+ )+ return "error"++ observe_task_run_workflow_start(task_run, outcome="started", reason="reconcile")+ logger.info("task_run_reconcile_dispatch_started", extra={"run_id": run_id, "task_id": task_id})+ return "recovered"++def resume_task_in_cloud_workflow(run_id: str, workflow_id: str) -> None:_capture_sandbox_event_ingest_flag(run_id)client = sync_connect()diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex 8abf2f8ff5de..d474df166d14 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -309,6 +309,27 @@ class TestFacadeReadsAndMappers(TestCase):assert created.latest_run is not Noneself.assertEqual(created.latest_run.task_id, created.task_id)+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_create_and_run_persists_dispatch_params_for_reconcile(self, _mock_workflow):+ # The reconciler re-dispatches lost runs from the row alone, so the dispatch params+ # must be committed onto the run — not left only in the in-memory on_commit closure.+ Integration.objects.create(team=self.team, kind="github", config={})+ created = facade.create_and_run_task(+ team=self.team,+ title="Created via facade",+ description="desc",+ origin_product=facade.TaskOriginProduct.USER_CREATED,+ user_id=self.user.id,+ repository="posthog/posthog",+ create_pr=False,+ posthog_mcp_scopes="full",+ )+ assert created.latest_run is not None+ run = TaskRun.objects.get(id=created.latest_run.id)+ self.assertEqual(run.state["pending_dispatch"]["create_pr"], False)+ self.assertEqual(run.state["pending_dispatch"]["posthog_mcp_scopes"], "full")+ self.assertEqual(run.state["pending_dispatch"]["user_id"], self.user.id)+@patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")def test_create_wizard_cloud_run_seeds_pending_user_message(self, _mock_workflow):Integration.objects.create(team=self.team, kind="github", config={})diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.pyindex 0a3d1aec94e2..6c5000a4dcdd 100644--- a/products/tasks/backend/tests/test_temporal_client.py+++ b/products/tasks/backend/tests/test_temporal_client.py@@ -4,6 +4,8 @@ from django.test import TestCase, override_settingsfrom asgiref.sync import async_to_syncfrom parameterized import parameterized+from temporalio.common import WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom posthog.models import Organization, Teamfrom posthog.models.user import User@@ -12,6 +14,7 @@ from products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.temporal.client import (execute_task_processing_workflow,execute_task_processing_workflow_async,+ redispatch_orphaned_task_run,resume_task_in_cloud_workflow,)@@ -173,3 +176,121 @@ class TestExecuteTaskProcessingWorkflow(TestCase):run.refresh_from_db()self.assertEqual(run.state["pending_user_message_ids"], ["message-1"])self.assertEqual(run.state["sandbox_event_ingest_enabled"], True)+++@override_settings(DEBUG=False)+class TestRedispatchOrphanedTaskRun(TestCase):+ def setUp(self) -> None:+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create(email="[email protected]")+ self.task = Task.objects.create(+ team=self.team,+ created_by=self.user,+ title="Test Task",+ description="Test Description",+ origin_product=Task.OriginProduct.USER_CREATED,+ )++ def _orphaned_run(+ self, pending_dispatch: dict | None = None, run_source: str | None = None, prewarmed: bool = False+ ) -> TaskRun:+ state: dict = {}+ if pending_dispatch is not None:+ state["pending_dispatch"] = pending_dispatch+ if run_source is not None:+ state["run_source"] = run_source+ if prewarmed:+ state["prewarmed"] = True+ return TaskRun.objects.create(task=self.task, team=self.team, status=TaskRun.Status.QUEUED, state=state)++ def _run_reconcile(self, run: TaskRun, start_workflow: Mock) -> str:+ client = Mock()+ client.start_workflow = start_workflow+ with (+ patch("products.tasks.backend.temporal.client.sync_connect", return_value=client),+ patch("products.tasks.backend.temporal.client.posthoganalytics.feature_enabled", return_value=False),+ ):+ return redispatch_orphaned_task_run(str(run.id))++ def test_recovers_orphaned_run_with_persisted_dispatch_params(self) -> None:+ run = self._orphaned_run(pending_dispatch={"create_pr": False, "posthog_mcp_scopes": "full"})+ start_workflow = AsyncMock()++ outcome = self._run_reconcile(run, start_workflow)++ self.assertEqual(outcome, "recovered")+ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.QUEUED)+ self.assertIsNone(run.error_message)+ # Re-dispatch must be faithful to how the run was created and idempotent (start-if-none).+ _, workflow_input = start_workflow.call_args.args+ self.assertEqual(workflow_input.run_id, str(run.id))+ self.assertEqual(workflow_input.create_pr, False)+ self.assertEqual(workflow_input.posthog_mcp_scopes, "full")+ self.assertEqual(+ start_workflow.call_args.kwargs["id_reuse_policy"],+ WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ )++ @parameterized.expand([(None, "full"), ("manual", "full"), ("signal_report", "full")])+ def test_falls_back_to_run_source_scopes_when_dispatch_params_absent(+ self, run_source: str | None, expected_scopes: str+ ) -> None:+ # The app's bootstrap/start path never persists pending_dispatch, so the reconciler must+ # derive mcp scopes from run_source exactly as the original dispatch does — not default to read_only.+ run = self._orphaned_run(run_source=run_source)+ start_workflow = AsyncMock()++ outcome = self._run_reconcile(run, start_workflow)++ self.assertEqual(outcome, "recovered")+ _, workflow_input = start_workflow.call_args.args+ self.assertEqual(workflow_input.posthog_mcp_scopes, expected_scopes)++ def test_does_not_fail_run_when_workflow_already_started(self) -> None:+ run = self._orphaned_run()+ start_workflow = AsyncMock(side_effect=WorkflowAlreadyStartedError(run.workflow_id, "process-task"))++ outcome = self._run_reconcile(run, start_workflow)++ self.assertEqual(outcome, "already_running")+ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.QUEUED)+ self.assertIsNone(run.error_message)++ def test_does_not_fail_run_on_transient_error(self) -> None:+ run = self._orphaned_run()+ start_workflow = AsyncMock(side_effect=RuntimeError("temporal unavailable"))++ outcome = self._run_reconcile(run, start_workflow)++ self.assertEqual(outcome, "error")+ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.QUEUED)+ self.assertIsNone(run.error_message)+ self.assertIsNone(run.completed_at)++ def test_skips_run_that_left_queue(self) -> None:+ run = self._orphaned_run()+ run.status = TaskRun.Status.IN_PROGRESS+ run.save(update_fields=["status"])+ start_workflow = AsyncMock()++ outcome = self._run_reconcile(run, start_workflow)++ self.assertEqual(outcome, "left_queue")+ start_workflow.assert_not_called()++ def test_skips_prewarmed_run(self) -> None:+ # Prewarmed runs are owned by the prewarmed reaper (it kills them); re-dispatching one would+ # boot an agent with no user prompt and drop the prewarmed flag, changing boot behaviour.+ run = self._orphaned_run(prewarmed=True)+ start_workflow = AsyncMock()++ outcome = self._run_reconcile(run, start_workflow)++ self.assertEqual(outcome, "skipped_prewarmed")+ start_workflow.assert_not_called()+ run.refresh_from_db()+ self.assertEqual(run.status, TaskRun.Status.QUEUED)