Skip to content

: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.

fix(tasks): credit self-driving PR webhooks to the implementation run (#94313)

posthog[bot]a0f42076f136
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 6b248dc74bed..4b8bace2a2c8 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -808,6 +808,65 @@ class TestGitHubPRWebhook(TestCase):
run.refresh_from_db()
self.assertEqual(run.output, {})
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_pr_opened_prefers_self_driving_run_over_newer_reviewhog_run(self, mock_capture, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ head_branch = "posthog-self-driving/fix-thing-abc123"
+
+ impl_task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Implementation Task",
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ repository="posthog/posthog",
+ )
+ impl_run = TaskRun.objects.create(
+ task=impl_task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ branch="master",
+ state={"self_driving_head_branch": head_branch, "ai_stage": "implementation"},
+ output={},
+ )
+ # ReviewHog checks out the PR head branch to review it, and its run is newer.
+ review_task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="ReviewHog Task",
+ origin_product=Task.OriginProduct.REVIEW_HOG,
+ repository="posthog/posthog",
+ )
+ review_run = TaskRun.objects.create(
+ task=review_task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ branch=head_branch,
+ output={},
+ )
+
+ pr_url = "https://github.com/posthog/posthog/pull/950"
+ payload = {
+ "action": "opened",
+ "pull_request": {
+ "html_url": pr_url,
+ "merged": False,
+ "head": {"ref": head_branch, "repo": {"full_name": "posthog/posthog"}},
+ },
+ "repository": {"full_name": "posthog/posthog"},
+ }
+
+ response = self._make_webhook_request(payload)
+ self.assertEqual(response.status_code, 200)
+
+ impl_run.refresh_from_db()
+ review_run.refresh_from_db()
+ assert impl_run.output is not None
+ self.assertEqual(impl_run.output["pr_url"], pr_url)
+ self.assertEqual(impl_run.state["verified_pr_urls"], [pr_url])
+ self.assertEqual(review_run.output, {})
+ self.assertNotIn("verified_pr_urls", review_run.state or {})
+
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_opened_does_not_overwrite_existing_pr_url(self, mock_capture, mock_get_secret):
@@ -1621,6 +1680,40 @@ class TestFindTaskRun(TestCase):
)
self.assertEqual(find_task_run(pr_url=pr_url), active_run)
+ def test_pr_url_match_ignores_stale_reviewhog_claim(self):
+ # A ReviewHog run only holds a verified_pr_urls claim when an earlier branch match
+ # bound it wrongly, so the claim must not keep the PR's later events off the run
+ # that authored it.
+ pr_url = "https://github.com/posthog/posthog/pull/451"
+ head_branch = "posthog-self-driving/fix-thing-abc123"
+ implementation_run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ branch="master",
+ state={"self_driving_head_branch": head_branch},
+ )
+ review_task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Review task",
+ description="Review the implementation",
+ origin_product=Task.OriginProduct.REVIEW_HOG,
+ repository="posthog/posthog",
+ )
+ TaskRun.objects.create(
+ task=review_task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ branch=head_branch,
+ state={"verified_pr_urls": [pr_url]},
+ output={"pr_url": pr_url},
+ )
+
+ result = find_task_run(pr_url=pr_url, branch=head_branch, repository="posthog/posthog")
+
+ self.assertEqual(result, implementation_run)
+
def test_team_scope_excludes_runs_from_other_teams(self):
# team_ids comes from the delivery's installation. Every leg has to honour it, both
# so another customer's run can't be matched and so the scan rides the team_id index.
@@ -1680,6 +1773,41 @@ class TestFindTaskRun(TestCase):
status=TaskRun.Status.IN_PROGRESS,
**branch_fields,
)
+ other_task = Task.objects.create(
+ team=self.team,
+ created_by=self.user,
+ title="Other task",
+ description="Another run on the same branch",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ repository="posthog/posthog",
+ )
+ newest_run = TaskRun.objects.create(
+ task=other_task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ **branch_fields,
+ )
+
+ result = find_task_run(branch="feature/shared-branch", repository="posthog/posthog")
+
+ self.assertEqual(result, newest_run)
+
+ @parameterized.expand([("branch", False), ("signed_head_branch", True)])
+ def test_branch_fallback_ignores_reviewhog_runs(self, _name, signed_head_branch):
+ branch_fields = (
+ {
+ "branch": "master",
+ "output": {"head_branches": [{"repository": "posthog/posthog", "branch": "feature/shared-branch"}]},
+ }
+ if signed_head_branch
+ else {"branch": "feature/shared-branch"}
+ )
+ implementation_run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.COMPLETED,
+ **branch_fields,
+ )
review_task = Task.objects.create(
team=self.team,
created_by=self.user,
@@ -1688,16 +1816,17 @@ class TestFindTaskRun(TestCase):
origin_product=Task.OriginProduct.REVIEW_HOG,
repository="posthog/posthog",
)
- newest_run = TaskRun.objects.create(
+ # Newer ReviewHog run on the same branch must never be a webhook target.
+ TaskRun.objects.create(
task=review_task,
team=self.team,
- status=TaskRun.Status.COMPLETED,
+ status=TaskRun.Status.IN_PROGRESS,
**branch_fields,
)
result = find_task_run(branch="feature/shared-branch", repository="posthog/posthog")
- self.assertEqual(result, newest_run)
+ self.assertEqual(result, implementation_run)
@parameterized.expand([("branch", False), ("signed_head_branch", True)])
def test_branch_fallback_prefers_newest_run_with_same_status_rank(self, _name, signed_head_branch):
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index 38db4ec2b6e0..621d5fa35e95 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -39,7 +39,7 @@ from products.tasks.backend.metrics import (
observe_github_webhook_pr_event_dropped,
observe_github_webhook_task_run_lookup,
)
-from products.tasks.backend.models import TaskRun
+from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.pr_urls import merge_pr_output, read_pr_urls
from products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIX
@@ -79,6 +79,12 @@ def find_task_run(
logger.info("github_webhook_task_run_lookup_unscoped", pr_url=pr_url, branch=branch, repository=repository)
candidates = TaskRun.objects.filter(team_id__in=team_ids) if team_ids else TaskRun.objects.all()
+ # ReviewHog runs check out the PR head branch to review it, but they never author a PR, so no
+ # leg below may return one. The exclusion belongs here rather than on each leg: a stale
+ # ``verified_pr_urls`` claim, left on a ReviewHog run by an earlier wrong branch match, would
+ # otherwise keep every later event for that PR on the reviewing run. Dropping the claim falls
+ # through to the legs below, which resolve the run that authored the PR.
+ candidates = candidates.exclude(task__origin_product=Task.OriginProduct.REVIEW_HOG)
if pr_url:
# A resumed wizard run inherits its predecessor's head branch, so a terminal
@@ -109,6 +115,28 @@ def find_task_run(
# 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.
if branch and repository:
+ # A self-driving implementation run stamps its server-generated head branch into
+ # PATCH-protected state (signals' auto_start). That stamp is the run->PR link no
+ # caller can forge, so resolve it before the generic branch legs below. Without
+ # this, a newer ReviewHog run whose checkout branch is the same head ref wins the
+ # branch match and every later webhook, misattributing the PR's lifecycle events.
+ # FAILED and CANCELLED runs and soft-deleted tasks are dropped; a COMPLETED run
+ # stays eligible because success flips the run to COMPLETED right after it opens
+ # the PR. The task_run_sd_branch_idx index covers this filter.
+ task_run = (
+ candidates.filter(
+ _run_repository_filter(repository),
+ state__self_driving_head_branch=branch,
+ task__deleted=False,
+ )
+ .exclude(status__in=(TaskRun.Status.FAILED, TaskRun.Status.CANCELLED))
+ .order_by("-created_at", "-id")
+ .select_related(*TASK_RUN_SELECT_RELATED)
+ .first()
+ )
+ if task_run:
+ return task_run
+
# 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.