: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): complete wizard cloud runs when their PR merges (#70071)
Fernando Gomes1520079b4b60
diff --git a/products/tasks/backend/temporal/process_task/README.md b/products/tasks/backend/temporal/process_task/README.mdindex a235b85664c9..5659dd8cee3f 100644--- a/products/tasks/backend/temporal/process_task/README.md+++ b/products/tasks/backend/temporal/process_task/README.md@@ -99,7 +99,7 @@ Environment variables consumed inside the sandbox:6. **start_agent_server** — Starts `npx agent-server` in sandbox, polls `/health` until ready7. **wait_condition** — Workflow blocks with a 2-hour inactivity timeout, extended by `heartbeat` signals from the agent. PostHog Code or the agent server signals completion via the API8. Agent server calls `PATCH /api/projects/{team_id}/task_runs/{run_id}/` with terminal status-9. API handler sends `complete_task(status, error_message)` signal to the Temporal workflow+9. API handler sends `complete_task(status, error_message)` signal to the Temporal workflow. For wizard cloud runs, the GitHub merge webhook sends the same signal (status `completed`) when the run's PR merges, so the run ends at merge instead of riding out the sandbox TTL10. **cleanup_sandbox** — Sandbox destroyed## Data modeldiff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex ae4bef67072d..ffe0d763b7d8 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -182,6 +182,111 @@ class TestGitHubPRWebhook(TestCase):run.refresh_from_db()self.assertEqual(run.output, {"pr_url": "https://github.com/posthog/posthog/pull/10"})+ def _merged_pr_payload(self, pr_url: str) -> dict:+ return {+ "action": "closed",+ "pull_request": {+ "html_url": pr_url,+ "merged": True,+ },+ }++ @parameterized.expand(+ [+ ("wizard_run_in_progress", {"wizard_config": {}}, TaskRun.Status.IN_PROGRESS, {}, 1),+ ("duplicate_merge_delivery", {"wizard_config": {}}, TaskRun.Status.IN_PROGRESS, {"pr_merged": True}, 0),+ ("non_wizard_run", {}, TaskRun.Status.IN_PROGRESS, {}, 0),+ ("already_terminal_run", {"wizard_config": {}}, TaskRun.Status.COMPLETED, {}, 0),+ ]+ )+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_merged_signals_wizard_workflow_completion(+ self, _name, state, status, extra_output, expected_signals, _mock_capture, mock_get_secret+ ):+ mock_get_secret.return_value = self.webhook_secret+ pr_url = "https://github.com/posthog/posthog/pull/777"+ run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=status,+ state=state,+ output={"pr_url": pr_url, **extra_output},+ )++ with patch("products.tasks.backend.webhooks.signal_workflow_completion") as mock_signal:+ with self.captureOnCommitCallbacks(execute=True):+ response = self._make_webhook_request(self._merged_pr_payload(pr_url))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(mock_signal.call_count, expected_signals)+ if expected_signals:+ mock_signal.assert_called_once_with(run.id, TaskRun.Status.COMPLETED, None)++ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_merged_resolves_to_active_run_when_resume_shares_pr(self, _mock_capture, mock_get_secret):+ # A resumed wizard run shares its predecessor's PR; the merge must land on the+ # live run (recording pr_merged and signaling wind-down), not the dead original.+ mock_get_secret.return_value = self.webhook_secret+ pr_url = "https://github.com/posthog/posthog/pull/779"+ active_run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"wizard_config": {}},+ output={"pr_url": pr_url},+ )+ terminal_run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.FAILED,+ state={"wizard_config": {}},+ output={"pr_url": pr_url},+ )+ payload = {+ "action": "closed",+ "pull_request": {"html_url": pr_url, "merged": True},+ "repository": {"full_name": "posthog/posthog"},+ }++ with patch("products.tasks.backend.webhooks.signal_workflow_completion") as mock_signal:+ with self.captureOnCommitCallbacks(execute=True):+ response = self._make_webhook_request(payload)++ self.assertEqual(response.status_code, 200)+ mock_signal.assert_called_once_with(active_run.id, TaskRun.Status.COMPLETED, None)+ active_run.refresh_from_db()+ terminal_run.refresh_from_db()+ assert active_run.output is not None and terminal_run.output is not None+ self.assertIs(active_run.output.get("pr_merged"), True)+ self.assertNotIn("pr_merged", terminal_run.output)++ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_merged_signal_failure_keeps_webhook_successful(self, _mock_capture, mock_get_secret):+ mock_get_secret.return_value = self.webhook_secret+ pr_url = "https://github.com/posthog/posthog/pull/778"+ run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"wizard_config": {}},+ output={"pr_url": pr_url},+ )++ with patch(+ "products.tasks.backend.webhooks.signal_workflow_completion",+ side_effect=RuntimeError("temporal unreachable"),+ ):+ with self.captureOnCommitCallbacks(execute=True):+ response = self._make_webhook_request(self._merged_pr_payload(pr_url))++ self.assertEqual(response.status_code, 200)+ run.refresh_from_db()+ assert run.output is not None+ self.assertIs(run.output.get("pr_merged"), True)+@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")@patch("products.tasks.backend.models.posthoganalytics.capture")def test_pr_closed_without_merge_webhook(self, mock_capture, mock_get_secret):@@ -754,6 +859,35 @@ class TestFindTaskRun(TestCase):result = find_task_run(pr_url="https://github.com/posthog/posthog/pull/123")self.assertEqual(result, task_run)+ def test_pr_url_prefers_active_run_over_terminal(self):+ # A resumed wizard run inherits its predecessor's head branch, so two runs can+ # claim the same PR URL; the lookup must resolve to the one still able to act.+ pr_url = "https://github.com/posthog/posthog/pull/321"+ active_run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ output={"pr_url": pr_url},+ )+ # Created later, so a purely newest-first lookup would wrongly pick this one.+ TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ output={"pr_url": pr_url},+ )+ self.assertEqual(find_task_run(pr_url=pr_url), active_run)++ def test_pr_url_does_not_match_other_repositories(self):+ pr_url = "https://github.com/posthog/posthog/pull/322"+ TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ output={"pr_url": pr_url},+ )+ self.assertIsNone(find_task_run(pr_url=pr_url, repository="acme/other"))+def test_finds_by_branch_when_no_pr_url_match(self):task_run = TaskRun.objects.create(task=self.task,diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex 440682a9ecdb..7ada9ba0e410 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -3,6 +3,7 @@ import uuidimport hashlibfrom django.db import transaction+from django.db.models import Case, IntegerField, Value, Whenfrom django.http import HttpResponseimport structlog@@ -14,6 +15,7 @@ from posthog.models.integration import Integrationfrom posthog.models.team.team import Teamfrom products.signals.backend.models import InvalidStatusTransition, SignalReport+from products.tasks.backend.facade.api import signal_workflow_completionfrom products.tasks.backend.models import TaskRunfrom products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIX@@ -21,21 +23,44 @@ logger = structlog.get_logger(__name__)TASK_RUN_SELECT_RELATED = ("task", "task__created_by", "team")+_TERMINAL_RUN_STATUSES = (TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED)+def find_task_run(pr_url: str | None = None,branch: str | None = None,repository: str | None = None,) -> TaskRun | None:+ repository = repository.strip() if repository else None+if pr_url:- task_run = TaskRun.objects.filter(output__pr_url=pr_url).select_related(*TASK_RUN_SELECT_RELATED).first()+ # A resumed wizard run inherits its predecessor's head branch, so a terminal+ # original and its live resume can both claim the same PR URL. Scope to the+ # webhook's repo and prefer non-terminal runs so merge handling lands on the+ # run that can still act on it.+ runs = TaskRun.objects.filter(output__pr_url=pr_url)+ if repository:+ runs = runs.filter(task__repository__iexact=repository)+ # Declared type keeps mypy happy: the annotated queryset yields an AnnotatedWith+ # variant that must not leak into the plain-queryset legs below.+ task_run: TaskRun | None = (+ runs.annotate(+ terminal_rank=Case(+ When(status__in=_TERMINAL_RUN_STATUSES, then=Value(1)),+ default=Value(0),+ output_field=IntegerField(),+ )+ )+ .order_by("terminal_rank", "-created_at")+ .select_related(*TASK_RUN_SELECT_RELATED)+ .first()+ )if task_run:return task_run# Branch-only lookups must be scoped to the repository the webhook came from.# Without this, a PR opened on an unrelated repo with a colliding branch name# (e.g. "main") gets attributed to whichever TaskRun shares that branch.- repository = repository.strip() if repository else Noneif branch and repository:# Wizard runs are excluded here: their `branch` column holds the checkout (base)# branch, so a same-repo PR whose head ref equals the base (e.g. "main") would@@ -63,7 +88,7 @@ def find_task_run(task__repository__iexact=repository,task__deleted=False,)- .exclude(status__in=(TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED))+ .exclude(status__in=_TERMINAL_RUN_STATUSES).select_related(*TASK_RUN_SELECT_RELATED).first())@@ -218,6 +243,34 @@ def _record_run_pr_merged(task_run: TaskRun) -> None:task_run.publish_stream_state_event()except Exception:logger.warning("github_pr_webhook_pr_merged_events_failed", run_id=str(task_run.id), exc_info=True)+ _complete_wizard_run_on_merge(task_run)+++def _complete_wizard_run_on_merge(task_run: TaskRun) -> None:+ """Wind down a wizard cloud run's Temporal workflow once its PR merges.++ A wizard run's only deliverable is its setup PR; once that merges, nothing is left for the+ sandbox to do, yet without this signal the workflow idles until the sandbox TTL expires and+ the onboarding UI reports the run as running for hours. Best-effort: the webhook must stay+ 2xx even if Temporal is unreachable or the workflow already finished.+ """+ state = task_run.state if isinstance(task_run.state, dict) else {}+ if "wizard_config" not in state:+ return+ if task_run.environment != TaskRun.Environment.CLOUD:+ return+ if task_run.status in _TERMINAL_RUN_STATUSES:+ return++ def _signal() -> None:+ try:+ signal_workflow_completion(task_run.id, TaskRun.Status.COMPLETED, None)+ except Exception:+ logger.warning("github_pr_webhook_wizard_completion_signal_failed", run_id=str(task_run.id), exc_info=True)++ # The pr_merged write has committed by the time the caller's atomic block exits; on_commit+ # keeps the signal after that commit even if this path ever runs inside an outer transaction.+ transaction.on_commit(_signal)def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, failure_log_event: str) -> bool: