: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): capture PR title, body, labels and reviewers on task PR events (#96359)
posthog[bot]8724e30ec02f
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex 7b30d5cb60f2..4f5bdcebb78b 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -26,6 +26,7 @@ from products.signals.backend.models import SignalActorKind, SignalReport, Signafrom products.tasks.backend.facade.api import find_signal_implementation_runfrom products.tasks.backend.models import Task, TaskRun, TaskThreadMessagefrom products.tasks.backend.webhooks import (+ _PR_BODY_MAX_CHARS,_account_type,_attribution_db_aliases,_bounded_attribution_lookup,@@ -600,6 +601,11 @@ class TestGitHubPRWebhook(TestCase):"pull_request": {"html_url": "https://github.com/posthog/posthog/pull/123","merged": False,+ "draft": True,+ "title": "fix(tasks): stop dropping the retry",+ "body": "## Problem\n\nThe retry never fires.",+ "labels": [{"name": "bug"}, {"name": "tasks"}],+ "requested_reviewers": [{"login": "octocat"}],},}@@ -610,6 +616,39 @@ class TestGitHubPRWebhook(TestCase):mock_capture.assert_called_once()call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["event"], "pr_created")+ props = call_kwargs["properties"]+ self.assertEqual(props["pr_title"], "fix(tasks): stop dropping the retry")+ self.assertEqual(props["pr_body"], "## Problem\n\nThe retry never fires.")+ self.assertIs(props["pr_body_truncated"], False)+ self.assertEqual(props["pr_labels"], ["bug", "tasks"])+ self.assertEqual(props["pr_requested_reviewers"], ["octocat"])+ self.assertIs(props["pr_is_draft"], True)++ @parameterized.expand(+ [+ ("at_the_cap", _PR_BODY_MAX_CHARS, False),+ ("over_the_cap", _PR_BODY_MAX_CHARS + 1, True),+ ]+ )+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("products.tasks.backend.models.posthoganalytics.capture")+ def test_pr_body_is_capped(self, _name, body_length, expected_truncated, mock_capture, mock_get_secret):+ mock_get_secret.return_value = self.webhook_secret++ payload = {+ "action": "opened",+ "pull_request": {+ "html_url": "https://github.com/posthog/posthog/pull/123",+ "merged": False,+ "body": "b" * body_length,+ },+ }++ self.assertEqual(self._make_webhook_request(payload).status_code, 200)++ props = mock_capture.call_args[1]["properties"]+ self.assertEqual(len(props["pr_body"]), min(body_length, _PR_BODY_MAX_CHARS))+ self.assertIs(props["pr_body_truncated"], expected_truncated)# The pr: task-list filter reads output.pr_state, so each state-changing# webhook action must land the canonical state on the run that claims the PR.@@ -1074,7 +1113,10 @@ class TestGitHubPRReviewWebhook(TestCase):return {"action": action,"review": {"id": 99, "state": state, "user": reviewer},- "pull_request": {"html_url": "https://github.com/posthog/posthog/pull/123"},+ "pull_request": {+ "html_url": "https://github.com/posthog/posthog/pull/123",+ "title": "fix(tasks): stop dropping the retry",+ },}@parameterized.expand(@@ -1107,6 +1149,7 @@ class TestGitHubPRReviewWebhook(TestCase):self.assertEqual(call_kwargs["properties"]["pr_reviewed_by_id"], 583231)self.assertEqual(call_kwargs["properties"].get("pr_reviewed_by_distinct_id"), expected_property)self.assertEqual(call_kwargs["properties"]["pr_source"], "task")+ self.assertEqual(call_kwargs["properties"]["pr_title"], "fix(tasks): stop dropping the retry")@parameterized.expand([@@ -1467,6 +1510,8 @@ class TestExternalPRWebhook(TestCase):"merged": merged,"user": {"login": "octocat"},"title": "Internal customer change",+ "body": "Internal customer detail",+ "labels": [{"name": "internal"}],"base": {"ref": "main"},"head": {"ref": "feature/x"},"additions": 120,@@ -1514,6 +1559,9 @@ class TestExternalPRWebhook(TestCase):self.assertIsNone(props["task_id"])self.assertIsNone(props["origin_product"])self.assertIsNone(props["title"])+ # An external PR's own words are customer business context, so the keys stay null.+ for key in ("pr_title", "pr_body", "pr_labels", "pr_requested_reviewers", "pr_is_draft"):+ self.assertIsNone(props[key])@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")@patch("products.tasks.backend.webhooks.posthoganalytics.capture")diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex 83e32c7cb6e9..e202a545cca5 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -571,6 +571,22 @@ def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, fai# 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")+# What a PR says, rather than how big it is. Only task-authored PRs carry these values -- an+# external PR's own words are customer business context, so it gets the keys as nulls for+# schema parity, the same way _TASK_ATTRIBUTION_KEYS works.+_PR_CONTENT_KEYS = (+ "pr_title",+ "pr_body",+ "pr_body_truncated",+ "pr_labels",+ "pr_requested_reviewers",+ "pr_is_draft",+)++# A PR body is the biggest string on the delivery, and an agent-authored one can run long.+# Cap it so one verbose body cannot push the event past the capture size limit.+_PR_BODY_MAX_CHARS = 10_000+def _account_type(payload: dict) -> str | None:"""Whether the webhook's repo is owned by a GitHub org or a personal account.@@ -606,6 +622,24 @@ def _pr_payload_properties(payload: dict) -> dict:}+def _pr_content_properties(payload: dict) -> dict:+ """What a task-authored PR says: its title, body, labels, requested reviewers, draft state."""+ pull_request = payload.get("pull_request") or {}+ body = pull_request.get("body") or ""+ return {+ "pr_title": pull_request.get("title"),+ "pr_body": body[:_PR_BODY_MAX_CHARS],+ "pr_body_truncated": len(body) > _PR_BODY_MAX_CHARS,+ "pr_labels": [label.get("name") for label in (pull_request.get("labels") or []) if label.get("name")],+ "pr_requested_reviewers": [+ reviewer.get("login")+ for reviewer in (pull_request.get("requested_reviewers") or [])+ if reviewer.get("login")+ ],+ "pr_is_draft": pull_request.get("draft"),+ }++# Cap the org-member lookup that attributes the merger (and reviewer). GitHub gives a# pull_request delivery one short window and never retries it, and the merged branch runs# functional side effects (merge bookkeeping, signal-report resolution, wizard wind-down)@@ -769,7 +803,7 @@ def _capture_pr_review_event(payload: dict, task_run: TaskRun | None, event_uuidpr_properties["pr_reviewed_by_distinct_id"] = reviewer_distinct_idcaptured = task_run.capture_event("pr_reviewed",- {**pr_properties, "pr_source": "task"},+ {**pr_properties, **_pr_content_properties(payload), "pr_source": "task"},event_uuid=event_uuid,distinct_id_override=reviewer_distinct_id,)@@ -792,8 +826,9 @@ def _capture_pr_review_event(payload: dict, task_run: TaskRun | None, event_uuid"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.+ # title and PR content omitted to avoid leaking customer business context.**dict.fromkeys(_TASK_ATTRIBUTION_KEYS, None),+ **dict.fromkeys(_PR_CONTENT_KEYS, None),}try:@@ -821,7 +856,7 @@ def _capture_pr_event(pr_properties = {**pr_properties, **merged_by_properties}captured = task_run.capture_event(analytics_event,- {**pr_properties, "pr_source": "task"},+ {**pr_properties, **_pr_content_properties(payload), "pr_source": "task"},event_uuid=event_uuid,distinct_id_override=merger_distinct_id,)@@ -846,8 +881,9 @@ def _capture_pr_event("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.+ # title and PR content omitted to avoid leaking customer business context.**dict.fromkeys(_TASK_ATTRIBUTION_KEYS, None),+ **dict.fromkeys(_PR_CONTENT_KEYS, None),}try:diff --git a/products/tasks/docs/INSTRUMENTATION.md b/products/tasks/docs/INSTRUMENTATION.mdindex 6480883123ee..87f421bb77b6 100644--- a/products/tasks/docs/INSTRUMENTATION.md+++ b/products/tasks/docs/INSTRUMENTATION.md@@ -273,9 +273,19 @@ These events use `TaskRun.capture_event()` so include all [TaskRun standard propTracked when a GitHub `pull_request.opened` webhook is received. Additional properties:-| Property | Type | Description |-| -------- | ----- | ------------- |-| `pr_url` | `str` | GitHub PR URL |+| Property | Type | Description |+| ------------------------ | ----------- | ----------------------------------------------- |+| `pr_url` | `str` | GitHub PR URL |+| `pr_title` | `str` | PR title |+| `pr_body` | `str` | PR description, capped at 10,000 characters |+| `pr_body_truncated` | `bool` | Whether the cap removed part of the description |+| `pr_labels` | `list[str]` | Label names on the PR |+| `pr_requested_reviewers` | `list[str]` | GitHub logins of the requested reviewers |+| `pr_is_draft` | `bool` | Whether the PR is a draft |++The `pr_title`, `pr_body`, `pr_labels`, `pr_requested_reviewers`, and `pr_is_draft` properties+carry a value only on task-authored PRs. An external PR's own words are customer business+context, so those events get the same keys as `null`.### `pr_merged`