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): scope GitHub webhook run lookups to the installation's teams and bound the attribution lookup (#83852)

posthog[bot]35f286f69a74
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 8aadc3fc3ba8..d3778c071584 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -277,6 +277,53 @@ def observe_compute_quota_check(outcome: ComputeQuotaOutcome) -> None:
COMPUTE_QUOTA_CHECK_TOTAL.labels(outcome=outcome).inc()
+# analytics_event: pr_created | pr_merged | pr_closed | pr_reviewed (bounded, code-defined).
+# reason: unresolved_installation (no Integration matched the delivery's installation id) or
+# capture_exception (posthoganalytics.capture raised). Both paths were silent before,
+# so a webhook-side event loss only showed up as a capture-rate dip in analytics.
+GITHUB_WEBHOOK_PR_EVENT_DROPPED_TOTAL = Counter(
+ "posthog_tasks_github_webhook_pr_event_dropped_total",
+ "GitHub PR webhook events that never reached PostHog capture, labeled by event and drop reason",
+ labelnames=["analytics_event", "reason"],
+)
+
+# outcome: resolved | unresolved | timeout | error. timeout means the bounded org-member
+# lookup hit statement_timeout and was skipped so the delivery survives without attribution.
+GITHUB_WEBHOOK_ATTRIBUTION_TOTAL = Counter(
+ "posthog_tasks_github_webhook_attribution_total",
+ "Outcome of the org-member lookup that attributes a GitHub login on the pr_merged/pr_reviewed webhook path",
+ labelnames=["outcome"],
+)
+
+# scoped: "true" when the delivery's installation resolved to at least one team, so the
+# TaskRun lookup could ride the team_id index. "false" means it fell back to the legacy
+# unscoped lookup, which walks posthog_task_run once per leg — the thing we want to watch
+# shrink in production before considering anything stricter.
+GITHUB_WEBHOOK_TASK_RUN_LOOKUP_TOTAL = Counter(
+ "posthog_tasks_github_webhook_task_run_lookup_total",
+ "GitHub webhook TaskRun lookups, labeled by whether they were scoped to the installation's teams",
+ labelnames=["scoped"],
+)
+
+GitHubWebhookAnalyticsEvent = Literal["pr_created", "pr_merged", "pr_closed", "pr_reviewed"]
+GitHubWebhookDropReason = Literal["unresolved_installation", "capture_exception"]
+GitHubWebhookAttributionOutcome = Literal["resolved", "unresolved", "timeout", "error"]
+
+
+def observe_github_webhook_pr_event_dropped(
+ *, analytics_event: GitHubWebhookAnalyticsEvent, reason: GitHubWebhookDropReason
+) -> None:
+ GITHUB_WEBHOOK_PR_EVENT_DROPPED_TOTAL.labels(analytics_event=analytics_event, reason=reason).inc()
+
+
+def observe_github_webhook_attribution(*, outcome: GitHubWebhookAttributionOutcome) -> None:
+ GITHUB_WEBHOOK_ATTRIBUTION_TOTAL.labels(outcome=outcome).inc()
+
+
+def observe_github_webhook_task_run_lookup(*, scoped: bool) -> None:
+ GITHUB_WEBHOOK_TASK_RUN_LOOKUP_TOTAL.labels(scoped="true" if scoped else "false").inc()
+
+
def _metric_label(value: object | None) -> str:
if value is None:
return "unknown"
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index e25c4485c977..6ddea395c47a 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -2389,7 +2389,12 @@ class TaskRun(models.Model):
properties: dict | None = None,
event_uuid: str | None = None,
distinct_id_override: str | None = None,
- ) -> None:
+ ) -> bool:
+ """Capture an analytics event for this run. Returns False when it never reached capture.
+
+ The exception stays swallowed — no caller wants a failed analytics call to fail their
+ work — but the outcome is reported so callers tracking event loss can count it.
+ """
try:
# The override lets the PR webhook attribute pr_merged to the GitHub user who
# actually merged, rather than the task's assigned user.
@@ -2433,6 +2438,8 @@ class TaskRun(models.Model):
posthoganalytics.capture(**capture_kwargs)
except Exception as e:
logger.warning("task_run.capture_event_failed", analytics_event=event, error=str(e))
+ return False
+ return True
def _duration_seconds(self) -> float:
if self.completed_at and self.created_at:
diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.py
index 32cf9791d62a..fb4c6e02f600 100644
--- a/products/tasks/backend/tests/test_webhooks.py
+++ b/products/tasks/backend/tests/test_webhooks.py
@@ -5,10 +5,13 @@ from typing import ClassVar
from unittest.mock import MagicMock, patch
+from django.conf import settings
from django.core.cache import cache
+from django.db import OperationalError, connection
from django.test import TestCase
from parameterized import parameterized
+from prometheus_client import REGISTRY
from rest_framework.test import APIClient
from social_django.models import UserSocialAuth
@@ -16,12 +19,20 @@ from posthog.models.integration import Integration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
from products.signals.backend.models import SignalReport
from products.signals.backend.task_run_artefacts import append_task_run_artefact
from products.tasks.backend.facade.api import find_signal_implementation_run
from products.tasks.backend.models import Task, TaskRun, TaskThreadMessage
-from products.tasks.backend.webhooks import _account_type, find_task_run
+from products.tasks.backend.webhooks import (
+ _account_type,
+ _attribution_db_aliases,
+ _bounded_attribution_lookup,
+ _installation_team_ids,
+ _task_run_scope_team_ids,
+ find_task_run,
+)
class TestAccountType(TestCase):
@@ -39,6 +50,10 @@ class TestAccountType(TestCase):
self.assertEqual(_account_type(payload), expected)
+def _sample_value(name: str, labels: dict[str, str]) -> float:
+ return REGISTRY.get_sample_value(name, labels) or 0.0
+
+
def generate_github_signature(payload: bytes, secret: str) -> str:
"""Generate a GitHub-style HMAC-SHA256 signature."""
return (
@@ -183,6 +198,115 @@ class TestGitHubPRWebhook(TestCase):
self.assertEqual(call_kwargs["properties"]["pr_merged_by_login"], "octocat")
self.assertNotIn("pr_merged_by_distinct_id", call_kwargs["properties"])
+ @patch(
+ "products.tasks.backend.webhooks.resolve_org_github_login_to_users",
+ side_effect=OperationalError("canceling statement due to statement timeout"),
+ )
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_pr_merged_attribution_timeout_keeps_webhook_successful(self, mock_capture, mock_get_secret, _mock_resolve):
+ # A slow member lookup must degrade to no attribution, never cost the delivery:
+ # GitHub does not retry pull_request events and the merge side effects run after.
+ mock_get_secret.return_value = self.webhook_secret
+ before = _sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "timeout"})
+
+ payload = {
+ "action": "closed",
+ "pull_request": {
+ "html_url": "https://github.com/posthog/posthog/pull/123",
+ "merged": True,
+ "merged_by": {"login": "octocat", "id": 583231},
+ },
+ }
+
+ response = self._make_webhook_request(payload)
+
+ self.assertEqual(response.status_code, 200)
+ call_kwargs = mock_capture.call_args[1]
+ self.assertEqual(call_kwargs["distinct_id"], "user-123")
+ self.assertEqual(call_kwargs["properties"]["pr_merged_by_login"], "octocat")
+ self.assertNotIn("pr_merged_by_distinct_id", call_kwargs["properties"])
+ self.assertEqual(
+ _sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "timeout"}), before + 1
+ )
+ self.task_run.refresh_from_db()
+ assert self.task_run.output is not None
+ self.assertIs(self.task_run.output.get("pr_merged"), True)
+
+ @patch(
+ "products.tasks.backend.webhooks.resolve_org_github_login_to_users",
+ side_effect=OperationalError("server closed the connection unexpectedly"),
+ )
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_pr_merged_attribution_connection_error_is_not_counted_as_timeout(
+ self, mock_capture, mock_get_secret, _mock_resolve
+ ):
+ # timeout is the leading indicator for the statement cap, so a plain DB outage has to
+ # land on error -- otherwise an incident reads as statement-timeout pressure.
+ mock_get_secret.return_value = self.webhook_secret
+ timeouts = _sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "timeout"})
+ errors = _sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "error"})
+
+ payload = {
+ "action": "closed",
+ "pull_request": {
+ "html_url": "https://github.com/posthog/posthog/pull/123",
+ "merged": True,
+ "merged_by": {"login": "octocat", "id": 583231},
+ },
+ }
+
+ response = self._make_webhook_request(payload)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertNotIn("pr_merged_by_distinct_id", mock_capture.call_args[1]["properties"])
+ self.assertEqual(
+ _sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "error"}), errors + 1
+ )
+ self.assertEqual(
+ _sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "timeout"}), timeouts
+ )
+
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture", side_effect=RuntimeError("capture down"))
+ def test_task_backed_capture_failure_increments_drop_counter(self, _mock_capture, mock_get_secret):
+ # TaskRun.capture_event swallows the failure, so without a reported outcome the drop
+ # counter would miss the task-backed path entirely — the bulk of the traffic.
+ mock_get_secret.return_value = self.webhook_secret
+ labels = {"analytics_event": "pr_merged", "reason": "capture_exception"}
+ before = _sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels)
+
+ payload = {
+ "action": "closed",
+ "pull_request": {"html_url": "https://github.com/posthog/posthog/pull/123", "merged": True},
+ }
+
+ response = self._make_webhook_request(payload)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)
+
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_delivery_without_installation_falls_back_to_unscoped_lookup(self, mock_capture, mock_get_secret):
+ # Deliveries carrying no installation block keep the legacy full-table lookup, so the
+ # match must not regress. The counter is how we see how much of that traffic is left.
+ mock_get_secret.return_value = self.webhook_secret
+ labels = {"scoped": "false"}
+ before = _sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels)
+
+ payload = {
+ "action": "closed",
+ "pull_request": {"html_url": "https://github.com/posthog/posthog/pull/123", "merged": True},
+ }
+
+ response = self._make_webhook_request(payload)
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(mock_capture.call_args[1]["properties"]["run_id"], str(self.task_run.id))
+ self.assertEqual(_sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels), before + 1)
+
@patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
@patch("products.tasks.backend.models.posthoganalytics.capture")
def test_pr_merged_publishes_stream_events(self, mock_capture, mock_get_secret):
@@ -1213,6 +1337,90 @@ class TestExternalPRWebhook(TestCase):
self.assertEqual(response.status_code, 200)
mock_capture.assert_not_called()
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
+ def test_external_pr_unresolved_installation_increments_drop_counter(self, mock_capture, mock_get_secret):
+ # The silent drop is now a counter, so a webhook-side event loss shows up as an
+ # error rate instead of only a dip in the downstream capture ratio.
+ mock_get_secret.return_value = self.webhook_secret
+ labels = {"analytics_event": "pr_merged", "reason": "unresolved_installation"}
+ before = _sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels)
+ payload = self._external_payload("closed", merged=True)
+ payload["installation"]["id"] = 999999
+
+ self.assertEqual(self._post(payload).status_code, 200)
+
+ mock_capture.assert_not_called()
+ self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)
+
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture", side_effect=RuntimeError("capture down"))
+ def test_external_pr_capture_exception_increments_drop_counter(self, _mock_capture, mock_get_secret):
+ mock_get_secret.return_value = self.webhook_secret
+ labels = {"analytics_event": "pr_created", "reason": "capture_exception"}
+ before = _sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels)
+
+ response = self._post(self._external_payload("opened", merged=False))
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)
+
+ def test_personal_install_scopes_to_the_users_org_teams(self):
+ # A personal install reaches a team only through the tasks that picked it, and
+ # Task.github_user_integration is unindexed. Such a task lives in a team of the
+ # installing user's org, so widen the scope there rather than give up and scan.
+ payload = self._external_payload("opened", merged=False)
+ self.assertEqual(_task_run_scope_team_ids(payload), [self.team.id])
+
+ personal_org = Organization.objects.create(name="Personal Org")
+ personal_team = Team.objects.create(organization=personal_org, name="Personal Team")
+ user = User.objects.create(email="[email protected]", distinct_id="personal-1")
+ OrganizationMembership.objects.create(organization=personal_org, user=user)
+ UserIntegration.objects.create(user=user, kind="github", integration_id="555000")
+
+ self.assertEqual(_task_run_scope_team_ids(payload), sorted([self.team.id, personal_team.id]))
+ # Attribution still resolves off the Integration rows alone.
+ self.assertEqual(_installation_team_ids(payload), [self.team.id])
+
+ @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")
+ @patch("products.tasks.backend.webhooks.posthoganalytics.capture")
+ def test_run_in_another_team_does_not_claim_the_delivery(self, mock_capture, mock_get_secret):
+ # The run lookup is scoped to the installation's teams, so a run belonging to an
+ # unrelated team cannot claim a PR URL it happens to share. Unscoped, the full-table
+ # scan would have matched it and emitted the event as pr_source="task".
+ mock_get_secret.return_value = self.webhook_secret
+ other_org = Organization.objects.create(name="Unrelated Org")
+ other_team = Team.objects.create(organization=other_org, name="Unrelated Team")
+ other_task = Task.objects.create(
+ team=other_team,
+ title="Unrelated Task",
+ description="",
+ origin_product=Task.OriginProduct.USER_CREATED,
+ repository="acme/widgets",
+ )
+ TaskRun.objects.create(
+ task=other_task,
+ team=other_team,
+ status=TaskRun.Status.IN_PROGRESS,
+ branch="feature/x",
+ state={"verified_pr_urls": ["https://github.com/acme/widgets/pull/7"]},
+ output={"pr_url": "https://github.com/acme/widgets/pull/7"},
+ )
+ labels = {"scoped": "true"}
+ before = _sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels)
+ # Creating the fixtures above already captured task_created through the same module.
+ mock_capture.reset_mock()
+
+ response = self._post(self._external_payload("opened", merged=False))
+
+ self.assertEqual(response.status_code, 200)
+ mock_capture.assert_called_once()
+ properties = mock_capture.call_args[1]["properties"]
+ self.assertEqual(properties["pr_source"], "external")
+ self.assertEqual(properties["team_id"], self.team.id)
+ self.assertIsNone(properties["run_id"])
+ self.assertEqual(_sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels), before + 1)
+
@patch("products.tasks.backend.facade.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):
@@ -1288,6 +1496,28 @@ class TestFindTaskRun(TestCase):
)
self.assertEqual(find_task_run(pr_url=pr_url), active_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.
+ pr_url = "https://github.com/posthog/posthog/pull/900"
+ run = TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=TaskRun.Status.IN_PROGRESS,
+ branch="feature/scoped",
+ output={"pr_url": pr_url, "head_branches": [{"repository": "posthog/posthog", "branch": "signed/scoped"}]},
+ state={"verified_pr_urls": [pr_url]},
+ )
+ other_team = Team.objects.create(organization=self.organization, name="Other Team")
+
+ for kwargs in (
+ {"pr_url": pr_url},
+ {"branch": "feature/scoped", "repository": "posthog/posthog"},
+ {"branch": "signed/scoped", "repository": "posthog/posthog"},
+ ):
+ self.assertEqual(find_task_run(**kwargs, team_ids=[self.team.id]), run)
+ self.assertIsNone(find_task_run(**kwargs, team_ids=[other_team.id]))
+
def test_pr_url_does_not_match_other_repositories(self):
pr_url = "https://github.com/posthog/posthog/pull/322"
TaskRun.objects.create(
@@ -1862,3 +2092,53 @@ class TestFindSignalImplementationRun(TestCase):
assert found is not None
assert found.run_id == legitimate.id
+
+
+class TestAttributionDbAliases(TestCase):
+ def _with_replica_configured(self):
+ return self.settings(DATABASES={**settings.DATABASES, "replica": settings.DATABASES["default"]})
+
+ def test_default_only_when_no_replica_is_configured(self):
+ self.assertEqual(_attribution_db_aliases(), ["default"])
+
+ @patch("products.tasks.backend.webhooks.router.db_for_read", return_value="default")
+ def test_skips_a_configured_replica_the_router_would_not_read_from(self, _mock_db_for_read):
+ # Bounding an alias means opening it, and connection setup is itself unbounded (these
+ # aliases carry no connect_timeout), so a replica the router never reads from must not
+ # be dialled just to install a cap on it.
+ with self._with_replica_configured():
+ self.assertEqual(_attribution_db_aliases(), ["default"])
+
+ @patch("products.tasks.backend.webhooks.router.db_for_read", return_value="replica")
+ def test_skips_the_primary_when_every_model_reads_from_the_replica(self, _mock_db_for_read):
+ # Symmetric to the above: a fully replica-opted deployment must not be made to wait on
+ # the primary either, since opening it is just as unbounded.
+ with self._with_replica_configured():
+ self.assertEqual(_attribution_db_aliases(), ["replica"])
+
+ @patch("products.tasks.backend.webhooks.router.db_for_read")
+ def test_covers_every_alias_the_models_read_from(self, mock_db_for_read):
+ mock_db_for_read.side_effect = lambda model: "replica" if model is User else "default"
+ with self._with_replica_configured():
+ self.assertEqual(sorted(_attribution_db_aliases()), ["default", "replica"])
+
+
+class TestBoundedAttributionLookup(TestCase):
+ def _statement_timeout(self) -> str:
+ with connection.cursor() as cursor:
+ cursor.execute("SHOW statement_timeout")
+ row = cursor.fetchone()
+ assert row is not None
+ return row[0]
+
+ def test_caps_statements_and_restores_the_previous_value(self):
+ # Django's TestCase runs each test inside a transaction, which is exactly the case
+ # the restore exists for: joining a transaction we did not open (a future caller's
+ # atomic block, or ATOMIC_REQUESTS) must not leave the 800 ms cap behind.
+ before = self._statement_timeout()
+
+ with _bounded_attribution_lookup():
+ inside = self._statement_timeout()
+
+ self.assertEqual(inside, "800ms")
+ self.assertEqual(self._statement_timeout(), before)
diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.py
index f277d7591f31..858a3e80f40c 100644
--- a/products/tasks/backend/webhooks.py
+++ b/products/tasks/backend/webhooks.py
@@ -1,23 +1,38 @@
import hmac
import uuid
import hashlib
+from collections.abc import Iterator
+from contextlib import ExitStack, contextmanager
-from django.db import transaction
+from django.conf import settings
+from django.db import OperationalError, connections, router, transaction
+from django.db.backends.base.base import BaseDatabaseWrapper
from django.db.models import Case, IntegerField, Q, Value, When
from django.http import HttpResponse
import structlog
import posthoganalytics
+from social_django.models import UserSocialAuth
from posthog.event_usage import groups
from posthog.models.instance_setting import get_instance_setting
from posthog.models.integration import Integration
+from posthog.models.organization import OrganizationMembership
from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
from products.signals.backend.models import InvalidStatusTransition, SignalReport
from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
from products.tasks.backend.facade.api import post_pr_created_thread_update, signal_workflow_completion
from products.tasks.backend.facade.cancellation import cancel_task_run
+from products.tasks.backend.metrics import (
+ GitHubWebhookAnalyticsEvent,
+ GitHubWebhookAttributionOutcome,
+ observe_github_webhook_attribution,
+ observe_github_webhook_pr_event_dropped,
+ observe_github_webhook_task_run_lookup,
+)
from products.tasks.backend.models import TaskRun
from products.tasks.backend.pr_urls import merge_pr_output, read_pr_urls
from products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIX
@@ -41,15 +56,30 @@ def find_task_run(
pr_url: str | None = None,
branch: str | None = None,
repository: str | None = None,
+ team_ids: list[int] | None = None,
) -> TaskRun | None:
+ """Find the TaskRun a GitHub webhook belongs to, preferably scoped to ``team_ids``.
+
+ Every leg below filters on a JSON containment or a plain ``branch`` value, none of which
+ is indexed, so an unscoped lookup walks all of ``posthog_task_run`` three times per
+ delivery. ``team_id`` is a plain FK and therefore already indexed: passing the teams the
+ webhook's installation belongs to turns those walks into index scans. When the caller
+ cannot resolve any team the old unscoped behaviour is kept, just counted.
+ """
repository = repository.strip() if repository else None
+ observe_github_webhook_task_run_lookup(scoped=bool(team_ids))
+ if not team_ids:
+ 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()
+
if pr_url:
# A resumed wizard run inherits its predecessor's head branch, so a terminal
# original and its live resume can both claim the same PR URL. Scope to the
# webhook's repo and prefer non-terminal runs so merge handling lands on the
# run that can still act on it.
- runs = TaskRun.objects.filter(state__verified_pr_urls__contains=[pr_url])
+ runs = candidates.filter(state__verified_pr_urls__contains=[pr_url])
if repository:
runs = runs.filter(_run_repository_filter(repository))
# Declared type keeps mypy happy: the annotated queryset yields an AnnotatedWith
@@ -77,7 +107,7 @@ def find_task_run(
# 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(
+ candidates.filter(
_run_repository_filter(repository),
branch=branch,
state__wizard_head_branch__isnull=True,
@@ -93,7 +123,7 @@ def find_task_run(
# cannot represent nested repositories or multiple PR branches.
head_branch = {"repository": repository.lower(), "branch": branch}
task_run = (
- TaskRun.objects.filter(
+ candidates.filter(
_run_repository_filter(repository),
output__head_branches__contains=[head_branch],
state__wizard_head_branch__isnull=True,
@@ -110,7 +140,7 @@ def find_task_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(
+ candidates.filter(
_run_repository_filter(repository),
state__wizard_head_branch=branch,
task__deleted=False,
@@ -183,7 +213,7 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
return HttpResponse(status=200)
pr_state = _pr_state_for_action(action, pull_request)
- analytics_event: str | None = None
+ analytics_event: GitHubWebhookAnalyticsEvent | None = None
if action == "opened":
event_action = "created"
analytics_event = "pr_created"
@@ -205,7 +235,9 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:
branch = pull_request.get("head", {}).get("ref")
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)
+ task_run = find_task_run(
+ pr_url=pr_url, branch=branch, repository=repository_full_name, team_ids=_task_run_scope_team_ids(payload)
+ )
claimed_pr_urls = (
read_pr_urls(task_run.output if isinstance(task_run.output, dict) else {}) if task_run is not None else []
)
@@ -312,7 +344,9 @@ def handle_pull_request_review_event(payload: dict) -> HttpResponse:
branch = (pull_request.get("head") or {}).get("ref")
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)
+ task_run = find_task_run(
+ pr_url=pr_url, branch=branch, repository=repository_full_name, team_ids=_task_run_scope_team_ids(payload)
+ )
# One review submission = one event; GitHub redeliveries collapse on the review id.
event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:pr_reviewed:{review.get('id')}"))
@@ -560,16 +594,130 @@ def _pr_payload_properties(payload: dict) -> dict:
}
+# 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)
+# right after capture. A slow lookup on the request path can therefore cost the whole
+# delivery, not just the analytics event. Bounding it degrades to no attribution instead.
+_ATTRIBUTION_STATEMENT_TIMEOUT_MS = 800
+
+# Models the org-member resolver reads. ReplicaRouter only sends a model to the replica when
+# that model is named in READ_REPLICA_OPT_IN, so the set of aliases the lookup can touch is
+# knowable up front.
+_ATTRIBUTION_MODELS = (Team, User, OrganizationMembership, UserSocialAuth, UserIntegration, Integration)
+
+
+def _attribution_db_aliases() -> list[str]:
+ """The aliases the org-member lookup actually reads from, deduped, in model order.
+
+ Bounding an alias means opening it, and opening is itself unbounded -- ``postgres_config``
+ sets no ``connect_timeout`` on these aliases. So take the set from the router rather than
+ assuming: reaching for an alias the resolver never uses could stall the webhook on
+ connection setup before the cap is installed, which is the failure this exists to prevent.
+ That cuts both ways -- a fully replica-opted deployment must not be made to wait on the
+ primary either.
+ """
+ aliases: list[str] = []
+ for model in _ATTRIBUTION_MODELS:
+ alias = router.db_for_read(model) or "default"
+ if alias not in aliases and alias in settings.DATABASES:
+ aliases.append(alias)
+ return aliases
+
+
+def _read_statement_timeout(connection: BaseDatabaseWrapper) -> str | None:
+ with connection.cursor() as cursor:
+ cursor.execute("SHOW statement_timeout")
+ row = cursor.fetchone()
+ return row[0] if row else None
+
+
+def _apply_statement_timeout(connection: BaseDatabaseWrapper, value: str) -> None:
+ # set_config(..., is_local=True) is SET LOCAL, but takes the value as a bind parameter,
+ # so a restored value ("30s", "0", ...) does not have to be quoted by hand.
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT set_config('statement_timeout', %s, true)", [value])
+
+
+@contextmanager
+def _statement_timeout(connection: BaseDatabaseWrapper, timeout_ms: int, *, restore: bool) -> Iterator[None]:
+ """Cap statements on one connection, optionally putting the previous value back."""
+ previous = _read_statement_timeout(connection) if restore else None
+ _apply_statement_timeout(connection, f"{timeout_ms}ms")
+
+ yield
+
+ # Only reached when the block succeeded. If it raised, the enclosing atomic() rolls the
+ # (sub)transaction back and PostgreSQL undoes SET LOCAL with it, so there is nothing to
+ # restore -- and a statement on an aborted transaction would error anyway.
+ if previous:
+ _apply_statement_timeout(connection, previous)
+
+
+@contextmanager
+def _bounded_attribution_lookup() -> Iterator[None]:
+ """Run a block under a per-statement timeout on each configured DB the lookup may use.
+
+ A read routed to an alias joins that alias's open transaction, so ``SET LOCAL
+ statement_timeout`` there caps the query regardless of read-replica routing.
+ """
+ with ExitStack() as stack:
+ for alias in _attribution_db_aliases():
+ connection = connections[alias]
+ # SET LOCAL dies with the transaction it was set in, so the cap only needs
+ # restoring when we are joining a transaction somebody else owns -- a future
+ # caller wrapping this in its own atomic block, or ATOMIC_REQUESTS (which
+ # PostHog does not enable today). Otherwise the commit below ends it for us.
+ restore = connection.in_atomic_block
+ stack.enter_context(transaction.atomic(using=alias))
+ stack.enter_context(_statement_timeout(connection, _ATTRIBUTION_STATEMENT_TIMEOUT_MS, restore=restore))
+ yield
+
+
+# PostgreSQL raises query_canceled when statement_timeout fires. Django wraps the driver
+# error in OperationalError, so the SQLSTATE lives on the cause -- psycopg3 spells it
+# `sqlstate`, psycopg2 `pgcode`. The message check is the fallback for anything that loses
+# the cause on the way up.
+_QUERY_CANCELED_SQLSTATE = "57014"
+
+
+def _is_statement_timeout(error: Exception) -> bool:
+ if not isinstance(error, OperationalError):
+ return False
+ cause = error.__cause__
+ if getattr(cause, "sqlstate", None) == _QUERY_CANCELED_SQLSTATE:
+ return True
+ if getattr(cause, "pgcode", None) == _QUERY_CANCELED_SQLSTATE:
+ return True
+ return "statement timeout" in str(error).lower()
+
+
def _resolve_github_login_distinct_id(login: str | None, team_id: int) -> str | None:
- """Distinct id of the org member matching a GitHub login, or None when unresolvable."""
+ """Distinct id of the org member matching a GitHub login, or None when unresolvable.
+
+ Runs under a per-statement timeout so a slow member lookup cannot hold the webhook
+ open past GitHub's delivery timeout (see ``_ATTRIBUTION_STATEMENT_TIMEOUT_MS``).
+ """
if not login:
return None
try:
- resolved = resolve_org_github_login_to_users(team_id, [login]).get(str(login).strip().lower())
+ with _bounded_attribution_lookup():
+ resolved = resolve_org_github_login_to_users(team_id, [login]).get(str(login).strip().lower())
except Exception as e:
- logger.warning("github_webhook_login_resolution_failed", login=login, team_id=team_id, error=str(e))
+ # timeout is meant to be the leading indicator for the cap we just installed, so it
+ # has to mean "statement cancelled", not "any OperationalError" -- connection resets
+ # and other DB incidents raise the same class and would drown the signal.
+ outcome: GitHubWebhookAttributionOutcome = "timeout" if _is_statement_timeout(e) else "error"
+ observe_github_webhook_attribution(outcome=outcome)
+ logger.warning(
+ "github_webhook_login_resolution_failed", login=login, team_id=team_id, outcome=outcome, error=str(e)
+ )
return None
- return str(resolved.distinct_id) if resolved is not None else None
+ if resolved is None:
+ observe_github_webhook_attribution(outcome="unresolved")
+ return None
+ observe_github_webhook_attribution(outcome="resolved")
+ return str(resolved.distinct_id)
def _merged_by_attribution(payload: dict, team_id: int) -> tuple[dict, str | None]:
@@ -607,16 +755,19 @@ def _capture_pr_review_event(payload: dict, task_run: TaskRun | None, event_uuid
reviewer_distinct_id = _resolve_github_login_distinct_id(login, task_run.team_id)
if reviewer_distinct_id is not None:
pr_properties["pr_reviewed_by_distinct_id"] = reviewer_distinct_id
- task_run.capture_event(
+ captured = task_run.capture_event(
"pr_reviewed",
{**pr_properties, "pr_source": "task"},
event_uuid=event_uuid,
distinct_id_override=reviewer_distinct_id,
)
+ if not captured:
+ observe_github_webhook_pr_event_dropped(analytics_event="pr_reviewed", reason="capture_exception")
return
team = _resolve_external_team(payload)
if team is None:
+ observe_github_webhook_pr_event_dropped(analytics_event="pr_reviewed", reason="unresolved_installation")
logger.debug("github_pr_review_webhook_unresolved_installation", pr_url=pr_properties.get("pr_url"))
return
@@ -642,10 +793,13 @@ def _capture_pr_review_event(payload: dict, task_run: TaskRun | None, event_uuid
uuid=event_uuid,
)
except Exception as e:
+ observe_github_webhook_pr_event_dropped(analytics_event="pr_reviewed", reason="capture_exception")
logger.warning("github_pr_review_webhook_capture_failed", error=str(e))
-def _capture_pr_event(payload: dict, task_run: TaskRun | None, analytics_event: str, event_uuid: str) -> None:
+def _capture_pr_event(
+ payload: dict, task_run: TaskRun | None, analytics_event: GitHubWebhookAnalyticsEvent, event_uuid: str
+) -> None:
pr_properties = _pr_payload_properties(payload)
if task_run is not None:
@@ -653,16 +807,19 @@ def _capture_pr_event(payload: dict, task_run: TaskRun | None, analytics_event:
if analytics_event == "pr_merged":
merged_by_properties, merger_distinct_id = _merged_by_attribution(payload, task_run.team_id)
pr_properties = {**pr_properties, **merged_by_properties}
- task_run.capture_event(
+ captured = task_run.capture_event(
analytics_event,
{**pr_properties, "pr_source": "task"},
event_uuid=event_uuid,
distinct_id_override=merger_distinct_id,
)
+ if not captured:
+ observe_github_webhook_pr_event_dropped(analytics_event=analytics_event, reason="capture_exception")
return
team = _resolve_external_team(payload)
if team is None:
+ observe_github_webhook_pr_event_dropped(analytics_event=analytics_event, reason="unresolved_installation")
logger.debug("github_pr_webhook_unresolved_installation", pr_url=pr_properties.get("pr_url"))
return
@@ -690,22 +847,86 @@ def _capture_pr_event(payload: dict, task_run: TaskRun | None, analytics_event:
uuid=event_uuid,
)
except Exception as e:
+ observe_github_webhook_pr_event_dropped(analytics_event=analytics_event, reason="capture_exception")
logger.warning("github_pr_webhook_capture_failed", analytics_event=analytics_event, error=str(e))
-def _resolve_external_team(payload: dict) -> Team | None:
+def _installation_id(payload: dict) -> str | None:
+ """The delivery's GitHub App installation id, in the form the integration rows store it."""
installation_id = (payload.get("installation") or {}).get("id")
- if installation_id is None:
- return None
+ return None if installation_id is None else str(installation_id)
+
+
+# The run lookup these feed reads TaskRun off the writer, and they run on the request path
+# outside the bounded attribution block. Pin them to the writer too: a replica-opted
+# Integration or Team would otherwise let a slow replica stall a delivery whose own lookup
+# never needed it, and replica lag could hide a freshly connected installation.
+_SCOPE_DB_ALIAS = "default"
+
+
+def _installation_team_ids(payload: dict) -> list[int]:
+ """Teams whose GitHub Integration matches the delivery's installation, in deterministic order.
+
+ Empty when the payload carries no installation id or no Integration matches it — the
+ lookups that take this fall back to their unscoped behaviour in that case.
+ """
+ external_id = _installation_id(payload)
+ if external_id is None:
+ return []
# 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")
+ return list(
+ Integration.objects.using(_SCOPE_DB_ALIAS)
+ .filter(kind="github", integration_id=external_id)
.order_by("team_id")
- .first()
+ .values_list("team_id", flat=True)
)
- return integration.team if integration else None
+
+
+def _task_run_scope_team_ids(payload: dict) -> list[int]:
+ """Teams to scope the TaskRun lookup to, or empty to leave the lookup unscoped.
+
+ An installation reaches a team two ways. Team-level ``Integration`` rows are the obvious
+ one. The other is a personal install: a task picks a ``UserIntegration`` through
+ ``Task.github_user_integration``, which is deliberately unindexed, so the run cannot be
+ reached from the integration side at all. Those tasks live in a team of the installing
+ user's organization, so widening the scope to those teams keeps the run findable while
+ every leg still runs as ``team_id IN (...)`` on the FK index.
+
+ Accepted edge: a user who has since left the organization no longer widens the scope, so
+ a delivery for a run they created that way stops matching. Anything with no installation
+ id, or an installation nothing is linked to, falls back to the unscoped lookup.
+ """
+ external_id = _installation_id(payload)
+ if external_id is None:
+ return []
+
+ team_ids = set(_installation_team_ids(payload))
+
+ # Left lazy on purpose: Django inlines these as subqueries, so the whole widening is one
+ # indexed round-trip rather than three.
+ user_ids = (
+ UserIntegration.objects.using(_SCOPE_DB_ALIAS)
+ .filter(kind="github", integration_id=external_id)
+ .values_list("user_id", flat=True)
+ )
+ org_ids = (
+ OrganizationMembership.objects.using(_SCOPE_DB_ALIAS)
+ .filter(user_id__in=user_ids)
+ .values_list("organization_id", flat=True)
+ )
+ team_ids.update(
+ Team.objects.using(_SCOPE_DB_ALIAS).filter(organization_id__in=org_ids).values_list("id", flat=True)
+ )
+
+ return sorted(team_ids)
+
+
+def _resolve_external_team(payload: dict) -> Team | None:
+ team_ids = _installation_team_ids(payload)
+ if not team_ids:
+ return None
+ return Team.objects.filter(pk=team_ids[0]).first()
def _transition_signal_reports_for_task(