: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): bind wizard PRs to their run via a server-generated head branch (#69591)
Fernando Gomes70d44c271263
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 8224271a2493..7b2abfbefeab 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -63,7 +63,7 @@ from products.tasks.backend.models import (TaskThreadMessage,TaskThreadMessageMention,)-from products.tasks.backend.prompts import WIZARD_PR_AGENT_PROMPT+from products.tasks.backend.prompts import build_wizard_pr_agent_prompt, generate_wizard_head_branchfrom products.tasks.backend.visibility import task_control_q, task_run_visibility_q, task_visibility_qfrom . import contracts@@ -765,11 +765,17 @@ def create_wizard_cloud_run(``user_id`` is the person going through onboarding; it becomes the task's ``created_by`` so therun is explicitly attributed to them.++ The PR head branch is generated here (not by the agent) so the GitHub PR webhook can bind the+ opened PR back to this run by branch + repository — wizard PRs are bot-authored, which the+ agent-side PR attribution cannot match."""+ head_branch = generate_wizard_head_branch()+ prompt = build_wizard_pr_agent_prompt(head_branch)return create_and_run_task(team=team,title="Set up PostHog",- description=WIZARD_PR_AGENT_PROMPT,+ description=prompt,origin_product=Task.OriginProduct.ONBOARDING,user_id=user_id,repository=repository,@@ -777,10 +783,11 @@ def create_wizard_cloud_run(mode="background",branch=branch,wizard_config={},+ wizard_head_branch=head_branch,posthog_mcp_scopes="read_only",# The agent server boots idle; this is the message that actually kicks it off once ready# (delivered by forward_pending_user_message). Without it the run stalls after "Started agent".- pending_user_message=WIZARD_PR_AGENT_PROMPT,+ pending_user_message=prompt,)@@ -1457,6 +1464,7 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("sandbox_ttl_seconds","inactivity_timeout_seconds","wizard_config",+ "wizard_head_branch","use_modal_directory_resume_snapshots","snapshot_external_id","snapshot_kind",@@ -3735,6 +3743,12 @@ def run_task(extra_state["resume_from_run_id"] = str(resume_from_run_id)extra_state.update(prev_state.resume_snapshot_carry_state())+ # The resumed agent still pushes the head branch baked into the original prompt, so the+ # PR webhook must be able to match this run, not the terminal predecessor.+ prev_wizard_head_branch = (previous_run.state or {}).get("wizard_head_branch")+ if prev_wizard_head_branch:+ extra_state["wizard_head_branch"] = prev_wizard_head_branch+if prev_state.sandbox_environment_id and sandbox_environment_id is None:sandbox_environment_id = prev_state.sandbox_environment_iddiff --git a/products/tasks/backend/migrations/0054_taskrun_wizard_branch_idx.py b/products/tasks/backend/migrations/0054_taskrun_wizard_branch_idx.pynew file mode 100644index 000000000000..7e695a8b59fc--- /dev/null+++ b/products/tasks/backend/migrations/0054_taskrun_wizard_branch_idx.py@@ -0,0 +1,23 @@+import django.db.models.fields.json+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("tasks", "0053_sandboxcustomimage_build_log"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="taskrun",+ index=models.Index(+ django.db.models.fields.json.KeyTransform("wizard_head_branch", "state"),+ name="task_run_wizard_branch_idx",+ condition=models.Q(state__wizard_head_branch__isnull=False),+ ),+ ),+ ]diff --git a/products/tasks/backend/migrations/max_migration.txt b/products/tasks/backend/migrations/max_migration.txtindex 183d708d3e09..6e6ce63652ef 100644--- a/products/tasks/backend/migrations/max_migration.txt+++ b/products/tasks/backend/migrations/max_migration.txt@@ -1 +1 @@-0053_sandboxcustomimage_build_log+0054_taskrun_wizard_branch_idxdiff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex d58fb7988158..9c183ef485a5 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -432,6 +432,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):sandbox_timeout_seconds: int | None = None,inactivity_timeout_seconds: int | None = None,wizard_config: dict | None = None,+ wizard_head_branch: str | None = None,pending_user_message: str | None = None,custom_image_builder_id: str | None = None,custom_image_id: str | None = None,@@ -599,6 +600,13 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):# Wizard runs must boot the agent only after the wizard step.extra_state["overlap_clone_boot_enabled"] = False+ # Server-generated head branch the agent is instructed to push to, so the GitHub PR+ # webhook can bind the opened PR back to this run (webhooks.find_task_run). Kept out of+ # TaskRun.branch, which means "branch to check out at provisioning" — not "branch the+ # agent will create".+ if wizard_head_branch:+ extra_state["wizard_head_branch"] = wizard_head_branch+# The first message handed to the agent once its server is ready (forward_pending_user_message# reads it from run state). Without it a background run boots the agent idle — it never gets a# prompt and just sits there while relay_sandbox_events waits for events that never come.@@ -688,6 +696,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):inactivity_timeout_seconds: int | None = None,ai_stage: str | None = None,wizard_config: dict | None = None,+ wizard_head_branch: str | None = None,pending_user_message: str | None = None,custom_image_builder_id: str | None = None,custom_image_id: str | None = None,@@ -718,6 +727,7 @@ class Task(FileSystemSyncMixin, DeletedMetaFields, models.Model):inactivity_timeout_seconds=inactivity_timeout_seconds,ai_stage=ai_stage,wizard_config=wizard_config,+ wizard_head_branch=wizard_head_branch,pending_user_message=pending_user_message,custom_image_builder_id=custom_image_builder_id,custom_image_id=custom_image_id,@@ -1018,6 +1028,13 @@ class TaskRun(models.Model):name="task_run_output_pr_url_idx",condition=models.Q(output__pr_url__isnull=False),),+ # Same shape for the wizard-run webhook leg `filter(state__wizard_head_branch=...)`;+ # only wizard runs carry the key, so the index stays tiny.+ models.Index(+ KeyTransform("wizard_head_branch", "state"),+ name="task_run_wizard_branch_idx",+ condition=models.Q(state__wizard_head_branch__isnull=False),+ ),# Time-range scans over runs (default ordering, recent-runs lookups, and the# signals outcome-billing query that buckets PR runs into a period).models.Index(fields=["created_at"], name="task_run_created_at_idx"),@@ -1424,6 +1441,18 @@ class TaskRun(models.Model):backend decides grouping granularity by picking a phase id (e.g.`"setup"`, `"pr_create"`)."""+ event = self.build_progress_event(step, status, label, group, detail)+ self.append_log([event])+ self.publish_stream_event(event)++ def build_progress_event(+ self,+ step: str,+ status: str,+ label: str,+ group: str,+ detail: Optional[str] = None,+ ) -> dict[str, Any]:params: dict[str, Any] = {"sessionId": str(self.id),"step": step,@@ -1433,7 +1462,7 @@ class TaskRun(models.Model):}if detail is not None:params["detail"] = detail- event = {+ return {"type": "notification","timestamp": django_timezone.now().isoformat(),"notification": {@@ -1442,8 +1471,6 @@ class TaskRun(models.Model):"params": params,},}- self.append_log([event])- self.publish_stream_event(event)def emit_sandbox_output(self, stdout: str, stderr: str, exit_code: int) -> None:"""Emit sandbox execution output as ACP notification."""diff --git a/products/tasks/backend/prompts.py b/products/tasks/backend/prompts.pyindex ce8dbdde0e8e..ab61236599cb 100644--- a/products/tasks/backend/prompts.py+++ b/products/tasks/backend/prompts.py@@ -1,3 +1,5 @@+import secrets+SHELL_EFFICIENCY_INSTRUCTION = """\Shell efficiency: optimize for the fewest shell round trips.- Batch related commands into one Bash invocation using `&&` (e.g. `npm run typecheck && npm run lint && npm test`).@@ -5,6 +7,19 @@ Shell efficiency: optimize for the fewest shell round trips.- Read multiple files at once.- Never rerun a command solely to reproduce output you already have."""+# Sentinel swapped for the run's server-generated head branch by build_wizard_pr_agent_prompt.+# A .replace() sentinel (not str.format) because the prompt body is full of literal braces.+WIZARD_HEAD_BRANCH_PLACEHOLDER = "<wizard-head-branch>"++WIZARD_HEAD_BRANCH_PREFIX = "posthog/instrumentation-"+++def generate_wizard_head_branch() -> str:+ """A unique PR head branch for a wizard run; the random suffix only prevents+ collisions with existing branches in the user's repo."""+ return f"{WIZARD_HEAD_BRANCH_PREFIX}{secrets.token_hex(3)}"++WIZARD_PR_AGENT_PROMPT = f"""# Context@@ -58,9 +73,9 @@ are actually in the repository.## Step 2 - Commit the wizard's changes to a new branch-1. Create a branch named `posthog/instrumentation-<random-short-sha>`, where- `<random-short-sha>` is a random 6-character hex string you generate (NOT the HEAD- commit SHA). Its only purpose is to keep this branch from clashing with an existing branch.+1. Create a branch named exactly `{WIZARD_HEAD_BRANCH_PLACEHOLDER}`. This name was+ pre-generated for this run and PostHog uses it to link the pull request back to the+ setup progress — do NOT choose a different branch name.2. Look at `git log` to learn this repository's commit message convention.3. Commit the wizard's changes in that style; the message should resemble the concept of"Add PostHog to codebase". For example, in a repo using conventional commits:@@ -72,11 +87,11 @@ are actually in the repository.4. Do NOT commit `posthog-setup-report.md` or `.posthog-events.json` - they are local referenceonly. Leave them untracked or exclude them from staging.-**Checkpoint:** the commit exists on `posthog/instrumentation-<random-short-sha>` and+**Checkpoint:** the commit exists on `{WIZARD_HEAD_BRANCH_PLACEHOLDER}` andcontains neither reference file:```bash-git rev-parse --abbrev-ref HEAD # prints: posthog/instrumentation-<random-short-sha>+git rev-parse --abbrev-ref HEAD # prints: {WIZARD_HEAD_BRANCH_PLACEHOLDER}git show --stat HEAD # lists the wizard's filesgit show --stat HEAD | grep -E 'posthog-setup-report|posthog-events|wizard-output' && echo "FAIL: forbidden files committed" || echo "OK: no forbidden files"# expected: OK: no forbidden files (the grep finding nothing is the pass case)@@ -255,3 +270,13 @@ unrelated to the integration and documented in a PR comment.{SHELL_EFFICIENCY_INSTRUCTION}"""+++def build_wizard_pr_agent_prompt(head_branch: str) -> str:+ """The wizard PR agent prompt with the run's server-generated head branch baked in.++ The branch must be known before the agent runs so the GitHub PR webhook can bind the+ opened PR back to the TaskRun (see webhooks.find_task_run); letting the agent invent+ the name made that binding impossible.+ """+ return WIZARD_PR_AGENT_PROMPT.replace(WIZARD_HEAD_BRANCH_PLACEHOLDER, head_branch)diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex a2701be52760..e9f0a38c7aa7 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -18,7 +18,7 @@ from products.tasks.backend.facade import (warm as warm_facade,)from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRun-from products.tasks.backend.prompts import WIZARD_PR_AGENT_PROMPT+from products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PLACEHOLDER, build_wizard_pr_agent_promptFACADE_MODULES = ["products.tasks.backend.facade.api",@@ -449,7 +449,16 @@ class TestFacadeReadsAndMappers(TestCase):run = TaskRun.objects.get(task_id=created.task_id)# The agent server boots idle; forward_pending_user_message only kicks it off if the run state# carries the prompt. Without this the cloud wizard stalls right after "Started agent".- self.assertEqual(run.state.get("pending_user_message"), WIZARD_PR_AGENT_PROMPT)+ head_branch = run.state.get("wizard_head_branch")+ # Server-generated head branch: the GitHub PR webhook binds the opened PR back to this+ # run by matching it (wizard PRs are bot-authored, so agent-side attribution can't).+ # Losing the state key or leaving the placeholder untemplated in the prompt silently+ # unbinds every wizard PR again.+ assert head_branch is not None+ self.assertRegex(head_branch, r"^posthog/instrumentation-[0-9a-f]{6}$")+ self.assertEqual(run.state.get("pending_user_message"), build_wizard_pr_agent_prompt(head_branch))+ self.assertIn(f"`{head_branch}`", run.state["pending_user_message"])+ self.assertNotIn(WIZARD_HEAD_BRANCH_PLACEHOLDER, run.state["pending_user_message"])# The agent-server self-delivers pending_user_message the moment it boots, so an# overlap-clone-boot launch (before run_wizard) burns the prompt on an untouched repo# and the run never opens a PR. Wizard runs must pin the overlap boot off.diff --git a/products/tasks/backend/tests/test_migration_0050.py b/products/tasks/backend/tests/test_migration_0050.pyindex 94d1da47d30b..8030a1ee588e 100644--- a/products/tasks/backend/tests/test_migration_0050.py+++ b/products/tasks/backend/tests/test_migration_0050.py@@ -1,9 +1,9 @@from typing import Any-from posthog.test.base import TestMigrations+from posthog.test.base import NonAtomicTestMigrations-class BackfillThreadMessageMentionsMigrationTest(TestMigrations):+class BackfillThreadMessageMentionsMigrationTest(NonAtomicTestMigrations):"""0050 indexes mentions already stored inline in existing thread messages. The backfillmust mirror write-time extraction: org members only, self-mentions skipped, created_atcopied from the message.@@ -12,6 +12,8 @@ class BackfillThreadMessageMentionsMigrationTest(TestMigrations):migrate_from = "0049_taskthreadmessagemention"migrate_to = "0050_backfill_thread_message_mentions"+ CLASS_DATA_LEVEL_SETUP = False+@propertydef app(self) -> str:return "tasks"diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex 5c9e432ccbb8..b659e2288f24 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -230,6 +230,36 @@ class TestGitHubPRWebhook(TestCase):assert run.output is not Noneself.assertEqual(run.output["pr_url"], pr_url)+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_opened_backfills_pr_url_on_wizard_head_branch_match(self, mock_capture, mock_get_secret):+ mock_get_secret.return_value = self.webhook_secret+ run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ branch="main",+ state={"wizard_head_branch": "posthog/instrumentation-ab12cd"},+ output={},+ )+ pr_url = "https://github.com/posthog/posthog/pull/778"+ payload = {+ "action": "opened",+ "pull_request": {+ "html_url": pr_url,+ "merged": False,+ "head": {"ref": "posthog/instrumentation-ab12cd", "repo": {"full_name": "posthog/posthog"}},+ },+ "repository": {"full_name": "posthog/posthog"},+ }++ response = self._make_webhook_request(payload)+ self.assertEqual(response.status_code, 200)++ run.refresh_from_db()+ assert run.output is not None+ self.assertEqual(run.output["pr_url"], pr_url)+@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")@patch("products.tasks.backend.models.posthoganalytics.capture")def test_pr_opened_from_fork_does_not_backfill_pr_url(self, mock_capture, mock_get_secret):@@ -746,6 +776,35 @@ class TestFindTaskRun(TestCase):)self.assertEqual(result, branch_run)+ def test_finds_wizard_run_by_state_head_branch(self):+ # Wizard cloud runs never have the PR head branch in TaskRun.branch (that column is+ # the checkout base); the server-generated head branch lives in run state. Dropping+ # this match leg silently unbinds every wizard PR from its run again.+ wizard_run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ branch="main",+ state={"wizard_head_branch": "posthog/instrumentation-ab12cd"},+ )+ result = find_task_run(branch="posthog/instrumentation-ab12cd", repository="posthog/posthog")+ self.assertEqual(result, wizard_run)+ # Same branch name from a foreign repository must not be attributed to this run.+ self.assertIsNone(find_task_run(branch="posthog/instrumentation-ab12cd", repository="acme/other"))+ # The run's `branch` column holds the checkout base, so a same-repo PR whose head+ # ref equals it must not claim the wizard run through the plain branch leg.+ self.assertIsNone(find_task_run(branch="main", repository="posthog/posthog"))++ def test_wizard_head_branch_leg_ignores_terminal_runs(self):+ # A reopened/re-PR'd wizard branch months later must not fire events on a dead run.+ TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.COMPLETED,+ state={"wizard_head_branch": "posthog/instrumentation-dead00"},+ )+ self.assertIsNone(find_task_run(branch="posthog/instrumentation-dead00", repository="posthog/posthog"))+def test_returns_none_when_no_match(self):result = find_task_run(pr_url="https://github.com/posthog/posthog/pull/999")self.assertIsNone(result)diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex c7f9d026cb41..08fa4b92b603 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -15,6 +15,7 @@ from posthog.models.team.team import Teamfrom products.signals.backend.models import InvalidStatusTransition, SignalReportfrom products.tasks.backend.models import TaskRun+from products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIXlogger = structlog.get_logger(__name__)@@ -36,14 +37,39 @@ def find_task_run(# (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+ # otherwise claim the run before the dedicated leg below is consulted.task_run = (- TaskRun.objects.filter(branch=branch, task__repository__iexact=repository)+ TaskRun.objects.filter(+ branch=branch,+ task__repository__iexact=repository,+ state__wizard_head_branch__isnull=True,+ ).select_related(*TASK_RUN_SELECT_RELATED).first())if task_run:return task_run+ # Wizard cloud runs push to a server-generated head branch stored in run state.+ # The prefix check keeps this leg off the hot path for ordinary PR webhooks, and+ # terminal runs are excluded so a reopened branch can't fire events on a dead run+ # (post-merge events for bound runs resolve via the pr_url leg above).+ if branch.startswith(WIZARD_HEAD_BRANCH_PREFIX):+ task_run = (+ TaskRun.objects.filter(+ state__wizard_head_branch=branch,+ task__repository__iexact=repository,+ task__deleted=False,+ )+ .exclude(status__in=(TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED))+ .select_related(*TASK_RUN_SELECT_RELATED)+ .first()+ )+ if task_run:+ return task_run+return None@@ -158,7 +184,20 @@ def _record_run_pr_url(task_run: TaskRun, pr_url: str) -> None:``output.pr_url`` stays empty, so inbox notifications, the CI follow-up loop,and later webhook lookups never resolve the PR."""- _record_run_output_field(task_run, "pr_url", pr_url, "github_pr_webhook_record_pr_url_failed")+ if not _record_run_output_field(task_run, "pr_url", pr_url, "github_pr_webhook_record_pr_url_failed"):+ return+ # Publish-only (no append_log): the S3 run log has a live writer — the agent is streaming+ # log batches at exactly this moment — and append_log's read-modify-write would race it.+ # Tolerant: a stream hiccup must not fail the webhook; clients recover on refetch.+ try:+ for event in (+ task_run.build_progress_event("pr", "completed", "Opened pull request", "setup", detail=pr_url),+ task_run.build_progress_event("ci", "in_progress", "Keeping CI green", "setup"),+ ):+ task_run.publish_stream_event(event)+ task_run.publish_stream_state_event()+ except Exception:+ logger.warning("github_pr_webhook_pr_events_failed", run_id=str(task_run.id), exc_info=True)def _record_run_pr_merged(task_run: TaskRun) -> None:@@ -171,26 +210,29 @@ def _record_run_pr_merged(task_run: TaskRun) -> None:_record_run_output_field(task_run, "pr_merged", True, "github_pr_webhook_record_pr_merged_failed")-def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, failure_log_event: str) -> None:+def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, failure_log_event: str) -> bool:"""Idempotently merge ``{key: value}`` into a run's ``output`` JSON under a row lock.- Tolerant: a failure here must not fail the webhook (GitHub retries 5xx, and the event is- already handled).+ Returns True only when this call performed the write, so callers can fire follow-on+ side effects exactly once. Tolerant: a failure here must not fail the webhook (GitHub+ retries 5xx, and the event is already handled)."""if isinstance(task_run.output, dict) and task_run.output.get(key):- return+ return Falsetry:with transaction.atomic():locked = TaskRun.objects.select_for_update().get(id=task_run.id)output = locked.output if isinstance(locked.output, dict) else {}if output.get(key):- return+ return Falselocked.output = {**output, key: value}locked.save(update_fields=["output", "updated_at"])# Keep the in-memory instance consistent for the rest of this request.task_run.output = locked.output+ return Trueexcept Exception:logger.warning(failure_log_event, run_id=str(task_run.id), exc_info=True)+ return False# Nulled on external PRs so their schema matches task-originated PR events.