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.

feat(tasks): emit pr analytics events for external PRs (#60719)

Joshua Snyderd52a29195112
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index d13692cfeb0b..dbc7fdeadd4a 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -98,6 +98,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(call_kwargs["properties"]["pr_url"], "https://github.com/posthog/posthog/pull/123")
self.assertEqual(call_kwargs["properties"]["task_id"], str(self.task.id))
self.assertEqual(call_kwargs["properties"]["run_id"], str(self.task_run.id))
+ self.assertEqual(call_kwargs["properties"]["pr_source"], "task")
@patch("products.tasks.backend.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
@@ -175,8 +176,8 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 403)
@patch("products.tasks.backend.webhooks.get_github_webhook_secret")
- @patch("products.tasks.backend.models.posthoganalytics.capture")
- def test_unknown_pr_url_returns_200(self, mock_capture, mock_get_secret):
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
+ def test_unmatched_pr_without_installation_not_captured(self, mock_capture, mock_get_secret):
mock_get_secret.return_value = self.webhook_secret
payload = {
@@ -240,7 +241,7 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(response.status_code, 405)
@patch("products.tasks.backend.webhooks.get_github_webhook_secret")
- @patch("products.tasks.backend.models.posthoganalytics.capture")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
def test_webhook_does_not_attribute_foreign_repo_pr_to_unrelated_run(self, mock_capture, mock_get_secret):
# Regression: a PR opened on a repo that has no matching TaskRun must
# not fall through to a branch-only lookup that attributes the event
@@ -384,6 +385,143 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):
self.assertEqual(self.report.status, SignalReport.Status.READY)
+class TestExternalPRWebhook(TestCase):
+ """PRs with no matching TaskRun are emitted as external PR events."""
+
+ organization: ClassVar[Organization]
+ team: ClassVar[Team]
+ integration: ClassVar[Integration]
+
+ @classmethod
+ def setUpTestData(cls):
+ cls.organization = Organization.objects.create(name="External Org")
+ cls.team = Team.objects.create(organization=cls.organization, name="External Team")
+ cls.integration = Integration.objects.create(
+ team=cls.team,
+ kind="github",
+ integration_id="555000",
+ config={"account": {"name": "acme"}},
+ )
+
+ def setUp(self):
+ self.client = APIClient()
+ self.webhook_secret = "test-webhook-secret"
+
+ def _post(self, payload: dict):
+ payload_bytes = json.dumps(payload).encode("utf-8")
+ signature = generate_github_signature(payload_bytes, self.webhook_secret)
+ return self.client.post(
+ "/webhooks/github/pr/",
+ data=payload_bytes,
+ content_type="application/json",
+ headers={"x-hub-signature-256": signature, "x-github-event": "pull_request"},
+ )
+
+ def _external_payload(self, action: str, merged: bool):
+ return {
+ "action": action,
+ "installation": {"id": 555000},
+ "repository": {"full_name": "acme/widgets"},
+ "pull_request": {
+ "html_url": "https://github.com/acme/widgets/pull/7",
+ "number": 7,
+ "merged": merged,
+ "user": {"login": "octocat"},
+ "title": "Internal customer change",
+ "base": {"ref": "main"},
+ "head": {"ref": "feature/x"},
+ },
+ }
+
+ @parameterized.expand(
+ [
+ ("opened", "opened", False, "pr_created"),
+ ("closed", "closed", False, "pr_closed"),
+ ("merged", "closed", True, "pr_merged"),
+ ]
+ )
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
+ def test_external_pr_event_attributes_to_installation_team(
+ self, _name, action, merged, expected_event, mock_capture, mock_get_secret
+ ):
+ mock_get_secret.return_value = self.webhook_secret
+
+ response = self._post(self._external_payload(action, merged))
+
+ self.assertEqual(response.status_code, 200)
+ mock_capture.assert_called_once()
+ call_kwargs = mock_capture.call_args[1]
+ props = call_kwargs["properties"]
+ self.assertEqual(call_kwargs["event"], expected_event)
+ self.assertEqual(call_kwargs["distinct_id"], str(self.team.uuid))
+ self.assertEqual(call_kwargs["groups"]["project"], str(self.team.uuid))
+ self.assertEqual(props["pr_source"], "external")
+ self.assertEqual(props["team_id"], self.team.id)
+ self.assertEqual(props["repository"], "acme/widgets")
+ self.assertEqual(props["pr_number"], 7)
+ self.assertEqual(props["pr_author"], "octocat")
+ self.assertEqual(props["pr_base_ref"], "main")
+ self.assertIsNone(props["task_id"])
+ self.assertIsNone(props["origin_product"])
+ self.assertIsNone(props["title"])
+
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
+ def test_external_pr_event_is_deduplicated_per_action(self, mock_capture, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+
+ payload = self._external_payload("closed", merged=True)
+ self.assertEqual(self._post(payload).status_code, 200)
+ self.assertEqual(self._post(payload).status_code, 200)
+
+ self.assertEqual(mock_capture.call_count, 2)
+ first_uuid = mock_capture.call_args_list[0][1]["uuid"]
+ second_uuid = mock_capture.call_args_list[1][1]["uuid"]
+ self.assertEqual(first_uuid, second_uuid)
+
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
+ def test_external_pr_without_resolvable_installation_is_dropped(self, mock_capture, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+
+ payload = self._external_payload("opened", merged=False)
+ payload["installation"]["id"] = 999999
+
+ response = self._post(payload)
+
+ self.assertEqual(response.status_code, 200)
+ mock_capture.assert_not_called()
+
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
+ def test_external_pr_shared_installation_resolves_deterministically(self, mock_capture, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ other_team = Team.objects.create(organization=self.organization, name="Other External Team")
+ Integration.objects.create(
+ team=other_team, kind="github", integration_id="555000", config={"account": {"name": "acme"}}
+ )
+ expected_team = min([self.team, other_team], key=lambda t: t.id)
+
+ self.assertEqual(self._post(self._external_payload("closed", merged=True)).status_code, 200)
+ self.assertEqual(self._post(self._external_payload("closed", merged=True)).status_code, 200)
+
+ distinct_ids = {call[1]["distinct_id"] for call in mock_capture.call_args_list}
+ self.assertEqual(distinct_ids, {str(expected_team.uuid)})
+
+ @patch("products.tasks.backend.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
+ def test_external_pr_without_installation_block_is_dropped(self, mock_capture, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ payload = self._external_payload("opened", merged=False)
+ del payload["installation"]
+
+ response = self._post(payload)
+
+ self.assertEqual(response.status_code, 200)
+ mock_capture.assert_not_called()
+
+
class TestFindTaskRun(TestCase):
def setUp(self):
self.organization = Organization.objects.create(name="Test Org")
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index 04ac476d5d9b..897d92873b74 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -5,8 +5,12 @@ import hashlib
from django.http import HttpResponse
import structlog
+import posthoganalytics
+from posthog.event_usage import groups
from posthog.models.instance_setting import get_instance_setting
+from posthog.models.integration import Integration
+from posthog.models.team.team import Team
from products.signals.backend.models import InvalidStatusTransition, SignalReport
from products.tasks.backend.models import TaskRun
@@ -102,35 +106,89 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
repository_full_name = (payload.get("repository") or {}).get("full_name")
task_run = find_task_run(pr_url=pr_url, branch=branch, repository=repository_full_name)
- if not task_run:
- logger.debug(
- "github_pr_webhook_no_task_run",
- action=action,
- pr_url=pr_url,
- message="No TaskRun found with this PR URL",
- )
- return HttpResponse(status=200)
-
logger.info(
"github_pr_webhook_processed",
action=action,
event_action=event_action,
pr_url=pr_url,
- task_id=str(task_run.task_id),
- run_id=str(task_run.id),
+ pr_source="task" if task_run else "external",
+ task_id=str(task_run.task_id) if task_run else None,
+ run_id=str(task_run.id) if task_run else None,
)
- # Generate a deterministic UUID from the PR URL and event type so that
- # duplicate webhook deliveries for the same PR action are deduplicated.
+ # Deterministic UUID dedupes duplicate webhook deliveries of the same PR action.
event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:{analytics_event}"))
- task_run.capture_event(analytics_event, {"pr_url": pr_url}, event_uuid=event_uuid)
+ _capture_pr_event(payload, task_run, analytics_event, event_uuid)
- if action == "closed" and merged:
+ if task_run and action == "closed" and merged:
_resolve_signal_reports_for_task(task_run.task_id, pr_url)
return HttpResponse(status=200)
+# 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")
+
+
+def _pr_payload_properties(payload: dict) -> dict:
+ pull_request = payload.get("pull_request") or {}
+ return {
+ "pr_url": pull_request.get("html_url"),
+ "pr_number": pull_request.get("number"),
+ "pr_author": (pull_request.get("user") or {}).get("login"),
+ "pr_base_ref": (pull_request.get("base") or {}).get("ref"),
+ "pr_head_ref": (pull_request.get("head") or {}).get("ref"),
+ }
+
+
+def _capture_pr_event(payload: dict, task_run: TaskRun | None, analytics_event: str, event_uuid: str) -> None:
+ pr_properties = _pr_payload_properties(payload)
+
+ if task_run is not None:
+ task_run.capture_event(analytics_event, {**pr_properties, "pr_source": "task"}, event_uuid=event_uuid)
+ return
+
+ team = _resolve_external_team(payload)
+ if team is None:
+ logger.debug("github_pr_webhook_unresolved_installation", pr_url=pr_properties.get("pr_url"))
+ return
+
+ properties: dict = {
+ **pr_properties,
+ "repository": ((payload.get("repository") or {}).get("full_name") or "").strip().lower() or None,
+ "pr_source": "external",
+ "team_id": team.id,
+ # title omitted to avoid leaking customer business context.
+ **dict.fromkeys(_TASK_ATTRIBUTION_KEYS, None),
+ }
+
+ try:
+ posthoganalytics.capture(
+ distinct_id=str(team.uuid),
+ event=analytics_event,
+ properties=properties,
+ groups=groups(team=team),
+ uuid=event_uuid,
+ )
+ except Exception as e:
+ logger.warning("github_pr_webhook_capture_failed", analytics_event=analytics_event, error=str(e))
+
+
+def _resolve_external_team(payload: dict) -> Team | None:
+ installation_id = (payload.get("installation") or {}).get("id")
+ if installation_id is None:
+ return None
+
+ # One installation can map to multiple teams; order_by makes attribution deterministic.
+ integration = (
+ Integration.objects.filter(kind="github", integration_id=str(installation_id))
+ .select_related("team")
+ .order_by("team_id")
+ .first()
+ )
+ return integration.team if integration else None
+
+
def _resolve_signal_reports_for_task(task_id: uuid.UUID, pr_url: str) -> None:
"""Mark signal reports linked to a merged PR's task as resolved.