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): assign pr in webhook (#64717)

Joshua Snyder758a5886661f
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index dbc7fdeadd4a..d89db9ec9c96 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -142,6 +142,91 @@ class TestGitHubPRWebhook(TestCase):
call_kwargs = mock_capture.call_args[1]
self.assertEqual(call_kwargs["event"], "pr_created")
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_pr_opened_backfills_pr_url_on_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="feature/needs-pr-url",
+ output={},
+ )
+ pr_url = "https://github.com/posthog/posthog/pull/777"
+ payload = {
+ "action": "opened",
+ "pull_request": {
+ "html_url": pr_url,
+ "merged": False,
+ "head": {"ref": "feature/needs-pr-url", "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.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):
+ mock_get_secret.return_value = self.webhook_secret
+ run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ branch="feature/needs-pr-url",
+ output={},
+ )
+ payload = {
+ "action": "opened",
+ "pull_request": {
+ "html_url": "https://github.com/attacker/posthog/pull/1",
+ "merged": False,
+ "head": {"ref": "feature/needs-pr-url", "repo": {"full_name": "attacker/posthog"}},
+ },
+ "repository": {"full_name": "posthog/posthog"},
+ }
+
+ response = self._make_webhook_request(payload)
+ self.assertEqual(response.status_code, 200)
+
+ run.refresh_from_db()
+ self.assertEqual(run.output, {})
+
+ @patch("products.tasks.backend.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):
+ mock_get_secret.return_value = self.webhook_secret
+ existing = "https://github.com/posthog/posthog/pull/900"
+ run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ branch="feature/has-pr",
+ output={"pr_url": existing},
+ )
+ payload = {
+ "action": "opened",
+ "pull_request": {
+ "html_url": "https://github.com/posthog/posthog/pull/901",
+ "merged": False,
+ "head": {"ref": "feature/has-pr", "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"], existing)
+
@patch("products.tasks.backend.webhooks.get_github_webhook_secret")
def test_invalid_signature_rejected(self, mock_get_secret):
"""Test that requests with invalid signatures are rejected."""
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index 897d92873b74..2e56e5b013da 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -2,6 +2,7 @@ import hmac
import uuid
import hashlib
+from django.db import transaction
from django.http import HttpResponse
import structlog
@@ -116,6 +117,22 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
run_id=str(task_run.id) if task_run else None,
)
+ # Backstop the agent-side PR detector: when we matched the run (by branch+repo)
+ # but its output carries no PR URL yet, persist it so the inbox-notification
+ # gate, CI follow-up loop, and later webhook lookups can resolve the PR.
+ # Only trust the match when the PR originates from a branch in the installed
+ # repo itself — never a fork. For fork PRs, head.ref is attacker-controlled
+ # while repository.full_name stays the base repo, so a branch+repo match could
+ # otherwise bind an unrelated PR to the run.
+ head_repo_full_name = ((pull_request.get("head") or {}).get("repo") or {}).get("full_name")
+ is_internal_branch = (
+ head_repo_full_name is not None
+ and repository_full_name is not None
+ and head_repo_full_name.strip().lower() == repository_full_name.strip().lower()
+ )
+ if task_run is not None and is_internal_branch:
+ _record_run_pr_url(task_run, pr_url)
+
# Deterministic UUID dedupes duplicate webhook deliveries of the same PR action.
event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:{analytics_event}"))
_capture_pr_event(payload, task_run, analytics_event, event_uuid)
@@ -126,6 +143,32 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
return HttpResponse(status=200)
+def _record_run_pr_url(task_run: TaskRun, pr_url: str) -> None:
+ """Persist ``output.pr_url`` for a webhook-matched run when it isn't set yet.
+
+ The agent server normally records the PR URL when it observes the agent open
+ the PR. When that detection misses, a branch+repo webhook match is the
+ backstop — without this the run is recognized for analytics but its
+ ``output.pr_url`` stays empty, so inbox notifications, the CI follow-up loop,
+ and later webhook lookups never resolve the PR. 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("pr_url"):
+ return
+ try:
+ 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("pr_url"):
+ return
+ locked.output = {**output, "pr_url": pr_url}
+ locked.save(update_fields=["output", "updated_at"])
+ # Keep the in-memory instance consistent for the rest of this request.
+ task_run.output = {**(task_run.output if isinstance(task_run.output, dict) else {}), "pr_url": pr_url}
+ except Exception:
+ logger.warning("github_pr_webhook_record_pr_url_failed", run_id=str(task_run.id), exc_info=True)
+
+
# Nulled on external PRs so their schema matches task-originated PR events.
_TASK_ATTRIBUTION_KEYS = ("task_id", "run_id", "origin_product", "signal_report_id", "environment", "mode", "title")