: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(ingress): route the GitHub App webhook through ingress (#100417)
Julian Beze8686798189d
diff --git a/.agents/skills/adding-inbound-webhooks/SKILL.md b/.agents/skills/adding-inbound-webhooks/SKILL.mdindex 60279f877e2e..f725cb90ccc6 100644--- a/.agents/skills/adding-inbound-webhooks/SKILL.md+++ b/.agents/skills/adding-inbound-webhooks/SKILL.md@@ -45,6 +45,7 @@ Rules that decide whether this works:- The handler runs synchronously inside the request. Enqueue a task for real work, the way stamphog and conversations do.- A handler that reads the database wraps the read in `bounded_statement_timeout(ms, models=...)` from `posthog.ingress.dispatch.database`, passing only the models the read actually uses. Opening an alias is itself unbounded, so naming one the read never touches can stall the delivery on connection setup.- An import-linter contract (`webhook consumers must only import facade`) holds the module to its own product's `facade/`. Reach product internals through the facade.+- A consumer whose resources are split across regions declares `ownership=`, pointing at a facade function that returns a `DeliveryOwnership`. Ingress forwards the signed request when the answer is `ELSEWHERE`, and dispatches locally either way. The lookup runs inside the request, so bound it with `bounded_statement_timeout(ms, models=...)`.Tests: extend the product's existing webhook test module rather than starting a parallel one.`products/stamphog/backend/tests/test_webhook_consumers.py` is the shape: drive the real view with a signed `RequestFactory` request and assert the enqueue, plus the event type the app does not register, the bad signature, the unparseable body, the non-POST, and the missing secret.diff --git a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yamlindex 8183ff61f8eb..53def9cfce2a 100644--- a/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml+++ b/.semgrep/rules/devex/inbound-webhooks-go-through-ingress.yaml@@ -116,9 +116,7 @@ rules:# so the rule holds whether or not the migrations land with it.- /ee/api/vercel/vercel_webhooks.py- /ee/partners/stripe/api/provisioning/signature.py- - /posthog/api/github_webhooks/signature.py- /posthog/models/integration/slack.py- - /products/conversations/backend/api/github_events.py- /products/conversations/backend/api/slack_events.py- /products/conversations/backend/mailgun.py- /products/conversations/backend/support_slack.pydiff --git a/docs/internal/github-webhooks.md b/docs/internal/github-webhooks.mddeleted file mode 100644index b9105062ed78..000000000000--- a/docs/internal/github-webhooks.md+++ /dev/null@@ -1,62 +0,0 @@-# GitHub webhooks--The GitHub App sends deliveries to `/webhooks/github/`.-`/webhooks/github/pr/` is an alias for the same view.--## Transport--`posthog/api/github_webhooks/views.py` checks the method and signature, parses the payload, and calls the dispatcher.-`posthog/urls.py` only registers the routes.-The secret remains the `GITHUB_WEBHOOK_SECRET` instance setting.--`handlers.py` lists the consumers for each event type.-Keep product-specific work behind the product's facade.-Product imports remain deferred so loading URL configuration does not load every consumer.--`dispatch.py` calls each consumer independently.-An exception does not prevent sibling consumers from running.-The first consumer that returns an HTTP response determines the response; otherwise, the dispatcher returns 200.-An HTTP error response alone does not raise an exception or release the delivery's deduplication entry.--Deduplication uses the delivery ID and consumer name, with a 24-hour cache expiry.-An exception releases that consumer's entry so a redelivery can retry it.-A cache failure allows processing to continue.-Keep consumer names stable when moving code: names are part of the cache key.--## PR analytics--`pull_requests.capture_pr_event` emits `pr_created`, `pr_closed`, `pr_merged`, and `pr_reviewed`.-It accepts a `PullRequestAttribution` value, independent of Task models.-The value carries the source product, team, default actor, groups, and product-specific properties.-A product can supply its own run identifier without creating a Task or implementing another emitter.--The caller owns PR matching, team authorization, event eligibility, and product side effects.-Tasks keeps those operations in `products/tasks/backend/webhooks.py`.-Its review handler ignores bots and accepts submitted reviews.-Signals owns report-assignment updates and GitHub user lookup through its facade.--The shared emitter resolves merger and reviewer attribution and applies common PR properties.-It preserves the caller's default actor when the GitHub user cannot be resolved.-Canonical PR properties, `team_id`, and `pr_source` take precedence over product properties.-Content is omitted unless attribution explicitly enables it.--Passing no attribution uses the external-PR fallback: the first team linked to the installation, in team-ID order.-External events omit PR title, body, labels, requested reviewers, and draft status.--Lifecycle event UUIDs derive from PR URL and event name.-Review UUIDs also include the review ID.-Redeliveries therefore reuse an event UUID.-Repeated close/reopen cycles retain the existing once-per-PR `pr_closed` UUID.-This analytics deduplication does not order product state updates.--Capture is best effort.-Failures increment the existing dropped-event metric and do not prevent subsequent Task effects.-The metric names retain their `posthog_tasks_github_webhook_` prefix for continuity.--## Adding attribution from another product--Resolve the PR within the product's authorized installation and team scope.-Build `PullRequestAttribution` and pass it to the shared emitter from the PR processing path.-Keep product state writes in the product.-When adding another owner to the shared webhook path, resolve ownership before capture so the delivery emits one event.-Wizard artifact matching and lifecycle persistence are separate work.diff --git a/owners.yaml b/owners.yamlindex a7e0918f123d..6919b830f6f6 100644--- a/owners.yaml+++ b/owners.yaml@@ -85,10 +85,8 @@ rules:# The URL surface and the inbound webhook transport: shared plumbing every product# lands on, so a change here reaches further than the product that prompted it.- match:- - '/docs/internal/github-webhooks.md'- '/docs/internal/url-routing.md'- '/posthog/api/__init__.py'- - '/posthog/api/github_webhooks/'- '/posthog/api/rest_router.py'- '/posthog/api/routing.py'- '/posthog/ee_urls.py'diff --git a/posthog/api/github_callback/installation_events.py b/posthog/api/github_callback/installation_events.pyindex b323fdf4c85c..942d65cb7151 100644--- a/posthog/api/github_callback/installation_events.py+++ b/posthog/api/github_callback/installation_events.py@@ -38,8 +38,8 @@ logger = structlog.get_logger(__name__)def handle_installation_event(payload: dict) -> HttpResponse:"""Process a pre-verified GitHub ``installation`` webhook event.- Called from ``posthog.urls.github_webhook`` after signature verification and- JSON parsing. ``action == "deleted"`` triggers integration cleanup; ``"created"``+ Registered by the GitHub incarnation as the ``installation_lifecycle`` consumer, so it+ runs after signature verification and JSON parsing. ``action == "deleted"`` triggers integration cleanup; ``"created"``resolves matching pending install requests. Reversible actions (suspend/unsuspend)and other lifecycle noise are ignored."""diff --git a/posthog/api/github_webhooks/__init__.py b/posthog/api/github_webhooks/__init__.pydeleted file mode 100644index 0a5a77631d76..000000000000--- a/posthog/api/github_webhooks/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""GitHub App webhook transport and shared pull request analytics."""diff --git a/posthog/api/github_webhooks/contracts.py b/posthog/api/github_webhooks/contracts.pydeleted file mode 100644index 86d63b48ad6d..000000000000--- a/posthog/api/github_webhooks/contracts.py+++ /dev/null@@ -1,17 +0,0 @@-from collections.abc import Mapping-from dataclasses import field--from posthog.dataclasses import frozen--type AnalyticsProperty = str | int | float | bool | None | list[AnalyticsProperty] | dict[str, AnalyticsProperty]---@frozen-class PullRequestAttribution:- source: str- team_id: int- distinct_id: str- groups: Mapping[str, str]- properties: Mapping[str, AnalyticsProperty] = field(default_factory=dict)- include_content: bool = False- send_feature_flags: bool = Falsediff --git a/posthog/api/github_webhooks/dispatch.py b/posthog/api/github_webhooks/dispatch.pydeleted file mode 100644index e9d832737cac..000000000000--- a/posthog/api/github_webhooks/dispatch.py+++ /dev/null@@ -1,87 +0,0 @@-from collections.abc import Callable-from typing import Any--from django.core.cache import cache-from django.http import HttpRequest, HttpResponse--import structlog--from posthog.exceptions_capture import capture_exception--logger = structlog.get_logger(__name__)-GithubWebhookHandler = Callable[[HttpRequest, str, dict[str, Any], str], HttpResponse | None]--GITHUB_WEBHOOK_DELIVERY_DEDUP_TTL_SECONDS = 24 * 60 * 60---def _is_duplicate_github_webhook_delivery(handler_name: str, delivery_id: str) -> bool:- """Redis-backed per-handler delivery dedup, fail-open when the cache backend errors.-- Keyed per handler, not just per delivery id: one GitHub delivery legitimately fans- out to multiple handlers (e.g. a pull_request delivery reaches both the tasks PR- backstop and the Loops handler), so a delivery-wide key would starve every handler- but the first. This sits alongside each consumer's own dedup (e.g. the conversations- Celery task) rather than replacing it.- """- key = _github_webhook_delivery_key(handler_name, delivery_id)- try:- return not cache.add(key, True, timeout=GITHUB_WEBHOOK_DELIVERY_DEDUP_TTL_SECONDS)- except Exception:- logger.warning(- "github_webhook_dedup_cache_failed", handler=handler_name, delivery_id=delivery_id, exc_info=True- )- return False---def _github_webhook_delivery_key(handler_name: str, delivery_id: str) -> str:- return f"github_webhook_delivery:{handler_name}:{delivery_id}"---def _release_github_webhook_delivery(handler_name: str, delivery_id: str) -> None:- """Drop the dedup mark after a handler failed, so GitHub's redelivery of the same- GUID gets processed instead of silently skipped (the mark is set before the handler- runs, so a failure would otherwise burn the delivery for 24h)."""- try:- cache.delete(_github_webhook_delivery_key(handler_name, delivery_id))- except Exception:- logger.warning(- "github_webhook_dedup_release_failed", handler=handler_name, delivery_id=delivery_id, exc_info=True- )---def dispatch_github_event(- request: HttpRequest,- event_type: str,- payload: dict[str, Any],- delivery_id: str,- handlers: list[tuple[str, GithubWebhookHandler]],-) -> HttpResponse:-- logger.info(- "github_webhook_dispatch",- event_type=event_type,- delivery_id=delivery_id,- handlers_matched=[name for name, _ in handlers],- )-- response: HttpResponse | None = None- for name, handler in handlers:- if delivery_id and _is_duplicate_github_webhook_delivery(name, delivery_id):- logger.info("github_webhook_handler_deduped", event_type=event_type, delivery_id=delivery_id, handler=name)- continue-- try:- handler_response = handler(request, event_type, payload, delivery_id)- except Exception as e:- logger.exception(- "github_webhook_handler_failed", event_type=event_type, delivery_id=delivery_id, handler=name- )- capture_exception(e)- if delivery_id:- _release_github_webhook_delivery(name, delivery_id)- continue-- if response is None and handler_response is not None:- response = handler_response-- return response if response is not None else HttpResponse(status=200)diff --git a/posthog/api/github_webhooks/handlers.py b/posthog/api/github_webhooks/handlers.pydeleted file mode 100644index 3de824bcaf51..000000000000--- a/posthog/api/github_webhooks/handlers.py+++ /dev/null@@ -1,112 +0,0 @@-from typing import Any--from django.http import HttpRequest, HttpResponse--from posthog.api.github_webhooks.dispatch import GithubWebhookHandler---def _dispatch_conversations_event(- request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str-) -> HttpResponse:- from products.conversations.backend.api.github_events import (- dispatch_github_event, # noqa: PLC0415 - keep product dependencies off the URL import path- )-- return dispatch_github_event(request, event_type, payload)---def _dispatch_pull_request_event(- request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str-) -> HttpResponse:- from products.tasks.backend.facade.webhooks import (- handle_pull_request_event, # noqa: PLC0415 - keep product dependencies off the URL import path- )-- return handle_pull_request_event(payload)---def _dispatch_pull_request_review_event(- request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str-) -> HttpResponse:- from products.tasks.backend.facade.webhooks import (- handle_pull_request_review_event, # noqa: PLC0415 - keep product dependencies off the URL import path- )-- return handle_pull_request_review_event(payload)---def _dispatch_installation_event(- request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str-) -> HttpResponse:- from posthog.api.github_callback.installation_events import (- handle_installation_event, # noqa: PLC0415 - keep product dependencies off the URL import path- )-- return handle_installation_event(payload)---def _dispatch_installation_repositories_event(- request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str-) -> HttpResponse:- from posthog.api.github_callback.installation_events import (- handle_installation_repositories_event, # noqa: PLC0415 - keep product dependencies off the URL import path- )-- return handle_installation_repositories_event(payload)---def _dispatch_loop_triggers(request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str) -> None:- from products.tasks.backend.facade.webhooks import (- handle_github_event_for_loops, # noqa: PLC0415 - keep product dependencies off the URL import path- )-- handle_github_event_for_loops(event_type, payload, delivery_id)- return None---def _dispatch_workflow_triggers(- request: HttpRequest, event_type: str, payload: dict[str, Any], delivery_id: str-) -> None:- from products.workflows.backend.github_workflow_events import (- emit_github_event, # noqa: PLC0415 - keep product dependencies off the URL import path- )-- emit_github_event(event_type, payload, delivery_id)- return None---# event_type -> ordered list of (handler_name, handler). Order matters only in that-# the first handler in a bucket to return a non-None HttpResponse determines the-# response sent back to GitHub; the pre-existing single handler in each bucket keeps-# that slot so its response is unchanged by additive handlers registered after it.-GITHUB_WEBHOOK_HANDLERS: dict[str, list[tuple[str, GithubWebhookHandler]]] = {- "issues": [- ("conversations", _dispatch_conversations_event),- ("loops", _dispatch_loop_triggers),- ("workflows", _dispatch_workflow_triggers),- ],- "issue_comment": [- ("conversations", _dispatch_conversations_event),- ("loops", _dispatch_loop_triggers),- ("workflows", _dispatch_workflow_triggers),- ],- "pull_request": [- ("tasks_pr_backstop", _dispatch_pull_request_event),- ("loops", _dispatch_loop_triggers),- ("workflows", _dispatch_workflow_triggers),- ],- "pull_request_review": [- ("tasks_pr_review", _dispatch_pull_request_review_event),- ("workflows", _dispatch_workflow_triggers),- ],- "installation": [- ("installation_lifecycle", _dispatch_installation_event),- ],- "installation_repositories": [- ("installation_repositories", _dispatch_installation_repositories_event),- ],- "push": [- ("loops", _dispatch_loop_triggers),- ("workflows", _dispatch_workflow_triggers),- ],-}diff --git a/posthog/api/github_webhooks/signature.py b/posthog/api/github_webhooks/signature.pydeleted file mode 100644index de59f579c8d7..000000000000--- a/posthog/api/github_webhooks/signature.py+++ /dev/null@@ -1,24 +0,0 @@-import hmac--from posthog.models.instance_setting import get_instance_setting---def verify_github_signature(payload: bytes, signature: str | None, secret: str) -> bool:- """- Verify the GitHub webhook signature using HMAC-SHA256.-- GitHub sends a signature in the X-Hub-Signature-256 header in the format:- sha256=<hex_digest>- """- if not signature or not signature.startswith("sha256="):- return False-- expected_signature = "sha256=" + hmac.digest(secret.encode("utf-8"), payload, "sha256").hex()-- return hmac.compare_digest(expected_signature, signature)---def get_github_webhook_secret() -> str | None:- """Get the GitHub webhook secret from instance settings."""- secret = get_instance_setting("GITHUB_WEBHOOK_SECRET")- return secret if secret else Nonediff --git a/posthog/api/github_webhooks/views.py b/posthog/api/github_webhooks/views.pydeleted file mode 100644index 3ee8a3a0e300..000000000000--- a/posthog/api/github_webhooks/views.py+++ /dev/null@@ -1,38 +0,0 @@-import json--from django.http import HttpRequest, HttpResponse-from django.views.decorators.csrf import csrf_exempt--from posthog.api.github_webhooks.dispatch import dispatch_github_event-from posthog.api.github_webhooks.handlers import GITHUB_WEBHOOK_HANDLERS-from posthog.api.github_webhooks.signature import get_github_webhook_secret, verify_github_signature---@csrf_exempt-def github_webhook(request: HttpRequest) -> HttpResponse:- """Unified GitHub App webhook dispatcher.-- Verifies the HMAC-SHA256 signature once, parses JSON once, then routes by- ``X-GitHub-Event`` to every registered product handler. Each handler runs in- isolation: one handler raising is logged and captured but never blocks another- handler or the response sent back to GitHub.- """- if request.method != "POST":- return HttpResponse(status=405)-- secret = get_github_webhook_secret()- if not secret:- return HttpResponse("Webhook not configured", status=500)-- signature = request.headers.get("X-Hub-Signature-256")- if not verify_github_signature(request.body, signature, secret):- return HttpResponse("Invalid signature", status=403)-- try:- payload = json.loads(request.body)- except json.JSONDecodeError:- return HttpResponse("Invalid JSON", status=400)-- event_type = request.headers.get("X-GitHub-Event", "")- delivery_id = request.headers.get("X-GitHub-Delivery", "")- return dispatch_github_event(request, event_type, payload, delivery_id, GITHUB_WEBHOOK_HANDLERS.get(event_type, []))diff --git a/posthog/api/test/test_github_installation_webhook.py b/posthog/api/test/test_github_installation_webhook.pyindex 8e6ebc7e84b9..5a55a3597976 100644--- a/posthog/api/test/test_github_installation_webhook.py+++ b/posthog/api/test/test_github_installation_webhook.py@@ -139,7 +139,7 @@ class TestGitHubInstallationWebhook(TestCase):user=self.user, kind="github", integration_id=installation_id, config={}, sensitive_config={})- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")def test_deleted_removes_all_rows_and_does_not_call_github(self, mock_client_request, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -148,40 +148,40 @@ class TestGitHubInstallationWebhook(TestCase):response = self._post({"action": "deleted", "installation": {"id": 12345}})- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.assertFalse(Integration.objects.filter(kind="github", integration_id="12345").exists())self.assertFalse(UserIntegration.objects.filter(kind="github", integration_id="12345").exists())# Inbound side must never call out to GitHub (loop prevention).mock_client_request.assert_not_called()- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_deleted_with_no_matching_rows_is_idempotent(self, mock_get_secret):mock_get_secret.return_value = self.webhook_secretresponse = self._post({"action": "deleted", "installation": {"id": 99999}})- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)@parameterized.expand([("suspend",), ("unsuspend",)])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_reversible_action_does_not_delete_rows(self, action, mock_get_secret):mock_get_secret.return_value = self.webhook_secretself._team_integration("12345")response = self._post({"action": action, "installation": {"id": 12345}})- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.assertTrue(Integration.objects.filter(kind="github", integration_id="12345").exists())- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- def test_missing_installation_id_returns_200(self, mock_get_secret):+ @patch("posthog.ingress.github.provider.get_instance_setting")+ def test_missing_installation_id_is_accepted(self, mock_get_secret):mock_get_secret.return_value = self.webhook_secretresponse = self._post({"action": "deleted"})- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_created_approves_the_requesters_pending_request_by_github_user_id(self, mock_get_secret):mock_get_secret.return_value = self.webhook_secretother_user = User.objects.create(email="[email protected]", distinct_id="other-requester-1")@@ -208,7 +208,7 @@ class TestGitHubInstallationWebhook(TestCase):})- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)matching.refresh_from_db()self.assertEqual(matching.status, GitHubInstallRequest.Status.APPROVED)self.assertEqual(matching.installation_id, "55555")@@ -220,7 +220,7 @@ class TestGitHubInstallationWebhook(TestCase):self.assertEqual(someone_else.status, GitHubInstallRequest.Status.PENDING)self.assertIsNone(someone_else.installation_id)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_created_without_a_requester_is_a_noop(self, mock_get_secret):# An owner installing for themselves sends no requester, and must not sweep up pending rows.mock_get_secret.return_value = self.webhook_secret@@ -233,11 +233,11 @@ class TestGitHubInstallationWebhook(TestCase):response = self._post({"action": "created", "installation": {"id": 55555}})- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)pending.refresh_from_db()self.assertEqual(pending.status, GitHubInstallRequest.Status.PENDING)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_installation_repositories_updates_selection_and_invalidates_caches(self, mock_get_secret):mock_get_secret.return_value = self.webhook_secretteam_row = self._team_integration("12345")@@ -259,7 +259,7 @@ class TestGitHubInstallationWebhook(TestCase):event_type="installation_repositories",)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)team_row.refresh_from_db()user_row.refresh_from_db()untouched.refresh_from_db()@@ -270,7 +270,7 @@ class TestGitHubInstallationWebhook(TestCase):self.assertEqual(untouched.config["repository_selection"], "selected")self.assertIsNotNone(untouched.repository_cache_updated_at)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_invalid_signature_returns_403_and_keeps_rows(self, mock_get_secret):mock_get_secret.return_value = self.webhook_secretself._team_integration("12345")diff --git a/posthog/github/README.md b/posthog/github/README.mdnew file mode 100644index 000000000000..8aa43f7ffa3e--- /dev/null+++ b/posthog/github/README.md@@ -0,0 +1,22 @@+# GitHub domain helpers++Code about GitHub that more than one product needs and that is neither transport nor an outbound call.+Inbound transport is `posthog/ingress/github/`, outbound calls are `posthog/egress/github/`, and neither imports the other.+Both may import this package.++- `installations.py` reads the installation id off a payload and resolves the teams linked to it.+- `attribution.py` resolves a GitHub login to an organization member, under a bounded statement timeout, so a slow lookup degrades to no attribution.+- `pull_request_events.py` emits the canonical `pr_created`, `pr_closed`, `pr_merged` and `pr_reviewed` analytics events.+- `metrics.py` holds the Prometheus counters for dropped events and attribution outcomes.++## PR analytics++A consumer that owns a pull request builds a `PullRequestAttribution` and passes it to `capture_pr_event`.+The caller owns PR matching, team authorization and product side effects; the emitter owns actor resolution and the common PR properties.++- Canonical PR properties, `team_id` and `pr_source` take precedence over the caller's properties.+- The caller's default actor stays when the GitHub user cannot be resolved.+- PR title, body, labels, reviewers and draft status are sent only when the attribution sets `include_content`.+- With no attribution, the event goes to the first team linked to the installation, in team-id order, without content.+- Event UUIDs derive from the PR URL and the event name, plus the review id for reviews, so a redelivery reuses the UUID and a close/reopen cycle keeps one `pr_closed`.+- Capture is best effort: a failure increments the dropped-event counter and never blocks the caller.diff --git a/posthog/github/__init__.py b/posthog/github/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/api/github_webhooks/attribution.py b/posthog/github/attribution.pysimilarity index 89%rename from posthog/api/github_webhooks/attribution.pyrename to posthog/github/attribution.pyindex 30a25a641960..92f030a64c4c 100644--- a/posthog/api/github_webhooks/attribution.py+++ b/posthog/github/attribution.py@@ -1,7 +1,7 @@import structlogfrom social_django.models import UserSocialAuth-from posthog.api.github_webhooks.metrics import GitHubWebhookAttributionOutcome, observe_github_webhook_attribution+from posthog.github.metrics import GitHubWebhookAttributionOutcome, observe_github_webhook_attributionfrom posthog.ingress.dispatch.database import bounded_statement_timeout, is_statement_timeoutfrom posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembership@@ -9,8 +9,6 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.models.user_integration import UserIntegration-from products.signals.backend.facade.github import resolve_github_login_distinct_id-logger = structlog.get_logger(__name__)# Cap the org-member lookup that attributes the merger (and reviewer). GitHub gives a@@ -34,6 +32,11 @@ def _resolve_github_login_distinct_id(login: str | None, team_id: int) -> str |"""if not login:return None++ from products.signals.backend.facade.github import (+ resolve_github_login_distinct_id, # noqa: PLC0415 - core must not import a product at module level+ )+try:with bounded_statement_timeout(_ATTRIBUTION_STATEMENT_TIMEOUT_MS, models=_ATTRIBUTION_MODELS):resolved = resolve_github_login_distinct_id(str(login), team_id)@@ -59,9 +62,8 @@ def _merged_by_attribution(payload: dict, team_id: int) -> tuple[dict, str | NonMerging is the one unambiguous personal act in the loop, so when the merger's GitHublogin maps to an org member the pr_merged event attributes to them. Without a match the- event keeps the task's assigned user (an auto-resolved reviewer or fallback for- auto-started reports), so a consumer tells the two apart by the presence of- pr_merged_by_distinct_id.+ event keeps the caller's default actor, so a consumer tells the two apart by the presence+ of pr_merged_by_distinct_id."""merged_by = (payload.get("pull_request") or {}).get("merged_by") or {}login = merged_by.get("login")diff --git a/posthog/api/github_webhooks/integrations.py b/posthog/github/installations.pysimilarity index 75%rename from posthog/api/github_webhooks/integrations.pyrename to posthog/github/installations.pyindex eeffddf25572..a8941fc614e7 100644--- a/posthog/api/github_webhooks/integrations.py+++ b/posthog/github/installations.py@@ -2,32 +2,32 @@ from posthog.models.integration import Integrationfrom posthog.models.team.team import Team-def _installation_id(payload: dict) -> str | 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")- return None if installation_id is None else str(installation_id)+ raw_installation_id = (payload.get("installation") or {}).get("id")+ return None if raw_installation_id is None else str(raw_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"+SCOPE_DB_ALIAS = "default"-def _installation_team_ids(payload: dict) -> list[int]:+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 — thelookups that take this fall back to their unscoped behaviour in that case."""- external_id = _installation_id(payload)+ external_id = installation_id(payload)if external_id is None:return []# One installation can map to multiple teams; order_by makes attribution deterministic.return list(- Integration.objects.using(_SCOPE_DB_ALIAS)+ Integration.objects.using(SCOPE_DB_ALIAS).filter(kind="github", integration_id=external_id).order_by("team_id").values_list("team_id", flat=True)@@ -35,7 +35,7 @@ def _installation_team_ids(payload: dict) -> list[int]:def _resolve_external_team(payload: dict) -> Team | None:- team_ids = _installation_team_ids(payload)+ team_ids = installation_team_ids(payload)if not team_ids:return Nonereturn Team.objects.filter(pk=team_ids[0]).first()diff --git a/posthog/api/github_webhooks/metrics.py b/posthog/github/metrics.pysimilarity index 100%rename from posthog/api/github_webhooks/metrics.pyrename to posthog/github/metrics.pydiff --git a/posthog/api/github_webhooks/pull_requests.py b/posthog/github/pull_request_events.pysimilarity index 89%rename from posthog/api/github_webhooks/pull_requests.pyrename to posthog/github/pull_request_events.pyindex 64c51fd05386..6fff400f7765 100644--- a/posthog/api/github_webhooks/pull_requests.py+++ b/posthog/github/pull_request_events.py@@ -1,18 +1,33 @@"""Canonical PR analytics for product-owned and external pull requests."""import uuid+from collections.abc import Mapping+from dataclasses import fieldimport structlogimport posthoganalytics-from posthog.api.github_webhooks.attribution import _merged_by_attribution, _resolve_github_login_distinct_id-from posthog.api.github_webhooks.contracts import PullRequestAttribution-from posthog.api.github_webhooks.integrations import _resolve_external_team-from posthog.api.github_webhooks.metrics import GitHubWebhookAnalyticsEvent, observe_github_webhook_pr_event_dropped+from posthog.dataclasses import frozenfrom posthog.event_usage import groups+from posthog.github.attribution import _merged_by_attribution, _resolve_github_login_distinct_id+from posthog.github.installations import _resolve_external_team+from posthog.github.metrics import GitHubWebhookAnalyticsEvent, observe_github_webhook_pr_event_droppedlogger = structlog.get_logger(__name__)+type AnalyticsProperty = str | int | float | bool | None | list[AnalyticsProperty] | dict[str, AnalyticsProperty]+++@frozen+class PullRequestAttribution:+ source: str+ team_id: int+ distinct_id: str+ groups: Mapping[str, str]+ properties: Mapping[str, AnalyticsProperty] = field(default_factory=dict)+ include_content: bool = False+ send_feature_flags: bool = False+# 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")diff --git a/posthog/github/test/__init__.py b/posthog/github/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/api/test/test_github_webhooks.py b/posthog/github/test/test_pull_request_events.pysimilarity index 52%rename from posthog/api/test/test_github_webhooks.pyrename to posthog/github/test/test_pull_request_events.pyindex a3e7f2240eec..f63134b805f5 100644--- a/posthog/api/test/test_github_webhooks.py+++ b/posthog/github/test/test_pull_request_events.py@@ -1,17 +1,13 @@import uuid-from unittest.mock import Mock, patch+from unittest.mock import patch-from django.core.cache import cache-from django.http import HttpResponse-from django.test import RequestFactory, SimpleTestCase, override_settings+from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.api.github_webhooks.contracts import PullRequestAttribution-from posthog.api.github_webhooks.dispatch import dispatch_github_event-from posthog.api.github_webhooks.metrics import GitHubWebhookAnalyticsEvent-from posthog.api.github_webhooks.pull_requests import capture_pr_event+from posthog.github.metrics import GitHubWebhookAnalyticsEvent+from posthog.github.pull_request_events import PullRequestAttribution, capture_pr_eventclass TestProductPullRequestAttribution(SimpleTestCase):@@ -51,14 +47,14 @@ class TestProductPullRequestAttribution(SimpleTestCase):with (patch(- "posthog.api.github_webhooks.attribution.resolve_github_login_distinct_id", return_value="reviewer-id"+ "products.signals.backend.facade.github.resolve_github_login_distinct_id", return_value="reviewer-id"),- patch("posthog.api.github_webhooks.attribution.bounded_statement_timeout"),+ patch("posthog.github.attribution.bounded_statement_timeout"),patch(- "posthog.api.github_webhooks.pull_requests._resolve_github_login_distinct_id",+ "posthog.github.pull_request_events._resolve_github_login_distinct_id",return_value="reviewer-id",),- patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture") as capture,+ patch("posthog.github.pull_request_events.posthoganalytics.capture") as capture,):for _ in range(2):capture_pr_event(payload, attribution, event)@@ -83,33 +79,3 @@ class TestProductPullRequestAttribution(SimpleTestCase):kwargs["uuid"],str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:{event}{suffix}")),)---@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})-class TestGitHubDispatch(SimpleTestCase):- def setUp(self) -> None:- cache.clear()-- @parameterized.expand([("success", False), ("failure", True)])- def test_fanout_preserves_response_and_retries_only_failed_consumer(self, _name: str, fails: bool) -> None:- request = RequestFactory().post("/webhooks/github/", data="{}", content_type="application/json")- first = (- Mock(side_effect=RuntimeError("consumer failed")) if fails else Mock(return_value=HttpResponse(status=202))- )- second = Mock(return_value=HttpResponse(status=204))- with patch("posthog.api.github_webhooks.dispatch.capture_exception"):- response = dispatch_github_event(- request, "pull_request", {}, "delivery-example", [("tasks_pr_backstop", first), ("loops", second)]- )- self.assertEqual(response.status_code, 204 if fails else 202)- self.assertEqual(second.call_count, 1)- first.side_effect = None- first.return_value = HttpResponse(status=202)- response = dispatch_github_event(- request, "pull_request", {}, "delivery-example", [("tasks_pr_backstop", first), ("loops", second)]- )- self.assertEqual(response.status_code, 202 if fails else 200)- self.assertEqual(first.call_count, 2 if fails else 1)- self.assertEqual(second.call_count, 1)- self.assertTrue(cache.get("github_webhook_delivery:tasks_pr_backstop:delivery-example"))- self.assertTrue(cache.get("github_webhook_delivery:loops:delivery-example"))diff --git a/posthog/ingress/README.md b/posthog/ingress/README.mdindex 741a39f96307..2c2e6b19f20e 100644--- a/posthog/ingress/README.md+++ b/posthog/ingress/README.md@@ -32,7 +32,6 @@ Adding a provider is another `<provider>/` folder, not a change to the mechanismThe GitHub endpoints and the SES one are declared in `posthog/urls.py`.The others are declared by the product that owns them.-See [`url-routing.md`](../../docs/internal/url-routing.md) for the routing rules those declarations follow, and [`github-webhooks.md`](../../docs/internal/github-webhooks.md) for the GitHub specifics.The Vapi endpoint sits behind a per-IP throttle the product owns, because ingress has no throttle lane and the endpoint is public.@@ -55,6 +54,7 @@ A consumer that wants asynchronous work enqueues its own task and answers immediThe HTTP response is a transport receipt: the verification result, the method, and the payload decide the status, and consumer return values are ignored.A consumer that fails must not turn a verified delivery into a 500 the provider will replay against every other consumer too.If a provider's protocol needs the response body to say something, the incarnation answers that handshake before dispatch.+The one exception is a failed forward to the owning region, which is a transport failure rather than a consumer outcome — see [Regional forwarding](#regional-forwarding).**Ingress does not promise an order.**Consumers are independent by construction; anything that depends on another consumer's result belongs in one consumer.@@ -117,6 +117,32 @@ Both controls exist because the incidents on the GitHub webhook path came from uThe fixes that worked bounded the queries: [#83852](https://github.com/PostHog/posthog/pull/83852) scoped the run lookup to the installation's teams and put a statement timeout on the attribution lookup, and [#87779](https://github.com/PostHog/posthog/pull/87779) added the indexes it needed.Ingress carries both as general controls, so the next endpoint gets them without rediscovering the same failure.+## Regional forwarding++A third party holds one callback URL, which points at the primary region (EU), so a delivery about a resource the other region (US) owns still arrives here first.+Ingress owns the forward, because what is replayed is the signed body — a consumer only ever sees the parsed mapping.++A consumer whose resources are split by region declares `ownership`, a callable that takes the delivery and answers a `DeliveryOwnership`:++- `LOCAL` — this region holds the resource. Nothing changes: local dispatch always runs.+- `ELSEWHERE` — the other region holds it. The request is forwarded.+- `UNDECIDED` — nothing in the delivery says, so nothing is forwarded.++Every delivery in the request is assessed first, and the request is then forwarded **once**, when any consumer answered `ELSEWHERE`.+One forward per request rather than per delivery, because the unit being replayed is the HTTP request.+Local dispatch runs either way: a consumer that answered `ELSEWHERE` no-ops on its own, and the other consumers on the endpoint are unaffected.+Only the primary region forwards; on the secondary region an `ELSEWHERE` answer is logged as `ingress_delivery_unowned_here`, because a local miss there is that consumer's unresolved routing rather than proof that no region owns the delivery.+The replay carries the signed bytes and the provider's own headers, but never the headers that name the host this region answered on: `Host`, `X-Forwarded-Host`, `X-Forwarded-Port`, `X-Forwarded-Proto` and `Forwarded`.+The receiving region reads which region it is off the connection it receives, so a forwarded host would make it forward the delivery on again.++The ownership lookup runs inside the request, before dispatch, and inside the same wall-clock budget.+A lookup that reads the database must be bounded with `bounded_statement_timeout(ms, models=...)`.+A lookup that raises is logged, captured, counted as `failed` and treated as `UNDECIDED`, so one consumer cannot cost the delivery the receipt it earned by signing.++A failed forward keeps the receipt by default.+A provider that redelivers on a non-2xx (Slack does, GitHub does not) sets `forward_failure_status` on its incarnation, and the view answers that status with outcome `forward_failed` instead — so the provider sends the delivery again rather than losing it.+That is the transport deciding the response, not a consumer.+## Adding a providerAdd a `<provider>/` subpackage with a `provider.py` holding three things (see `github/` for the full shape, `vapi/` for a small one):@@ -158,9 +184,11 @@ A provider that sends no delivery id skips dedup entirely, and its own README sa## Observability-- **`posthog_ingress_deliveries_total{provider,app,outcome}`** — what the transport answered: `accepted`, `method_not_allowed`, `not_configured`, `invalid_signature`, `invalid_payload`. A consumer failure is not here, because a failing consumer still gets a 2xx receipt.+- **`posthog_ingress_deliveries_total{provider,app,outcome}`** — what the transport answered: `accepted`, `method_not_allowed`, `not_configured`, `invalid_signature`, `invalid_payload`, `forward_failed`. A consumer failure is not here, because a failing consumer still gets a 2xx receipt.- **`posthog_ingress_consumer_runs_total{provider,consumer,outcome}`** — `succeeded`, `failed`, `deduped`, `budget_exceeded`.- **`posthog_ingress_consumer_duration_seconds{provider,consumer}`** — where a delivery's budget actually went.+- **`posthog_ingress_ownership_total{provider,consumer,outcome}`** — what a consumer answered when asked which region owns the delivery: `local`, `elsewhere`, `undecided`, `failed`.+- **`posthog_ingress_forwards_total{provider,app,outcome}`** — what the owning region answered a forwarded request: `forwarded`, `rejected`, `failed`.- **`ingress_delivery_invalid_payload`** — a warning log with the parser error text for a verified delivery whose body did not parse. The counter above cannot carry that text.A secret in a URL or header is the credential and never becomes a metric label.diff --git a/posthog/ingress/contracts.py b/posthog/ingress/contracts.pyindex 2467c70dc135..63795ddc66eb 100644--- a/posthog/ingress/contracts.py+++ b/posthog/ingress/contracts.py@@ -2,11 +2,20 @@from collections.abc import Callable, Mappingfrom datetime import datetime+from enum import Enumfrom typing import Anyfrom posthog.dataclasses import frozen+class DeliveryOwnership(Enum):+ """Where the resource a delivery is about lives, as the consumer that owns it sees it."""++ LOCAL = "local" # this region holds the resource; dispatch here+ ELSEWHERE = "elsewhere" # the resource lives in the other region; forward the request+ UNDECIDED = "undecided" # nothing in the delivery says; dispatch here, forward nothing++@frozenclass WebhookDelivery:"""One inbound delivery, already verified and parsed.@@ -41,6 +50,10 @@ class WebhookConsumer:# Off for a consumer that already keys its own recovery on the provider's delivery id: the# 24 h mark would otherwise stop a redelivery from ever reaching that recovery path.dedup: bool = True+ # A consumer whose resources are split by region answers where this delivery's resource lives,+ # and ingress forwards the signed request when the answer is elsewhere. A lookup inside must be+ # bounded (`bounded_statement_timeout`): it runs in the request, before dispatch.+ ownership: Callable[[WebhookDelivery], DeliveryOwnership] | None = None@frozendiff --git a/posthog/ingress/dispatch/dispatcher.py b/posthog/ingress/dispatch/dispatcher.pyindex 48e9edd4f5c5..09240b64f1d8 100644--- a/posthog/ingress/dispatch/dispatcher.py+++ b/posthog/ingress/dispatch/dispatcher.py@@ -5,11 +5,11 @@ import timeimport structlogfrom posthog.exceptions_capture import capture_exception-from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery+from posthog.ingress.contracts import DeliveryOwnership, WebhookConsumer, WebhookDeliveryfrom posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_secondsfrom posthog.ingress.dispatch.dedup import DeliveryDedupfrom posthog.ingress.dispatch.registry import ConsumerRegistry-from posthog.ingress.observability.metrics import observe_consumer_duration, observe_consumer_run+from posthog.ingress.observability.metrics import observe_consumer_duration, observe_consumer_run, observe_ownershiplogger = structlog.get_logger(__name__)@@ -71,6 +71,52 @@ class WebhookDispatcher:provider=delivery.provider, consumer=consumer.name, seconds=time.monotonic() - started)+ def _ask_ownership(self, consumer: WebhookConsumer, delivery: WebhookDelivery) -> DeliveryOwnership:+ if consumer.ownership is None:+ return DeliveryOwnership.UNDECIDED+ try:+ answer = consumer.ownership(delivery)+ except Exception as error:+ # Isolated like a handler is: a consumer that cannot answer must not cost the delivery+ # the receipt it already earned by signing, nor stop another consumer from answering.+ logger.exception(+ "ingress_ownership_failed",+ provider=delivery.provider,+ consumer=consumer.name,+ event_type=delivery.event_type,+ delivery_id=delivery.delivery_id,+ )+ capture_exception(error)+ observe_ownership(provider=delivery.provider, consumer=consumer.name, outcome="failed")+ return DeliveryOwnership.UNDECIDED+ observe_ownership(provider=delivery.provider, consumer=consumer.name, outcome=answer.value)+ return answer++ def ownership_of(self, delivery: WebhookDelivery) -> tuple[DeliveryOwnership, tuple[str, ...]]:+ """Where this delivery's resource lives, and which consumers said it lives elsewhere.++ Any one consumer answering `ELSEWHERE` is enough to forward the request, because the+ forward is the whole request rather than one consumer's share of it. A `LOCAL` answer+ changes nothing: local dispatch runs either way.+ """+ answers: list[DeliveryOwnership] = []+ elsewhere: list[str] = []+ for consumer in self._registry.consumers_for(+ provider=delivery.provider, app=delivery.app, event_type=delivery.event_type+ ):+ if consumer.ownership is None:+ continue+ answer = self._ask_ownership(consumer, delivery)+ answers.append(answer)+ if answer is DeliveryOwnership.ELSEWHERE:+ elsewhere.append(consumer.name)++ if elsewhere:+ return DeliveryOwnership.ELSEWHERE, tuple(elsewhere)+ if DeliveryOwnership.LOCAL in answers:+ return DeliveryOwnership.LOCAL, ()+ return DeliveryOwnership.UNDECIDED, ()+def dispatch(self, delivery: WebhookDelivery, *, budget: DeliveryBudget | None = None) -> None:"""Run this delivery's consumers.diff --git a/posthog/ingress/dispatch/forward.py b/posthog/ingress/dispatch/forward.pynew file mode 100644index 000000000000..192cca83c29a--- /dev/null+++ b/posthog/ingress/dispatch/forward.py@@ -0,0 +1,76 @@+"""Replay a verified request to the region that owns the resource it is about.++A third party sends every delivery to the primary region, so a delivery for a resource the other+region holds has to be forwarded there. The forward is the raw signed bytes, unchanged: the other+region verifies the same signature over the same body, which is why no consumer can do this --+by the time a consumer sees a delivery, the body is a parsed mapping.+"""++from urllib.parse import urlparse, urlunparse++from django.http import HttpRequest++import requests+import structlog+from requests import RequestException++from posthog.ingress.observability.metrics import observe_forward+from posthog.regions import SECONDARY_REGION_DOMAIN++logger = structlog.get_logger(__name__)++# The other region reads its own identity off the connection it receives, so a host this region+# put on the request would let it read itself as the primary region and forward the delivery on+# again. X-Forwarded-Proto travels with them because SECURE_PROXY_SSL_HEADER resolves the scheme+# from it. X-Forwarded-For stays: nothing regional reads it, and it holds the third party's address.+HOST_IDENTIFYING_HEADERS = frozenset({"host", "x-forwarded-host", "x-forwarded-port", "x-forwarded-proto", "forwarded"})+++def forward_to_secondary_region(request: HttpRequest, *, provider: str, app: str, timeout: float = 3.0) -> bool:+ """Send this request on to the secondary region once. True only when it answered 2xx.++ Forwarding once per request rather than once per delivery: the unit being replayed is the HTTP+ request, so a batched body that carries several unowned deliveries still crosses once.+ """+ target_url = urlunparse(urlparse(request.build_absolute_uri())._replace(netloc=SECONDARY_REGION_DOMAIN))+ headers = {key: value for key, value in request.headers.items() if key.lower() not in HOST_IDENTIFYING_HEADERS}++ try:+ response = requests.request(+ method=request.method or "POST",+ url=target_url,+ data=request.body,+ headers=headers,+ timeout=timeout,+ )+ except RequestException as error:+ logger.exception(+ "ingress_forward_to_secondary_region_failed",+ provider=provider,+ app=app,+ target_url=target_url,+ error=str(error),+ )+ observe_forward(provider=provider, app=app, outcome="failed")+ return False++ if not response.ok:+ logger.warning(+ "ingress_forward_to_secondary_region_rejected",+ provider=provider,+ app=app,+ target_url=target_url,+ status_code=response.status_code,+ )+ observe_forward(provider=provider, app=app, outcome="rejected")+ return False++ logger.info(+ "ingress_forwarded_to_secondary_region",+ provider=provider,+ app=app,+ target_url=target_url,+ status_code=response.status_code,+ )+ observe_forward(provider=provider, app=app, outcome="forwarded")+ return Truediff --git a/posthog/ingress/github/README.md b/posthog/ingress/github/README.mdindex 4c25c8f484c4..cf306d48688e 100644--- a/posthog/ingress/github/README.md+++ b/posthog/ingress/github/README.md@@ -32,11 +32,13 @@ A consumer registers against an app name, so the two apps share no consumers.The status codes are the defaults: 403 on a bad signature, 500 when unconfigured, 202 on success.The installation lifecycle is a core consumer rather than a product one, because it keeps PostHog's own integration rows in step with GitHub.+The `posthog` app's conversations consumer declares ownership by installation, so a delivery for an installation the other region holds is forwarded there before local dispatch. The consumers in this region still run — see [Regional forwarding](../README.md#regional-forwarding).## Consumers- `posthog/ingress/github/provider.py` registers `installation_lifecycle` and `installation_repositories` on the `posthog` app.+- `products/{tasks,conversations,workflows}/backend/webhook_consumers.py` register the product consumers on the `posthog` app.- `products/stamphog/backend/webhook_consumers.py` registers `stamphog_review` on the `stamphog` app.-The remaining GitHub consumers move to ingress one product at a time.-The [Endpoints table](../README.md#endpoints) lists them.+The [Endpoints table](../README.md#endpoints) lists the consumer names per event type.+PR analytics shared by those consumers live in `posthog/github/`, see its README.diff --git a/posthog/ingress/observability/metrics.py b/posthog/ingress/observability/metrics.pyindex cc3e326cc515..08c4cedcbff5 100644--- a/posthog/ingress/observability/metrics.py+++ b/posthog/ingress/observability/metrics.py@@ -13,12 +13,21 @@ DeliveryOutcome = Literal["not_configured","invalid_signature","invalid_payload",+ "forward_failed",]# budget_exceeded means the delivery ran out of wall clock before this consumer started. It is# not marked in dedup, so the provider's redelivery reaches it.ConsumerOutcome = Literal["succeeded", "failed", "deduped", "budget_exceeded"]+# What a consumer answered when asked which region owns the delivery's resource; `failed` is the+# lookup raising, which counts as undecided.+OwnershipOutcome = Literal["local", "elsewhere", "undecided", "failed"]++# What the owning region answered the replayed request: `rejected` is a non-2xx, `failed` is the+# request never completing.+ForwardOutcome = Literal["forwarded", "rejected", "failed"]+INGRESS_DELIVERIES_TOTAL = Counter("posthog_ingress_deliveries_total","Inbound webhook deliveries, labeled by provider app and what the transport answered",@@ -31,6 +40,18 @@ INGRESS_CONSUMER_RUNS_TOTAL = Counter(labelnames=["provider", "consumer", "outcome"],)+INGRESS_OWNERSHIP_TOTAL = Counter(+ "posthog_ingress_ownership_total",+ "Ownership answers from consumers that declare one, labeled by consumer and answer",+ labelnames=["provider", "consumer", "outcome"],+)++INGRESS_FORWARDS_TOTAL = Counter(+ "posthog_ingress_forwards_total",+ "Requests replayed to the region that owns the delivery, labeled by what that region answered",+ labelnames=["provider", "app", "outcome"],+)+INGRESS_CONSUMER_DURATION_SECONDS = Histogram("posthog_ingress_consumer_duration_seconds","Wall-clock seconds one consumer spent on one inbound webhook delivery",@@ -46,5 +67,13 @@ def observe_consumer_run(*, provider: str, consumer: str, outcome: ConsumerOutcoINGRESS_CONSUMER_RUNS_TOTAL.labels(provider=provider, consumer=consumer, outcome=outcome).inc()+def observe_ownership(*, provider: str, consumer: str, outcome: OwnershipOutcome) -> None:+ INGRESS_OWNERSHIP_TOTAL.labels(provider=provider, consumer=consumer, outcome=outcome).inc()+++def observe_forward(*, provider: str, app: str, outcome: ForwardOutcome) -> None:+ INGRESS_FORWARDS_TOTAL.labels(provider=provider, app=app, outcome=outcome).inc()++def observe_consumer_duration(*, provider: str, consumer: str, seconds: float) -> None:INGRESS_CONSUMER_DURATION_SECONDS.labels(provider=provider, consumer=consumer).observe(seconds)diff --git a/posthog/ingress/providers.py b/posthog/ingress/providers.pyindex 557b253f7bf1..be72e81c62f0 100644--- a/posthog/ingress/providers.py+++ b/posthog/ingress/providers.py@@ -40,6 +40,11 @@ class WebhookProvider(ABC):invalid_signature_status: int = 403unconfigured_status: int = 500success_status: int = 202+ # Answered instead of the receipt when the forward to the owning region fails, so a provider+ # that redelivers on a non-2xx tries again (Slack does, GitHub does not). `None` keeps the+ # receipt. This is the one documented exception to "consumers never decide the response": the+ # decision is the transport's, not a consumer's.+ forward_failure_status: int | None = None# An incarnation that answers 404 to withhold the endpoint's existence sets this False, so the# body does not name the reason the status code was chosen to hide.explains_rejections: bool = True@@ -56,10 +61,12 @@ class WebhookProvider(ABC):return self.scheme().verify(body=request.body, headers=request.headers)def pre_dispatch_response(self, request: HttpRequest, payload: Any) -> HttpResponse | None:- """A response the provider's protocol demands before any consumer runs.+ """A handshake the protocol demands, answered before any consumer runs.- Only handshakes belong here (Slack's `url_verification` challenge), never anything a- consumer's outcome decides.+ Only that: Slack's `url_verification` challenge is the case. Never a side effect, and+ never anything a consumer's outcome decides. Regional forwarding used to live here and+ does not any more -- a consumer declares `ownership` and the view forwards.+ Returning `None` lets dispatch continue."""return Nonediff --git a/posthog/ingress/test/test_dispatcher.py b/posthog/ingress/test/test_dispatcher.pyindex 0ad15a90699f..9cd5c0933844 100644--- a/posthog/ingress/test/test_dispatcher.py+++ b/posthog/ingress/test/test_dispatcher.py@@ -7,7 +7,7 @@ from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized-from posthog.ingress.contracts import ProviderSpec, WebhookConsumer, WebhookDelivery+from posthog.ingress.contracts import DeliveryOwnership, ProviderSpec, WebhookConsumer, WebhookDeliveryfrom posthog.ingress.dispatch.budget import DEFAULT_DELIVERY_BUDGET_SECONDS, DeliveryBudget, delivery_budget_secondsfrom posthog.ingress.dispatch.dedup import DeliveryDedupfrom posthog.ingress.dispatch.dispatcher import WebhookDispatcher@@ -28,7 +28,7 @@ def _delivery(delivery_id: str | None = "delivery-1") -> WebhookDelivery:)-def _consumer(name: str, handler, *, dedup: bool = True) -> WebhookConsumer:+def _consumer(name: str, handler, *, dedup: bool = True, ownership=None) -> WebhookConsumer:return WebhookConsumer(name=name,provider="github",@@ -36,9 +36,19 @@ def _consumer(name: str, handler, *, dedup: bool = True) -> WebhookConsumer:event_types=frozenset({"pull_request"}),handler=handler,dedup=dedup,+ ownership=ownership,)+def _ownership(answer):+ def lookup(delivery: WebhookDelivery) -> DeliveryOwnership:+ if isinstance(answer, Exception):+ raise answer+ return answer++ return lookup++def _dispatcher(consumers: list[WebhookConsumer], *, budget_seconds: float | None = None) -> WebhookDispatcher:return WebhookDispatcher(ConsumerRegistry(providers=[SPEC], consumers=consumers),@@ -160,6 +170,50 @@ class TestWebhookDispatcher(SimpleTestCase):second.assert_not_called()+class TestDeliveryOwnership(SimpleTestCase):+ @parameterized.expand(+ [+ ("nobody_declares_one", [], DeliveryOwnership.UNDECIDED, ()),+ ("every_answer_is_local", [DeliveryOwnership.LOCAL] * 2, DeliveryOwnership.LOCAL, ()),+ (+ "one_elsewhere_decides_the_request",+ [DeliveryOwnership.LOCAL, DeliveryOwnership.ELSEWHERE],+ DeliveryOwnership.ELSEWHERE,+ ("consumer-1",),+ ),+ (+ "a_lookup_that_raises_leaves_the_others_deciding",+ [RuntimeError("lookup failed"), DeliveryOwnership.ELSEWHERE],+ DeliveryOwnership.ELSEWHERE,+ ("consumer-1",),+ ),+ (+ "a_lookup_that_raises_alone_is_undecided",+ [RuntimeError("lookup failed")],+ DeliveryOwnership.UNDECIDED,+ (),+ ),+ ]+ )+ def test_any_consumer_answering_elsewhere_forwards_the_request(+ self, _name: str, answers: list, expected: DeliveryOwnership, expected_names: tuple[str, ...]+ ) -> None:+ consumers = [+ _consumer(f"consumer-{index}", Mock(), ownership=_ownership(answer)) for index, answer in enumerate(answers)+ ]++ with patch("posthog.ingress.dispatch.dispatcher.capture_exception"):+ self.assertEqual(_dispatcher(consumers).ownership_of(_delivery()), (expected, expected_names))++ def test_a_consumer_without_an_ownership_lookup_is_never_asked(self) -> None:+ asked = Mock(return_value=DeliveryOwnership.LOCAL)+ consumers = [_consumer("alpha", Mock()), _consumer("zulu", Mock(), ownership=asked)]++ _dispatcher(consumers).ownership_of(_delivery())++ asked.assert_called_once()++class TestDeliveryBudgetSeconds(SimpleTestCase):@parameterized.expand([diff --git a/posthog/ingress/test/test_views.py b/posthog/ingress/test/test_views.pyindex 5875779de741..077505835381 100644--- a/posthog/ingress/test/test_views.py+++ b/posthog/ingress/test/test_views.py@@ -1,17 +1,26 @@import hmacimport json+from typing import castfrom unittest.mock import Mock, patch+from django.core.cache import cachefrom django.test import RequestFactory, SimpleTestCase, override_settingsimport structlog.testingfrom parameterized import parameterized+from requests import RequestException-from posthog.ingress.github.provider import build_github_provider+from posthog.ingress.contracts import DeliveryOwnership, ProviderSpec, WebhookConsumer, WebhookDelivery+from posthog.ingress.dispatch.dispatcher import WebhookDispatcher+from posthog.ingress.dispatch.forward import HOST_IDENTIFYING_HEADERS, forward_to_secondary_region+from posthog.ingress.dispatch.registry import ConsumerRegistry+from posthog.ingress.github.provider import GitHubProvider, build_github_providerfrom posthog.ingress.pandadoc.provider import build_pandadoc_provider+from posthog.ingress.providers import WebhookProviderfrom posthog.ingress.slack.provider import build_slack_providerfrom posthog.ingress.views import build_webhook_view+from posthog.regions import SECONDARY_REGION_DOMAINSECRET = "s3cret"@@ -24,10 +33,23 @@ def _slack_signature(timestamp: str, body: bytes) -> str:return "v0=" + hmac.digest(SECRET.encode(), b"v0:" + timestamp.encode() + b":" + body, "sha256").hex()+GITHUB_SPEC = ProviderSpec(provider="github", app="posthog", event_types=frozenset({"issues"}))+PANDADOC_SPEC = ProviderSpec(provider="pandadoc", app="default", event_types=frozenset({"document_state_changed"}))++RAISES = object()+++class _RedeliveringGitHubProvider(GitHubProvider):+ # Stands in for a provider that replays a delivery the endpoint did not accept, which GitHub+ # itself does not do.+ forward_failure_status = 502++class TestWebhookView(SimpleTestCase):def setUp(self) -> None:self.factory = RequestFactory()self.dispatcher = Mock()+ self.dispatcher.ownership_of.return_value = (DeliveryOwnership.UNDECIDED, ())patcher = patch("posthog.ingress.views.get_dispatcher", return_value=self.dispatcher)patcher.start()self.addCleanup(patcher.stop)@@ -198,3 +220,204 @@ class TestWebhookView(SimpleTestCase):self.assertEqual(delivery.event_type, "app_mention")self.assertEqual(delivery.delivery_id, "Ev1")self.assertEqual(delivery.context["slack_team_id"], "T1")+++def _consumer(+ spec: ProviderSpec,+ *,+ name: str,+ handler: Mock,+ answer: object = None,+) -> WebhookConsumer:+ def ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ if answer is RAISES:+ raise RuntimeError("ownership lookup failed")+ return cast(DeliveryOwnership, answer)++ return WebhookConsumer(+ name=name,+ provider=spec.provider,+ app=spec.app,+ event_types=spec.event_types,+ handler=handler,+ ownership=None if answer is None else ownership,+ )+++@override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}})+class TestRegionalForwarding(SimpleTestCase):+ def setUp(self) -> None:+ cache.clear()+ self.factory = RequestFactory()+ self.handler = Mock()++ secret = patch("posthog.ingress.github.provider.get_instance_setting", return_value=SECRET)+ secret.start()+ self.addCleanup(secret.stop)++ forward = patch("posthog.ingress.dispatch.forward.requests.request")+ self.requests = forward.start()+ self.requests.return_value = Mock(ok=True, status_code=202)+ self.addCleanup(forward.stop)++ def _view(self, consumers: list[WebhookConsumer], *, provider: WebhookProvider | None = None):+ registry = ConsumerRegistry(providers=[GITHUB_SPEC, PANDADOC_SPEC], consumers=consumers)+ dispatcher = patch("posthog.ingress.views.get_dispatcher", return_value=WebhookDispatcher(registry))+ dispatcher.start()+ self.addCleanup(dispatcher.stop)+ return build_webhook_view(provider if provider is not None else build_github_provider("posthog"))++ def _github_request(self):+ body = json.dumps({"action": "opened", "installation": {"id": 42}}).encode()+ return self.factory.post(+ "/webhooks/github/",+ data=body,+ content_type="application/json",+ headers={+ "X-Hub-Signature-256": _github_signature(body),+ "X-GitHub-Event": "issues",+ "X-GitHub-Delivery": "delivery-1",+ },+ )++ @parameterized.expand(+ [+ ("elsewhere_forwards_once", DeliveryOwnership.ELSEWHERE, 1, 0),+ ("local_forwards_nothing", DeliveryOwnership.LOCAL, 0, 0),+ ("undecided_forwards_nothing", DeliveryOwnership.UNDECIDED, 0, 0),+ ("a_lookup_that_raises_counts_as_undecided", RAISES, 0, 1),+ ]+ )+ def test_the_ownership_answer_decides_the_forward_and_never_the_local_dispatch(+ self, _name: str, answer: object, forwards: int, captures: int+ ) -> None:+ view = self._view([_consumer(GITHUB_SPEC, name="probe", handler=self.handler, answer=answer)])++ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.dispatch.dispatcher.capture_exception") as capture,+ ):+ response = view(self._github_request())++ self.assertEqual(response.status_code, 202)+ self.assertEqual(self.requests.call_count, forwards)+ self.handler.assert_called_once()+ self.assertEqual(capture.call_count, captures)++ @parameterized.expand(+ [+ ("a_provider_that_redelivers_asks_for_one", _RedeliveringGitHubProvider, 502, "forward_failed", 0),+ ("a_provider_that_does_not_keeps_the_receipt", GitHubProvider, 202, "accepted", 1),+ ]+ )+ def test_a_failed_forward_answers_what_the_provider_needs_to_redeliver(+ self, _name: str, provider_class: type[GitHubProvider], status: int, outcome: str, dispatched: int+ ) -> None:+ self.requests.side_effect = RequestException("no route to the other region")+ view = self._view(+ [_consumer(GITHUB_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.ELSEWHERE)],+ provider=provider_class("posthog"),+ )++ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ patch("posthog.ingress.views.observe_delivery") as observe,+ ):+ response = view(self._github_request())++ self.assertEqual(response.status_code, status)+ self.assertEqual([call.kwargs["outcome"] for call in observe.call_args_list], [outcome])+ self.assertEqual(self.handler.call_count, dispatched)++ def test_the_secondary_region_reports_an_unowned_delivery_rather_than_forwarding_it_back(self) -> None:+ view = self._view(+ [_consumer(GITHUB_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.ELSEWHERE)]+ )++ with (+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "eu.posthog.com"),+ patch("posthog.ingress.views.logger") as logger,+ ):+ response = view(self._github_request())++ self.assertEqual(response.status_code, 202)+ self.requests.assert_not_called()+ self.handler.assert_called_once()+ self.assertEqual([call.args[0] for call in logger.warning.call_args_list], ["ingress_delivery_unowned_here"])++ def test_a_batched_body_of_unowned_deliveries_forwards_the_request_once(self) -> None:+ view = self._view(+ [_consumer(PANDADOC_SPEC, name="probe", handler=self.handler, answer=DeliveryOwnership.ELSEWHERE)],+ provider=build_pandadoc_provider(),+ )+ body = json.dumps([{"event": "document_state_changed"}, {"event": "document_state_changed"}]).encode()+ request = self.factory.post(+ "/webhooks/pandadoc/",+ data=body,+ content_type="application/json",+ headers={"X-PandaDoc-Signature": hmac.digest(SECRET.encode(), body, "sha256").hex()},+ )++ with (+ override_settings(PANDADOC_WEBHOOK_SECRET=SECRET),+ patch("posthog.regions.PRIMARY_REGION_DOMAIN", "testserver"),+ ):+ response = view(request)++ self.assertEqual(response.status_code, 202)+ self.assertEqual(self.requests.call_count, 1)+ self.assertEqual(self.handler.call_count, 2)+++class TestForwardToSecondaryRegion(SimpleTestCase):+ def setUp(self) -> None:+ self.body = json.dumps({"action": "opened"}).encode()+ self.request = RequestFactory().post(+ "/webhooks/github/",+ data=self.body,+ content_type="application/json",+ headers={+ "X-Hub-Signature-256": _github_signature(self.body),+ "X-GitHub-Event": "issues",+ "X-Forwarded-Host": "eu.posthog.com",+ "X-Forwarded-Proto": "https",+ "Forwarded": "host=eu.posthog.com;proto=https",+ "X-Forwarded-For": "140.82.115.1",+ },+ )++ @parameterized.expand(+ [+ ("a_2xx_is_a_forward", 202, None, True, "forwarded"),+ ("a_non_2xx_is_a_rejection", 500, None, False, "rejected"),+ ("a_transport_error_is_a_failure", None, RequestException("no route"), False, "failed"),+ ]+ )+ def test_only_a_2xx_from_the_other_region_counts_as_forwarded(+ self, _name: str, status_code: int | None, error: Exception | None, forwarded: bool, outcome: str+ ) -> None:+ response = Mock(ok=status_code is not None and status_code < 300, status_code=status_code)++ with (+ patch("posthog.ingress.dispatch.forward.requests.request", side_effect=error, return_value=response),+ patch("posthog.ingress.dispatch.forward.observe_forward") as observe,+ ):+ result = forward_to_secondary_region(self.request, provider="github", app="posthog")++ self.assertEqual(result, forwarded)+ self.assertEqual(observe.call_args.kwargs["outcome"], outcome)++ def test_the_replay_carries_the_signed_bytes_unchanged(self) -> None:+ with patch("posthog.ingress.dispatch.forward.requests.request") as request:+ request.return_value = Mock(ok=True, status_code=202)+ forward_to_secondary_region(self.request, provider="github", app="posthog")++ kwargs = request.call_args.kwargs+ self.assertEqual(kwargs["data"], self.body)+ self.assertEqual(kwargs["headers"]["X-Hub-Signature-256"], _github_signature(self.body))+ sent = {key.lower() for key in kwargs["headers"]}+ # The other region routes on the host it sees, so any host this region sends would send the+ # request straight back here and both regions would forward it in a loop.+ self.assertEqual(sent & HOST_IDENTIFYING_HEADERS, set())+ self.assertIn("x-forwarded-for", sent)+ self.assertIn(SECONDARY_REGION_DOMAIN, kwargs["url"])diff --git a/posthog/ingress/views.py b/posthog/ingress/views.pyindex 586f9611354c..5757c77dc8c7 100644--- a/posthog/ingress/views.py+++ b/posthog/ingress/views.py@@ -8,11 +8,14 @@ from django.views.decorators.csrf import csrf_exemptimport structlog+from posthog.ingress.contracts import DeliveryOwnershipfrom posthog.ingress.dispatch.budget import DeliveryBudget, delivery_budget_seconds+from posthog.ingress.dispatch.forward import forward_to_secondary_regionfrom posthog.ingress.dispatch.loading import get_dispatcherfrom posthog.ingress.observability.metrics import observe_deliveryfrom posthog.ingress.providers import WebhookProviderfrom posthog.ingress.verify.schemes import VerificationOutcome+from posthog.regions import is_primary_regionlogger = structlog.get_logger(__name__)@@ -57,10 +60,36 @@ def build_webhook_view(provider: WebhookProvider) -> Callable[[HttpRequest], Httreturn handshakedispatcher = get_dispatcher()+ deliveries = provider.deliveries(request, payload)# One budget for the whole request, not one per delivery: PandaDoc turns a batched body- # into many deliveries, and a budget each would hold the request open for the sum.+ # into many deliveries, and a budget each would hold the request open for the sum. It+ # starts before the ownership lookups, which read the database and forward on the same+ # request path.budget = DeliveryBudget(delivery_budget_seconds())- for delivery in provider.deliveries(request, payload):++ elsewhere: dict[str, None] = {}+ for delivery in deliveries:+ ownership, consumers = dispatcher.ownership_of(delivery)+ if ownership is DeliveryOwnership.ELSEWHERE:+ elsewhere.update(dict.fromkeys(consumers))+ if elsewhere:+ if is_primary_region(request):+ # Once for the request, not once per delivery: what is replayed is the signed body.+ forwarded = forward_to_secondary_region(request, provider=provider.provider, app=provider.app)+ if not forwarded and provider.forward_failure_status is not None:+ observe_delivery(provider=provider.provider, app=provider.app, outcome="forward_failed")+ return HttpResponse(status=provider.forward_failure_status)+ else:+ # A local miss on the secondary region is that consumer's unresolved routing, not+ # proof that no region owns the delivery.+ logger.warning(+ "ingress_delivery_unowned_here",+ provider=provider.provider,+ app=provider.app,+ consumers=list(elsewhere),+ )++ for delivery in deliveries:dispatcher.dispatch(delivery, budget=budget)observe_delivery(provider=provider.provider, app=provider.app, outcome="accepted")diff --git a/posthog/regions.py b/posthog/regions.pynew file mode 100644index 000000000000..f4e30a78a460--- /dev/null+++ b/posthog/regions.py@@ -0,0 +1,24 @@+"""Which of PostHog's two Cloud regions a request reached.++EU is the primary region: the callback and webhook URLs third parties hold point there, so a+request for a resource the US region owns arrives here first and has to be forwarded on.++This sits outside `posthog/ingress/` on purpose. Endpoints that are not inbound webhooks ask the+same question, and they must not take a dependency on the webhook machinery to answer it.+"""++from urllib.parse import urlparse++from django.conf import settings+from django.http import HttpRequest++PRIMARY_REGION_DOMAIN = "eu.posthog.com"+SECONDARY_REGION_DOMAIN = "us.posthog.com"++if settings.DEBUG:+ PRIMARY_REGION_DOMAIN = urlparse(settings.SITE_URL).netloc+ SECONDARY_REGION_DOMAIN = "localhost:8000"+++def is_primary_region(request: HttpRequest) -> bool:+ return request.get_host() == PRIMARY_REGION_DOMAINdiff --git a/posthog/urls.py b/posthog/urls.pyindex 1aa7f392b765..37d0e4594681 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -23,7 +23,6 @@ from posthog.api import (user,)from posthog.api.github_callback.views import github_oauth_callback, github_setup_callback-from posthog.api.github_webhooks.views import github_webhookfrom posthog.api.integration_connect import integration_connect_redirectfrom posthog.api.oauth.connected_apps import ConnectedAppsViewSetfrom posthog.api.oauth.hogli_metadata import HOGLI_METADATA_PATH, HogliClientMetadataView@@ -35,6 +34,8 @@ from posthog.api.two_factor_qrcode import CacheAwareQRGeneratorViewfrom posthog.api.web_experiment import web_experimentsfrom posthog.ee_urls import ee_urlpatternsfrom posthog.frontend_views import home, home_with_region_redirect+from posthog.ingress.github.provider import build_github_provider+from posthog.ingress.views import build_webhook_viewfrom posthog.oauth2_urls import urlpatterns as oauth2_urlsfrom posthog.temporal.codec_server import decode_payloadsfrom posthog.web_bot_auth import http_message_signatures_directory@@ -70,7 +71,6 @@ from products.slack_app.backend.views import (slack_user_link_authorize,slack_user_link_callback,)-from products.stamphog.backend.facade.webhooks import stamphog_github_webhookfrom products.streamlit_apps.backend.presentation.bridge_views import StreamlitBridgeViewfrom products.surveys.backend.api.survey import public_survey_pagefrom products.tasks.backend.facade.agent_proxy import agent_proxy_callback@@ -98,6 +98,13 @@ from .views import (update_preferences,)+# One view for both paths, so the provider is built once per process rather than once per route.+github_app_webhook = build_webhook_view(build_github_provider("posthog"))++# Stamphog runs on its own GitHub App, with its own signing secret and its own consumers, so it+# gets its own view rather than sharing the customer-facing App's endpoint.+stamphog_github_webhook = build_webhook_view(build_github_provider("stamphog"))+urlpatterns = [# EU spend must precede both the API router and the API fallback.*(@@ -358,9 +365,9 @@ urlpatterns = [opt_slash_path("slack/event-callback", posthog_code_event_handler),opt_slash_path("slack/command-callback", slack_app_command_handler),opt_slash_path("slack/workspace/claims", slack_workspace_claims_view),- # GitHub App webhook — fans out to tasks (PRs) and conversations (issues)- opt_slash_path("webhooks/github/pr", github_webhook),- opt_slash_path("webhooks/github", github_webhook),+ # GitHub App webhook — ingress fans it out to the tasks, conversations and workflows consumers+ opt_slash_path("webhooks/github/pr", github_app_webhook),+ opt_slash_path("webhooks/github", github_app_webhook),# Stamphog runs as its own GitHub App with a dedicated inbound endpoint (not the fan-out above)opt_slash_path("webhooks/stamphog/github", stamphog_github_webhook),# AWS SES tenant reputation events (EventBridge -> SNS HTTPS subscription)diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.pyindex 592edabbb7f3..c571829fc687 100644--- a/products/conversations/backend/api/email_events.py+++ b/products/conversations/backend/api/email_events.py@@ -20,6 +20,7 @@ from posthog.models.comment import Commentfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import User+from posthog.regions import is_primary_regionfrom products.conversations.backend.mailgun import validate_webhook_signaturefrom products.conversations.backend.models import (@@ -50,7 +51,6 @@ from products.conversations.backend.services.email_thread_ingestion import (ingest_customer_email,)from products.conversations.backend.services.region_routing import (- is_primary_region,proxy_to_secondary_region,request_secondary_region_status,)diff --git a/products/conversations/backend/api/github_events.py b/products/conversations/backend/api/github_events.pydeleted file mode 100644index 655486a914d4..000000000000--- a/products/conversations/backend/api/github_events.py+++ /dev/null@@ -1,87 +0,0 @@-"""GitHub event dispatch for Conversations GitHub Issues channel.--The entry point is ``dispatch_github_event``, called from the GitHub App-webhook fan-out in ``posthog.urls.github_webhook`` after signature verification-and JSON parsing.-"""--import hashlib-from typing import Any, cast--from django.http import HttpRequest, HttpResponse--import structlog--from posthog.models.integration import Integration--from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region-from products.conversations.backend.tasks.github import process_github_event--logger = structlog.get_logger(__name__)---def _team_for_github_installation(installation_id: str) -> tuple[int | None, bool]:- """Resolve team ID from a GitHub App installation ID.-- Returns (team_id, github_enabled). team_id is None if no team has this- installation connected for conversations.-- Multiple teams can share the same GitHub App installation ID (the unique- constraint is per-team). We iterate all matches and only accept the one- whose conversations_settings.github_integration_id explicitly points back- to the Integration row, ensuring deterministic routing.- """- integrations = (- Integration.objects.filter(kind="github", integration_id=installation_id).select_related("team").order_by("id")- )-- for integration in integrations:- settings_dict = integration.team.conversations_settings or {}- if not settings_dict.get("github_enabled", False):- continue- expected_integration_id = settings_dict.get("github_integration_id")- if expected_integration_id is not None and expected_integration_id != integration.id:- continue- if expected_integration_id is None:- continue- return integration.team_id, True-- return None, False---def dispatch_github_event(request: HttpRequest, event_type: str, data: dict[str, Any]) -> HttpResponse:- """Route a pre-verified GitHub event to the conversations Celery pipeline.-- Called from ``posthog.urls.github_webhook`` after signature verification- and JSON parsing are already done.- """- installation_id = str(data.get("installation", {}).get("id", ""))- if not installation_id:- logger.warning("github_issues_webhook_no_installation")- return HttpResponse(status=200)-- team_id, github_enabled = _team_for_github_installation(installation_id)-- if team_id and github_enabled:- repo_full_name = data.get("repository", {}).get("full_name", "")- action = data.get("action", "")- delivery_id = request.headers.get("X-GitHub-Delivery") or hashlib.sha256(request.body).hexdigest()[:32]-- cast(Any, process_github_event).delay(- event_type=event_type,- action=action,- payload=data,- delivery_id=delivery_id,- team_id=team_id,- repo=repo_full_name,- )- return HttpResponse(status=202)- elif is_primary_region(request):- proxy_to_secondary_region(request, log_prefix="github_issues")- return HttpResponse(status=200)- else:- logger.warning(- "github_issues_webhook_no_team",- installation_id=installation_id,- )- return HttpResponse(status=200)diff --git a/products/conversations/backend/api/slack_events.py b/products/conversations/backend/api/slack_events.pyindex 2553aa011ccf..10b73e577e8b 100644--- a/products/conversations/backend/api/slack_events.py+++ b/products/conversations/backend/api/slack_events.py@@ -10,6 +10,7 @@ from django.views.decorators.csrf import csrf_exemptimport structlogfrom posthog.models.integration import SlackIntegrationError+from posthog.regions import is_primary_regionfrom products.conversations.backend.models import ConversationInboundEventSourcefrom products.conversations.backend.services.inbound_events import (@@ -17,7 +18,7 @@ from products.conversations.backend.services.inbound_events import (slack_events_source_id,slack_retry_metadata,)-from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region+from products.conversations.backend.services.region_routing import proxy_to_secondary_regionfrom products.conversations.backend.support_slack import team_for_slack_workspace, validate_support_requestfrom products.conversations.backend.tasks.slack import wake_inbound_eventdiff --git a/products/conversations/backend/api/slack_interactivity.py b/products/conversations/backend/api/slack_interactivity.pyindex bf53606eb2ba..caefc3095b05 100644--- a/products/conversations/backend/api/slack_interactivity.py+++ b/products/conversations/backend/api/slack_interactivity.py@@ -15,6 +15,7 @@ from django.views.decorators.csrf import csrf_exemptimport structlogfrom posthog.models.integration import SlackIntegrationError+from posthog.regions import is_primary_regionfrom products.conversations.backend.models import ConversationInboundEventSourcefrom products.conversations.backend.services.inbound_events import (@@ -22,7 +23,7 @@ from products.conversations.backend.services.inbound_events import (slack_interactivity_source_id,slack_retry_metadata,)-from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region+from products.conversations.backend.services.region_routing import proxy_to_secondary_regionfrom products.conversations.backend.support_slack import team_for_slack_workspace, validate_support_requestfrom products.conversations.backend.tasks.slack import wake_inbound_eventdiff --git a/products/conversations/backend/api/teams_events.py b/products/conversations/backend/api/teams_events.pyindex b3c21b172982..6a03353260ff 100644--- a/products/conversations/backend/api/teams_events.py+++ b/products/conversations/backend/api/teams_events.py@@ -12,9 +12,10 @@ from rest_framework.request import Request as DRFRequestfrom posthog.models.team import Teamfrom posthog.rate_limit import TeamsEventWebhookThrottle+from posthog.regions import is_primary_regionfrom products.conversations.backend.models import TeamConversationsTeamsConfig-from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region+from products.conversations.backend.services.region_routing import proxy_to_secondary_regionfrom products.conversations.backend.support_teams import (get_bot_from_id,is_trusted_teams_service_url,diff --git a/products/conversations/backend/api/tests/test_github_webhook.py b/products/conversations/backend/api/tests/test_github_webhook.pydeleted file mode 100644index 991c533be95c..000000000000--- a/products/conversations/backend/api/tests/test_github_webhook.py+++ /dev/null@@ -1,137 +0,0 @@-import hmac-import json-import hashlib-from typing import Any--from posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch--from django.test import RequestFactory--from parameterized import parameterized--from posthog.models.integration import Integration--from products.conversations.backend.api.github_events import dispatch_github_event---def _sign(payload: bytes, secret: str) -> str:- sig = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()- return f"sha256={sig}"---def _issue_event(- *,- action: str = "opened",- installation_id: int = 12345,- repo: str = "org/repo",- issue_number: int = 1,- title: str = "Bug report",- body: str = "",- sender_login: str = "octocat",-) -> dict[str, Any]:- return {- "action": action,- "installation": {"id": installation_id},- "repository": {"full_name": repo},- "issue": {- "number": issue_number,- "title": title,- "body": body,- "user": {"login": sender_login},- },- "sender": {"login": sender_login},- }---WEBHOOK_SECRET = "test-webhook-secret"---class TestDispatchGithubEvent(BaseTest):- """Tests for dispatch_github_event called directly (as github_webhook does)."""-- def setUp(self):- super().setUp()- self.factory = RequestFactory()-- self.integration = Integration.objects.create(- team=self.team,- kind="github",- integration_id="12345",- config={"account": {"name": "org"}},- )- self.team.conversations_enabled = True- self.team.conversations_settings = {- "github_enabled": True,- "github_integration_id": self.integration.id,- "github_repos": ["org/repo"],- }- self.team.save()-- def _dispatch(self, payload: dict, event_type: str = "issues", delivery_id: str = "delivery-abc"):- body = json.dumps(payload).encode()- request = self.factory.post(- "/webhooks/github/pr/",- data=body,- content_type="application/json",- HTTP_X_GITHUB_DELIVERY=delivery_id,- )- return dispatch_github_event(request, event_type, payload)-- @patch("products.conversations.backend.api.github_events.process_github_event")- def test_dispatches_issue_event_to_celery(self, mock_task):- mock_task.delay = MagicMock()- payload = _issue_event()- resp = self._dispatch(payload)-- assert resp.status_code == 202- mock_task.delay.assert_called_once()- call_kwargs = mock_task.delay.call_args[1]- assert call_kwargs["event_type"] == "issues"- assert call_kwargs["team_id"] == self.team.id- assert call_kwargs["repo"] == "org/repo"-- @patch("products.conversations.backend.api.github_events.process_github_event")- def test_falls_back_to_sha256_when_delivery_header_missing(self, mock_task):- mock_task.delay = MagicMock()- payload = _issue_event()- body = json.dumps(payload).encode()- expected_hash = hashlib.sha256(body).hexdigest()[:32]-- request = self.factory.post(- "/webhooks/github/pr/",- data=body,- content_type="application/json",- )- dispatch_github_event(request, "issues", payload)-- call_kwargs = mock_task.delay.call_args[1]- assert call_kwargs["delivery_id"] == expected_hash-- def test_no_installation_returns_200(self):- payload = _issue_event()- del payload["installation"]- resp = self._dispatch(payload)- assert resp.status_code == 200-- @parameterized.expand(- [- ("unknown_installation", 99999, {}, "no matching Integration row"),- ("github_disabled", 12345, {"github_enabled": False}, "feature disabled"),- ("no_integration_binding", 12345, {"github_integration_id": None}, "no explicit binding"),- ]- )- @patch("products.conversations.backend.api.github_events.process_github_event")- def test_no_dispatch(self, _name, installation_id, settings_override, _reason, mock_task):- mock_task.delay = MagicMock()- if settings_override:- for key, val in settings_override.items():- if val is None:- self.team.conversations_settings.pop(key, None)- else:- self.team.conversations_settings[key] = val- self.team.save()-- resp = self._dispatch(_issue_event(installation_id=installation_id))- assert resp.status_code == 200- mock_task.delay.assert_not_called()diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex e70f24b10773..45b3bce833fd 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -23,6 +23,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedErrorfrom temporalio.service import RPCErrorfrom posthog.dataclasses import frozen+from posthog.ingress.contracts import DeliveryOwnership, WebhookDeliveryfrom posthog.models.comment import Commentfrom posthog.models.integration import Integrationfrom posthog.models.team import Team@@ -105,6 +106,26 @@ class SupportMessageSendError(Exception):self.retry_after = retry_after+def accept_github_event(delivery: WebhookDelivery) -> None:+ """The inbound GitHub App webhook enters conversations here, so its consumer needs no internal import."""+ # Deferred to keep the Celery task module off the facade import path.+ from products.conversations.backend.services import github_events # noqa: PLC0415++ github_events.accept_github_event(delivery)+++def github_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Whether this region holds the team the delivery's GitHub installation is connected to.++ Ingress asks before it dispatches, and forwards the signed request to the other region when+ the answer is elsewhere.+ """+ # Deferred to keep the Celery task module off the facade import path.+ from products.conversations.backend.services import github_events # noqa: PLC0415++ return github_events.github_delivery_ownership(delivery)++def sync_google_account_email(integration_id: int, team_id: int) -> None:from products.conversations.backend.services.gmail_sync import ( # noqa: PLC0415 -- avoids the Conversations and Customer Analytics facade cycleGmailSyncError,diff --git a/products/conversations/backend/services/github_events.py b/products/conversations/backend/services/github_events.pynew file mode 100644index 000000000000..b87bb06c988f--- /dev/null+++ b/products/conversations/backend/services/github_events.py@@ -0,0 +1,126 @@+"""GitHub App deliveries for the Conversations GitHub Issues channel.++Two entry points, both reached from the facade after ingress verified the signature and parsed+the body: ``github_delivery_ownership`` answers which region holds the delivery's installation,+and ``accept_github_event`` hands the delivery to the Celery pipeline. No HTTP in here — ingress+owns the request, the receipt, and the forward to the region that owns the installation.+"""++import json+import hashlib+from typing import Any, cast++from django.db import OperationalError++import structlog++from posthog.github.installations import installation_id+from posthog.ingress.contracts import DeliveryOwnership, WebhookDelivery+from posthog.ingress.dispatch.database import bounded_statement_timeout, is_statement_timeout+from posthog.models.integration import Integration++from products.conversations.backend.tasks.github import process_github_event++logger = structlog.get_logger(__name__)++# The event types this product consumes, and so the only ones it can answer ownership for.+_CONSUMED_EVENT_TYPES = frozenset({"issues", "issue_comment"})++# The lookup runs inside the request, before dispatch, so it draws on the delivery's wall clock.+_INSTALLATION_LOOKUP_TIMEOUT_MS = 800+++def _payload_delivery_id(data: dict[str, Any]) -> str:+ """A stable id for a delivery GitHub sent no `X-GitHub-Delivery` for.++ The Celery task keys its own idempotency on this, so an empty string would collapse every+ header-less delivery onto one key. GitHub always sends the header in practice.+ """+ return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()[:32]+++def _team_for_github_installation(external_id: str) -> tuple[int | None, bool]:+ """Resolve team ID from a GitHub App installation ID.++ Returns (team_id, github_enabled). team_id is None if no team has this+ installation connected for conversations.++ Multiple teams can share the same GitHub App installation ID (the unique+ constraint is per-team). We iterate all matches and only accept the one+ whose conversations_settings.github_integration_id explicitly points back+ to the Integration row, ensuring deterministic routing.++ A cancelled statement raises, because a lookup that never finished is not an answer. Each+ caller decides what to do with it.+ """+ with bounded_statement_timeout(_INSTALLATION_LOOKUP_TIMEOUT_MS, models=[Integration]):+ integrations = list(+ Integration.objects.filter(kind="github", integration_id=external_id).select_related("team").order_by("id")+ )++ for integration in integrations:+ settings_dict = integration.team.conversations_settings or {}+ if not settings_dict.get("github_enabled", False):+ continue+ expected_integration_id = settings_dict.get("github_integration_id")+ if expected_integration_id is not None and expected_integration_id != integration.id:+ continue+ if expected_integration_id is None:+ continue+ return integration.team_id, True++ return None, False+++def github_delivery_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ """Which region holds the team this delivery's installation is connected to.++ An installation this region does not own is `ELSEWHERE` rather than undecided, so the+ delivery reaches the other region: it is the only one that can tell an installation it holds+ from one nobody holds, and GitHub never redelivers an event it got a receipt for.+ """+ if delivery.event_type not in _CONSUMED_EVENT_TYPES:+ return DeliveryOwnership.UNDECIDED+ external_id = installation_id(dict(delivery.payload))+ if external_id is None:+ return DeliveryOwnership.UNDECIDED++ try:+ team_id, github_enabled = _team_for_github_installation(external_id)+ except OperationalError as error:+ if not is_statement_timeout(error):+ raise+ # Elsewhere rather than an error: the two answers here are "this region owns it" and+ # "somebody else does", and a lookup that never finished has not shown ownership here.+ logger.warning("github_issues_webhook_installation_lookup_timed_out", installation_id=external_id)+ return DeliveryOwnership.ELSEWHERE++ if team_id and github_enabled:+ return DeliveryOwnership.LOCAL+ return DeliveryOwnership.ELSEWHERE+++def accept_github_event(delivery: WebhookDelivery) -> None:+ """Route a verified GitHub delivery to the conversations Celery pipeline."""+ payload = dict(delivery.payload)+ external_id = installation_id(payload)+ if external_id is None:+ logger.warning("github_issues_webhook_no_installation")+ return++ # Unguarded on purpose: a timed-out lookup fails the delivery, so the dispatcher releases the+ # dedup mark and a redelivery reaches this consumer instead of the event being lost.+ team_id, github_enabled = _team_for_github_installation(external_id)+ if not (team_id and github_enabled):+ # Quiet on purpose: ingress reports a delivery no region here owns, off the ownership+ # answer this module gave it before dispatch.+ return++ cast(Any, process_github_event).delay(+ event_type=delivery.event_type,+ action=payload.get("action", ""),+ payload=payload,+ delivery_id=delivery.delivery_id or _payload_delivery_id(payload),+ team_id=team_id,+ repo=payload.get("repository", {}).get("full_name", ""),+ )diff --git a/products/conversations/backend/services/region_routing.py b/products/conversations/backend/services/region_routing.pyindex 9765ba7e4be0..b1d7c93f59f1 100644--- a/products/conversations/backend/services/region_routing.py+++ b/products/conversations/backend/services/region_routing.py@@ -1,13 +1,15 @@-"""Regional routing helpers for conversations webhooks.+"""Regional proxy for the conversations webhooks that still own their own endpoint.-EU is the primary region (external callback URLs point here).If the primary region doesn't own the resource, it proxies therequest to the secondary region (US).++The endpoints on `posthog/ingress/` forward through that package instead. This proxy stays for+the ones that have not moved: they take multipart bodies, which the raw-bytes replay there+cannot reconstruct."""from urllib.parse import urlparse, urlunparse-from django.conf import settingsfrom django.http import HttpRequestfrom django.http.request import RawPostDataException@@ -15,18 +17,9 @@ import requestsimport structlogfrom requests import RequestException-logger = structlog.get_logger(__name__)--PRIMARY_REGION_DOMAIN = "eu.posthog.com"-SECONDARY_REGION_DOMAIN = "us.posthog.com"+from posthog.regions import SECONDARY_REGION_DOMAIN-if settings.DEBUG:- PRIMARY_REGION_DOMAIN = urlparse(settings.SITE_URL).netloc- SECONDARY_REGION_DOMAIN = "localhost:8000"---def is_primary_region(request: HttpRequest) -> bool:- return request.get_host() == PRIMARY_REGION_DOMAIN+logger = structlog.get_logger(__name__)def _build_proxy_kwargs(request: HttpRequest, headers: dict[str, str]) -> dict:diff --git a/products/conversations/backend/tests/test_github_events.py b/products/conversations/backend/tests/test_github_events.pynew file mode 100644index 000000000000..14d7dc1308f9--- /dev/null+++ b/products/conversations/backend/tests/test_github_events.py@@ -0,0 +1,178 @@+import json+import hashlib+from datetime import UTC, datetime+from typing import Any++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.db import OperationalError++from parameterized import parameterized++from posthog.ingress.contracts import DeliveryOwnership, WebhookDelivery+from posthog.models.integration import Integration++from products.conversations.backend.facade import api as conversations_facade++GITHUB_EVENTS_MODULE = "products.conversations.backend.services.github_events"+++def _issue_event(+ *,+ action: str = "opened",+ installation_id: int | None = 12345,+ repo: str = "org/repo",+ issue_number: int = 1,+ title: str = "Bug report",+ body: str = "",+ sender_login: str = "octocat",+) -> dict[str, Any]:+ return {+ "action": action,+ # GitHub sends `"installation": null` for a delivery outside an App installation.+ "installation": {"id": installation_id} if installation_id is not None else None,+ "repository": {"full_name": repo},+ "issue": {+ "number": issue_number,+ "title": title,+ "body": body,+ "user": {"login": sender_login},+ },+ "sender": {"login": sender_login},+ }+++def _delivery(+ payload: dict[str, Any],+ *,+ event_type: str = "issues",+ delivery_id: str | None = "delivery-abc",+) -> WebhookDelivery:+ return WebhookDelivery(+ provider="github",+ app="posthog",+ delivery_id=delivery_id,+ event_type=event_type,+ payload=payload,+ received_at=datetime(2026, 9, 15, tzinfo=UTC),+ context={},+ )+++class TestConversationsGitHubDeliveries(BaseTest):+ def setUp(self):+ super().setUp()++ self.integration = Integration.objects.create(+ team=self.team,+ kind="github",+ integration_id="12345",+ config={"account": {"name": "org"}},+ )+ self.team.conversations_enabled = True+ self.team.conversations_settings = {+ "github_enabled": True,+ "github_integration_id": self.integration.id,+ "github_repos": ["org/repo"],+ }+ self.team.save()++ def _disable(self, settings_override: dict[str, Any]) -> None:+ for key, value in settings_override.items():+ if value is None:+ self.team.conversations_settings.pop(key, None)+ else:+ self.team.conversations_settings[key] = value+ self.team.save()++ @parameterized.expand(+ [+ ("an_installation_connected_here", "issues", 12345, {}, DeliveryOwnership.LOCAL),+ ("an_installation_no_team_here_has", "issues", 99999, {}, DeliveryOwnership.ELSEWHERE),+ ("github_turned_off_for_the_team", "issues", 12345, {"github_enabled": False}, DeliveryOwnership.ELSEWHERE),+ (+ "no_explicit_integration_binding",+ "issues",+ 12345,+ {"github_integration_id": None},+ DeliveryOwnership.ELSEWHERE,+ ),+ ("an_event_type_this_product_ignores", "pull_request", 99999, {}, DeliveryOwnership.UNDECIDED),+ ("a_delivery_outside_an_installation", "issues", None, {}, DeliveryOwnership.UNDECIDED),+ ]+ )+ def test_ownership_answers_where_the_installations_team_lives(+ self,+ _name: str,+ event_type: str,+ installation_id: int | None,+ settings_override: dict[str, Any],+ expected: DeliveryOwnership,+ ):+ self._disable(settings_override)+ delivery = _delivery(_issue_event(installation_id=installation_id), event_type=event_type)++ assert conversations_facade.github_delivery_ownership(delivery) == expected++ @patch(f"{GITHUB_EVENTS_MODULE}.Integration.objects.filter")+ def test_a_lookup_that_hits_its_timeout_forwards_rather_than_claiming_the_delivery(self, mock_filter):+ # Forwarding is the recoverable answer: the other region repeats the lookup and no-ops if+ # it does not own the installation, while claiming it here would drop the delivery.+ mock_filter.side_effect = OperationalError("canceling statement due to statement timeout")++ answer = conversations_facade.github_delivery_ownership(_delivery(_issue_event()))++ assert answer == DeliveryOwnership.ELSEWHERE++ @patch(f"{GITHUB_EVENTS_MODULE}.process_github_event")+ @patch(f"{GITHUB_EVENTS_MODULE}.Integration.objects.filter")+ def test_a_lookup_that_hits_its_timeout_fails_the_dispatch_rather_than_receipting_it(self, mock_filter, mock_task):+ # Swallowing it would return quietly, the dispatcher would mark the delivery done for 24+ # hours, and GitHub does not redeliver a receipted event, so the issue event is lost here.+ mock_task.delay = MagicMock()+ mock_filter.side_effect = OperationalError("canceling statement due to statement timeout")++ with self.assertRaises(OperationalError):+ conversations_facade.accept_github_event(_delivery(_issue_event()))++ mock_task.delay.assert_not_called()++ @patch(f"{GITHUB_EVENTS_MODULE}.process_github_event")+ def test_accepting_a_delivery_enqueues_it_for_the_owning_team(self, mock_task):+ mock_task.delay = MagicMock()++ conversations_facade.accept_github_event(_delivery(_issue_event()))++ call_kwargs = mock_task.delay.call_args[1]+ assert call_kwargs["event_type"] == "issues"+ assert call_kwargs["team_id"] == self.team.id+ assert call_kwargs["repo"] == "org/repo"+ assert call_kwargs["delivery_id"] == "delivery-abc"++ @patch(f"{GITHUB_EVENTS_MODULE}.process_github_event")+ def test_falls_back_to_sha256_when_delivery_header_missing(self, mock_task):+ mock_task.delay = MagicMock()+ payload = _issue_event()+ expected_hash = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:32]++ conversations_facade.accept_github_event(_delivery(payload, delivery_id=None))++ assert mock_task.delay.call_args[1]["delivery_id"] == expected_hash++ @parameterized.expand(+ [+ ("github_turned_off_for_the_team", 12345, {"github_enabled": False}),+ ("a_delivery_outside_an_installation", None, {}),+ ]+ )+ @patch(f"{GITHUB_EVENTS_MODULE}.process_github_event")+ def test_a_delivery_this_region_does_not_own_enqueues_nothing(+ self, _name: str, installation_id: int | None, settings_override: dict[str, Any], mock_task+ ):+ mock_task.delay = MagicMock()+ self._disable(settings_override)++ conversations_facade.accept_github_event(_delivery(_issue_event(installation_id=installation_id)))++ mock_task.delay.assert_not_called()diff --git a/products/conversations/backend/webhook_consumers.py b/products/conversations/backend/webhook_consumers.pynew file mode 100644index 000000000000..dce28653c2c3--- /dev/null+++ b/products/conversations/backend/webhook_consumers.py@@ -0,0 +1,31 @@+"""Conversations' consumer on the customer-facing GitHub App endpoint.++The registry imports this module on the first delivery, so it stays cheap: both callables defer+their own product import.+"""++from posthog.ingress.contracts import DeliveryOwnership, WebhookConsumer, WebhookDelivery+++def _run_conversations(delivery: WebhookDelivery) -> None:+ from products.conversations.backend.facade.api import accept_github_event # noqa: PLC0415++ accept_github_event(delivery)+++def _github_ownership(delivery: WebhookDelivery) -> DeliveryOwnership:+ from products.conversations.backend.facade.api import github_delivery_ownership # noqa: PLC0415++ return github_delivery_ownership(delivery)+++WEBHOOK_CONSUMERS = (+ WebhookConsumer(+ name="conversations",+ provider="github",+ app="posthog",+ event_types=frozenset({"issues", "issue_comment"}),+ handler=_run_conversations,+ ownership=_github_ownership,+ ),+)diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 38dcd0bf0657..0d3e1c0aa9fd 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -194,8 +194,6 @@ django.HttpRequest products.notebooks.backend.facade.sql_v2.notebook_sql_v2_datadjango.HttpRequest products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane_status facade-accepts(request) 1django.HttpResponse products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane facade-returns 1django.HttpResponse products.notebooks.backend.facade.sql_v2.notebook_sql_v2_data_plane_status facade-returns 1-django.HttpResponse products.tasks.backend.facade.webhooks.handle_pull_request_event facade-returns 1-django.HttpResponse products.tasks.backend.facade.webhooks.handle_pull_request_review_event facade-returns 1django.HttpResponseBase products.exports.backend.facade.api.get_export_asset_content_response facade-returns 1django.JsonResponse products.notebooks.backend.facade.sql_v2.notebook_sql_v2_callback facade-returns 1django.JsonResponse products.tasks.backend.facade.agent_proxy.agent_proxy_callback facade-returns 1diff --git a/products/signals/backend/facade/github.py b/products/signals/backend/facade/github.pyindex 284e2c273631..2a72bd6aa828 100644--- a/products/signals/backend/facade/github.py+++ b/products/signals/backend/facade/github.py@@ -2,7 +2,7 @@import structlog-from posthog.api.github_webhooks.integrations import _installation_team_ids+from posthog.github.installations import installation_team_idsfrom products.signals.backend.report_assignments import update_assignments_for_pull_requestfrom products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users@@ -17,7 +17,7 @@ def resolve_github_login_distinct_id(login: str, team_id: int) -> str | None:def update_pull_request_assignments(payload: dict, pr_state: str | None) -> None:repository = (payload.get("repository") or {}).get("full_name")- team_ids = _installation_team_ids(payload)+ team_ids = installation_team_ids(payload)if pr_state is None or not repository or not team_ids:returnpull_request = payload.get("pull_request") or {}diff --git a/products/stamphog/backend/facade/webhooks.py b/products/stamphog/backend/facade/webhooks.pydeleted file mode 100644index 625e7eced811..000000000000--- a/products/stamphog/backend/facade/webhooks.py+++ /dev/null@@ -1,9 +0,0 @@-"""Facade re-export for the dedicated Stamphog GitHub App webhook view.--Core routes a standalone URL at this view; it stays out of the unified-``posthog.urls.github_webhook`` fan-out because Stamphog is its own GitHub App.-"""--from products.stamphog.backend.presentation.webhooks import stamphog_github_webhook--__all__ = ["stamphog_github_webhook"]diff --git a/products/stamphog/backend/presentation/webhooks.py b/products/stamphog/backend/presentation/webhooks.pydeleted file mode 100644index 2c3969e50918..000000000000--- a/products/stamphog/backend/presentation/webhooks.py+++ /dev/null@@ -1,13 +0,0 @@-"""The inbound webhook view for the dedicated Stamphog GitHub App.--This is a standalone endpoint for Stamphog's own GitHub App. It does not share the-customer-facing App's endpoint. The integration layer wires the URL at this name.-"""--from posthog.ingress.github.provider import build_github_provider-from posthog.ingress.views import build_webhook_view--# Built once per process: the provider only stores the secret getter, it never reads the secret here.-stamphog_github_webhook = build_webhook_view(build_github_provider("stamphog"))--__all__ = ["stamphog_github_webhook"]diff --git a/products/stamphog/backend/tests/test_webhook_consumers.py b/products/stamphog/backend/tests/test_webhook_consumers.pyindex 1eae537c00e2..f394ddd8ad96 100644--- a/products/stamphog/backend/tests/test_webhook_consumers.py+++ b/products/stamphog/backend/tests/test_webhook_consumers.py@@ -1,19 +1,17 @@import hmacimport jsonimport hashlib-from typing import Anyfrom unittest.mock import patchfrom django.core.cache import cache-from django.test import RequestFactory, SimpleTestCase, override_settings+from django.http.response import HttpResponseBase+from django.test import SimpleTestCase, override_settingsfrom parameterized import parameterizedfrom posthog.ingress.dispatch.loading import reset_consumer_registry-from products.stamphog.backend.facade.webhooks import stamphog_github_webhook-WEBHOOK_SECRET = "test-webhook-secret"WEBHOOK_PATH = "/webhooks/stamphog/github"@@ -28,7 +26,6 @@ def _signature(body: bytes, secret: str) -> str:@override_settings(STAMPHOG_GITHUB_APP_WEBHOOK_SECRET=WEBHOOK_SECRET)class TestStamphogGitHubWebhook(SimpleTestCase):def setUp(self) -> None:- self.factory = RequestFactory()# The registry is cached for the process and the dedup marks sit in the cache; both would# otherwise carry another test's state into this one.reset_consumer_registry()@@ -43,11 +40,11 @@ class TestStamphogGitHubWebhook(SimpleTestCase):signature: str | None,event: str = "pull_request",delivery_id: str = "delivery-1",- ) -> Any:+ ) -> HttpResponseBase:headers: dict[str, str] = {"X-GitHub-Event": event, "X-GitHub-Delivery": delivery_id}if signature is not None:headers["X-Hub-Signature-256"] = signature- return self.factory.post(WEBHOOK_PATH, data=body, content_type="application/json", headers=headers)+ return self.client.post(WEBHOOK_PATH, data=body, content_type="application/json", headers=headers)@parameterized.expand([@@ -60,10 +57,9 @@ class TestStamphogGitHubWebhook(SimpleTestCase):self, event: str, expected_task: str, other_task: str) -> None:body = json.dumps({"action": "opened"}).encode("utf-8")- request = self._post(body, event=event, signature=_signature(body, WEBHOOK_SECRET))with patch(expected_task) as expected_delay, patch(other_task) as other_delay:- response = stamphog_github_webhook(request)+ response = self._post(body, event=event, signature=_signature(body, WEBHOOK_SECRET))assert response.status_code == 202expected_delay.assert_called_once_with(payload={"action": "opened"}, delivery_id="delivery-1")@@ -74,8 +70,7 @@ class TestStamphogGitHubWebhook(SimpleTestCase):body = json.dumps({"action": "opened"}).encode("utf-8")for _ in range(2):- request = self._post(body, signature=_signature(body, WEBHOOK_SECRET))- assert stamphog_github_webhook(request).status_code == 202+ assert self._post(body, signature=_signature(body, WEBHOOK_SECRET)).status_code == 202# The task keys its resume path on the delivery id, so GitHub's redelivery is how a run# that never finished gets picked up. An ingress dedup mark would hold that off for 24 h.@@ -87,9 +82,8 @@ class TestStamphogGitHubWebhook(SimpleTestCase):self, mock_installation_delay, mock_pull_request_delay) -> None:body = json.dumps({"action": "created"}).encode("utf-8")- request = self._post(body, event="issue_comment", signature=_signature(body, WEBHOOK_SECRET))- response = stamphog_github_webhook(request)+ response = self._post(body, event="issue_comment", signature=_signature(body, WEBHOOK_SECRET))assert response.status_code == 202mock_pull_request_delay.assert_not_called()@@ -104,9 +98,8 @@ class TestStamphogGitHubWebhook(SimpleTestCase):@patch(PULL_REQUEST_DELAY)def test_an_invalid_signature_is_rejected(self, _name: str, signature: str | None, mock_delay) -> None:body = json.dumps({"action": "opened"}).encode("utf-8")- request = self._post(body, signature=signature)- response = stamphog_github_webhook(request)+ response = self._post(body, signature=signature)assert response.status_code == 403mock_delay.assert_not_called()@@ -114,16 +107,15 @@ class TestStamphogGitHubWebhook(SimpleTestCase):@patch(PULL_REQUEST_DELAY)def test_a_signed_but_unparseable_body_is_rejected(self, mock_delay) -> None:body = b"{not json"- request = self._post(body, signature=_signature(body, WEBHOOK_SECRET))- response = stamphog_github_webhook(request)+ response = self._post(body, signature=_signature(body, WEBHOOK_SECRET))assert response.status_code == 400mock_delay.assert_not_called()@patch(PULL_REQUEST_DELAY)def test_a_non_post_is_refused(self, mock_delay) -> None:- response = stamphog_github_webhook(self.factory.get(WEBHOOK_PATH))+ response = self.client.get(WEBHOOK_PATH)assert response.status_code == 405mock_delay.assert_not_called()@@ -132,9 +124,8 @@ class TestStamphogGitHubWebhook(SimpleTestCase):@patch(PULL_REQUEST_DELAY)def test_a_missing_app_secret_is_500_rather_than_a_signature_failure(self, mock_delay) -> None:body = json.dumps({"action": "opened"}).encode("utf-8")- request = self._post(body, signature=_signature(body, "irrelevant"))- response = stamphog_github_webhook(request)+ response = self._post(body, signature=_signature(body, "irrelevant"))assert response.status_code == 500mock_delay.assert_not_called()diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex a66ceee8eddb..2cf413fee8e2 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -46,6 +46,7 @@ import posthoganalyticsfrom posthog.dataclasses import frozenfrom posthog.event_usage import groups+from posthog.ingress.contracts import WebhookDeliveryfrom posthog.models import Team, Userfrom posthog.models.integration import Integrationfrom posthog.models.oauth import OAuthAccessToken, OAuthRefreshToken@@ -10155,3 +10156,30 @@ def post_pr_created_thread_update(run: TaskRun, pr_url: str) -> None:)except Exception:logger.exception("Failed to post pr-created thread update", extra={"task_id": str(run.task_id)})+++# --- Inbound GitHub App deliveries (entered from backend/webhook_consumers.py) ---+++def accept_github_pull_request(delivery: WebhookDelivery) -> None:+ """The PR backstop that records a pull request the agent output never reported."""+ # Deferred to keep the GitHub client off the facade import path.+ from products.tasks.backend.webhooks import handle_pull_request_event # noqa: PLC0415++ handle_pull_request_event(dict(delivery.payload))+++def accept_github_pull_request_review(delivery: WebhookDelivery) -> None:+ """A review on a PR a task opened, which can resume the run that is waiting on it."""+ # Deferred to keep the GitHub client off the facade import path.+ from products.tasks.backend.webhooks import handle_pull_request_review_event # noqa: PLC0415++ handle_pull_request_review_event(dict(delivery.payload))+++def accept_github_event_for_loops(delivery: WebhookDelivery) -> None:+ """Every event type a loop trigger can match on, which fires the loops whose filters accept it."""+ # Deferred to keep the Redis client off the facade import path.+ from products.tasks.backend.loop_github_events import handle_github_event_for_loops # noqa: PLC0415++ handle_github_event_for_loops(delivery.event_type, dict(delivery.payload), delivery.delivery_id or "")diff --git a/products/tasks/backend/facade/webhooks.py b/products/tasks/backend/facade/webhooks.pydeleted file mode 100644index ad59b999ec09..000000000000--- a/products/tasks/backend/facade/webhooks.py+++ /dev/null@@ -1,6 +0,0 @@-"""Task-owned GitHub PR processing and loop triggers."""--from products.tasks.backend.loop_github_events import handle_github_event_for_loops-from products.tasks.backend.webhooks import handle_pull_request_event, handle_pull_request_review_event--__all__ = ["handle_github_event_for_loops", "handle_pull_request_event", "handle_pull_request_review_event"]diff --git a/products/tasks/backend/loop_github_events.py b/products/tasks/backend/loop_github_events.pyindex 618a3c38c56d..18490d2dd190 100644--- a/products/tasks/backend/loop_github_events.py+++ b/products/tasks/backend/loop_github_events.py@@ -1,9 +1,9 @@"""GitHub event matching and firing for Loops.-The entry point is ``handle_github_event_for_loops``, registered as a handler in the-GitHub App webhook fan-out (``posthog.urls.github_webhook``) for the ``pull_request``,-``issues``, ``issue_comment`` and ``push`` events. Called after signature verification-and JSON parsing, alongside the other webhook consumers.+The entry point is ``handle_github_event_for_loops``, registered by+``products/tasks/backend/webhook_consumers.py`` as the ``loops`` consumer on the GitHub App+endpoint for the ``pull_request``, ``issues``, ``issue_comment`` and ``push`` events. Called+after signature verification and JSON parsing, alongside the other consumers."""import time@@ -13,6 +13,7 @@ import structlogfrom prometheus_client import Counterfrom posthog.exceptions_capture import capture_exception+from posthog.ingress.dispatch.database import bounded_statement_timeout, is_statement_timeoutfrom posthog.models.integration import Integrationfrom posthog.redis import get_client@@ -30,6 +31,12 @@ _SELF_TRIGGER_BRANCH_PREFIX = "loop/"_EVENT_THROTTLE_LIMIT = 300_EVENT_THROTTLE_WINDOW_SECONDS = 300+# Cap the matching lookups. This consumer runs inside the fan-out's shared per-delivery budget,+# which cannot interrupt a query already in flight, so a slow lookup costs every other consumer+# on the delivery too. Bounding it degrades to a missed match instead. Same cap as the GitHub+# attribution lookup in posthog/github/attribution.py.+_MATCH_STATEMENT_TIMEOUT_MS = 800+LoopGithubEventOutcome = Literal["matched", "deduped", "skipped", "throttled", "fired", "error"]LOOP_GITHUB_EVENT_TOTAL = Counter(@@ -85,11 +92,24 @@ def handle_github_event_for_loops(event_type: str, payload: dict[str, Any], deliaction = payload.get("action")summary = _build_event_summary(event_type, payload)- matched = 0- for integration in Integration.objects.filter(kind="github", integration_id=installation_id):- matched += _match_and_fire_for_integration(- integration, repository_full_name, event_type, action, payload, delivery_id, summary+ try:+ triggers = _matching_triggers(installation_id, repository_full_name, event_type, action, payload, delivery_id)+ except Exception as e:+ if not is_statement_timeout(e):+ raise+ logger.warning(+ "loop_github_event_match_timed_out",+ event_type=event_type,+ delivery_id=delivery_id,+ repository=repository_full_name,)+ _observe_github_event("skipped")+ return++ # Outside the cap on purpose: firing writes rows and dispatches a run, and the cap is there to+ # bound the lookups a delivery waits on, not the work it decided to do.+ for trigger in triggers:+ _fire_matched_trigger(trigger, delivery_id, summary)logger.info("loop_github_event_matched",@@ -97,52 +117,89 @@ def handle_github_event_for_loops(event_type: str, payload: dict[str, Any], deliaction=action,delivery_id=delivery_id,repository=repository_full_name,- matched_triggers=matched,+ matched_triggers=len(triggers),)-def _match_and_fire_for_integration(+def _matching_triggers(+ installation_id: str,+ repository_full_name: str,+ event_type: str,+ action: str | None,+ payload: dict[str, Any],+ delivery_id: str,+) -> list[LoopTrigger]:+ """Collect the triggers every team on this installation matches.++ Only the installation lookup is capped here. Each team's trigger lookup carries its own cap,+ so a cancelled statement for one team leaves the matches the other teams already produced.+ """+ with bounded_statement_timeout(_MATCH_STATEMENT_TIMEOUT_MS, models=[Integration]):+ integrations = list(Integration.objects.filter(kind="github", integration_id=installation_id))++ triggers: list[LoopTrigger] = []+ for integration in integrations:+ triggers.extend(+ _matching_triggers_for_integration(+ integration, repository_full_name, event_type, action, payload, delivery_id+ )+ )+ return triggers+++def _matching_triggers_for_integration(integration: Integration,repository_full_name: str,event_type: str,action: str | None,payload: dict[str, Any],delivery_id: str,- summary: dict[str, Any],-) -> int:- """Match and fire triggers for one team's integration, isolated from other teams.+) -> list[LoopTrigger]:+ """Match triggers for one team's integration, isolated from other teams.A lookup failure for one team (e.g. a stale team reference) must not stop thesame delivery from firing loops for every other team sharing the installation.++ The cap sits on this query rather than around the whole match, because a cancelled statement+ aborts the transaction it was installed in. One transaction per team keeps that abort local."""try:- triggers = (- LoopTrigger.objects.for_team(integration.team_id)- .filter(- type=LoopTrigger.TriggerType.GITHUB,- enabled=True,- loop__enabled=True,- loop__deleted=False,- github_integration_id=integration.id,- repository__iexact=repository_full_name,- event_types__contains=[event_type],+ with bounded_statement_timeout(_MATCH_STATEMENT_TIMEOUT_MS, models=[LoopTrigger]):+ triggers = list(+ LoopTrigger.objects.for_team(integration.team_id)+ .filter(+ type=LoopTrigger.TriggerType.GITHUB,+ enabled=True,+ loop__enabled=True,+ loop__deleted=False,+ github_integration_id=integration.id,+ repository__iexact=repository_full_name,+ event_types__contains=[event_type],+ )+ .select_related("loop"))- .select_related("loop")- )except Exception as e:+ if is_statement_timeout(e):+ logger.warning(+ "loop_github_events_trigger_lookup_timed_out",+ integration_id=integration.id,+ team_id=integration.team_id,+ delivery_id=delivery_id,+ )+ _observe_github_event("skipped")+ return []logger.exception("loop_github_event_team_lookup_failed", team_id=integration.team_id, delivery_id=delivery_id)capture_exception(e)_observe_github_event("error")- return 0+ return []- matched = 0+ matched: list[LoopTrigger] = []for trigger in triggers:if not _trigger_filters_match(trigger, action, payload):continue- matched += 1+ matched.append(trigger)_observe_github_event("matched")- _fire_matched_trigger(trigger, delivery_id, summary)return matcheddiff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.pyindex d752b59d9cf7..5d71f8640ca1 100644--- a/products/tasks/backend/tests/test_facade.py+++ b/products/tasks/backend/tests/test_facade.py@@ -46,7 +46,6 @@ FACADE_MODULES = ["products.tasks.backend.facade.streams","products.tasks.backend.facade.temporal","products.tasks.backend.facade.max_tools",- "products.tasks.backend.facade.webhooks",]diff --git a/products/tasks/backend/tests/test_loop_github_events.py b/products/tasks/backend/tests/test_loop_github_events.pyindex bb2d43cf8831..a157f4509faf 100644--- a/products/tasks/backend/tests/test_loop_github_events.py+++ b/products/tasks/backend/tests/test_loop_github_events.py@@ -4,6 +4,7 @@ from typing import ClassVarimport time_machinefrom unittest.mock import patch+from django.db import OperationalErrorfrom django.test import TestCasefrom parameterized import parameterized@@ -414,6 +415,64 @@ class TestHandleGithubEventForLoops(TestCase):fire_keys = [call.kwargs["fire_key"] for call in mock_fire_loop.call_args_list]self.assertEqual(fire_keys, ["del-redelivered", "del-redelivered", "del-other"])+ @patch(f"{LOOP_GITHUB_EVENTS_MODULE}.logger")+ @patch(FIRE_LOOP_PATCH_TARGET, autospec=True)+ def test_one_teams_trigger_lookup_timing_out_still_fires_the_other_teams(self, mock_fire_loop, mock_logger):+ team_b = Team.objects.create(organization=self.organization, name="Team B")+ Integration.objects.create(team=team_b, kind="github", integration_id="998877", config={})++ loop_a = self._create_loop(self.team, name="Loop A")+ trigger_a = self._create_github_trigger(+ self.team,+ loop_a,+ github_integration_id=self.integration.id,+ repository="acme/repo",+ events=["push"],+ )+ payload = self._event_payload("push", installation_id=998877, repository="acme/repo")++ real_for_team = LoopTrigger.objects.for_team++ def for_team(team_id, *args, **kwargs):+ if team_id == team_b.id:+ raise OperationalError("canceling statement due to statement timeout")+ return real_for_team(team_id, *args, **kwargs)++ with patch.object(LoopTrigger.objects, "for_team", side_effect=for_team):+ handle_github_event_for_loops("push", payload, delivery_id="del-timeout")++ mock_fire_loop.assert_called_once()+ self.assertEqual(mock_fire_loop.call_args.kwargs["trigger"].id, trigger_a.id)+ warnings = [call.args[0] for call in mock_logger.warning.call_args_list]+ self.assertEqual(warnings, ["loop_github_events_trigger_lookup_timed_out"])++ @patch(f"{LOOP_GITHUB_EVENTS_MODULE}.logger")+ @patch(FIRE_LOOP_PATCH_TARGET, autospec=True)+ def test_an_installation_lookup_timeout_skips_the_delivery_instead_of_firing(self, mock_fire_loop, mock_logger):+ # The fan-out's per-delivery budget cannot interrupt a query already in flight, so the+ # statement cap is what keeps a slow match from costing the whole delivery. A cancelled+ # statement must leave the consumer reporting "skipped", not escape it.+ loop = self._create_loop(self.team)+ self._create_github_trigger(+ self.team,+ loop,+ github_integration_id=self.integration.id,+ repository="acme/repo",+ events=["push"],+ )+ payload = self._event_payload("push", installation_id=998877, repository="acme/repo")++ with patch.object(+ Integration.objects,+ "filter",+ side_effect=OperationalError("canceling statement due to statement timeout"),+ ):+ handle_github_event_for_loops("push", payload, delivery_id="del-timeout")++ mock_fire_loop.assert_not_called()+ warnings = [call.args[0] for call in mock_logger.warning.call_args_list]+ self.assertEqual(warnings, ["loop_github_event_match_timed_out"])+@patch(FIRE_LOOP_PATCH_TARGET, autospec=True)def test_event_flood_beyond_the_throttle_stops_matching_and_firing(self, mock_fire_loop):# A collaborator streaming matching events with unique delivery ids must be boundeddiff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex e01e963d19d8..02d5af04a5a1 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -14,8 +14,8 @@ from prometheus_client import REGISTRYfrom rest_framework.test import APIClientfrom social_django.models import UserSocialAuth-from posthog.api.github_webhooks.integrations import _installation_team_ids-from posthog.api.github_webhooks.pull_requests import _PR_BODY_MAX_CHARS, _account_type+from posthog.github.installations import installation_team_ids+from posthog.github.pull_request_events import _PR_BODY_MAX_CHARS, _account_typefrom posthog.models.integration import Integrationfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Team@@ -104,8 +104,8 @@ class TestGitHubPRWebhook(TestCase):headers={"x-hub-signature-256": signature, "x-github-event": event_type},)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_webhook(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -119,7 +119,7 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_called_once()call_kwargs = mock_capture.call_args[1]@@ -139,8 +139,8 @@ class TestGitHubPRWebhook(TestCase):("unresolvable_login", "stranger", None, "user-123"),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_attributes_to_merger(self, _name, merged_by_login, expected_property, expected_distinct_id, mock_capture, mock_get_secret):@@ -160,16 +160,16 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["distinct_id"], expected_distinct_id)self.assertEqual(call_kwargs["properties"]["pr_merged_by_login"], merged_by_login)self.assertEqual(call_kwargs["properties"]["pr_merged_by_id"], 583231)self.assertEqual(call_kwargs["properties"].get("pr_merged_by_distinct_id"), expected_property)- @patch("posthog.api.github_webhooks.attribution.resolve_github_login_distinct_id", side_effect=RuntimeError("boom"))- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("products.signals.backend.facade.github.resolve_github_login_distinct_id", side_effect=RuntimeError("boom"))+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_by_resolution_failure_keeps_webhook_successful(self, mock_capture, mock_get_secret, _mock_resolve):@@ -186,18 +186,18 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)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"])@patch(- "posthog.api.github_webhooks.attribution.resolve_github_login_distinct_id",+ "products.signals.backend.facade.github.resolve_github_login_distinct_id",side_effect=OperationalError("canceling statement due to statement timeout"),)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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.@@ -215,7 +215,7 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)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")@@ -228,11 +228,11 @@ class TestGitHubPRWebhook(TestCase):self.assertIs(self.task_run.output.get("pr_merged"), True)@patch(- "posthog.api.github_webhooks.attribution.resolve_github_login_distinct_id",+ "products.signals.backend.facade.github.resolve_github_login_distinct_id",side_effect=OperationalError("server closed the connection unexpectedly"),)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_attribution_connection_error_is_not_counted_as_timeout(self, mock_capture, mock_get_secret, _mock_resolve):@@ -253,7 +253,7 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)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@@ -262,10 +262,8 @@ class TestGitHubPRWebhook(TestCase):_sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "timeout"}), timeouts)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch(- "posthog.api.github_webhooks.pull_requests.posthoganalytics.capture", side_effect=RuntimeError("capture down")- )+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture", side_effect=RuntimeError("capture down"))def test_task_backed_capture_failure_increments_drop_counter(self, _mock_capture, mock_get_secret):# Capture failures must still count as dropped events for Task-owned PRs.mock_get_secret.return_value = self.webhook_secret@@ -279,11 +277,11 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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.@@ -298,12 +296,12 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)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("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_publishes_stream_events(self, mock_capture, mock_get_secret):# A live installation-progress view only learns about the merge through the stream;# recording output.pr_merged without publishing leaves the UI stuck on "opened".@@ -319,14 +317,14 @@ class TestGitHubPRWebhook(TestCase):with patch.object(TaskRun, "publish_stream_event") as mock_publish:response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)published = [c.args[0] for c in mock_publish.call_args_list if c.args]progress = [e for e in published if e.get("notification", {}).get("method") == "_posthog/progress"]self.assertEqual(len(progress), 1)self.assertEqual(progress[0]["notification"]["params"]["label"], "Pull request merged")- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_from_fork_does_not_record_pr_merged(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretrun = TaskRun.objects.create(@@ -347,13 +345,13 @@ class TestGitHubPRWebhook(TestCase):}response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)run.refresh_from_db()self.assertEqual(run.output, {})- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_for_other_pr_on_same_branch_does_not_record_pr_merged(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretrun = TaskRun.objects.create(@@ -374,7 +372,7 @@ class TestGitHubPRWebhook(TestCase):}response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)run.refresh_from_db()self.assertEqual(@@ -405,8 +403,8 @@ class TestGitHubPRWebhook(TestCase):("already_terminal_run", {"wizard_config": {}}, TaskRun.Status.COMPLETED, {}, 0),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_signals_wizard_workflow_completion(self, _name, state, status, extra_output, expected_signals, _mock_capture, mock_get_secret):@@ -424,13 +422,13 @@ class TestGitHubPRWebhook(TestCase):with self.captureOnCommitCallbacks(execute=True):response = self._make_webhook_request(self._merged_pr_payload(pr_url))- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.assertEqual(mock_signal.call_count, expected_signals)if expected_signals:mock_signal.assert_called_once_with(run.id, TaskRun.Status.COMPLETED, None)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_resolves_to_active_run_when_resume_shares_pr(self, _mock_capture, mock_get_secret):# A resumed wizard run shares its predecessor's PR; the merge must land on the# live run (recording pr_merged and signaling wind-down), not the dead original.@@ -460,7 +458,7 @@ class TestGitHubPRWebhook(TestCase):with self.captureOnCommitCallbacks(execute=True):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_signal.assert_called_once_with(active_run.id, TaskRun.Status.COMPLETED, None)active_run.refresh_from_db()terminal_run.refresh_from_db()@@ -468,8 +466,8 @@ class TestGitHubPRWebhook(TestCase):self.assertIs(active_run.output.get("pr_merged"), True)self.assertNotIn("pr_merged", terminal_run.output)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_merged_signal_failure_keeps_webhook_successful(self, _mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretpr_url = "https://github.com/posthog/posthog/pull/778"@@ -488,7 +486,7 @@ class TestGitHubPRWebhook(TestCase):with self.captureOnCommitCallbacks(execute=True):response = self._make_webhook_request(self._merged_pr_payload(pr_url))- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)run.refresh_from_db()assert run.output is not Noneself.assertIs(run.output.get("pr_merged"), True)@@ -511,8 +509,8 @@ class TestGitHubPRWebhook(TestCase):("local_run", {"wizard_config": {}}, TaskRun.Status.IN_PROGRESS, TaskRun.Environment.LOCAL, 0),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_closed_cancels_wizard_run(self, _name, state, status, environment, expected_cancels, _mock_capture, mock_get_secret):@@ -531,7 +529,7 @@ class TestGitHubPRWebhook(TestCase):with self.captureOnCommitCallbacks(execute=True):response = self._make_webhook_request(self._closed_pr_payload(pr_url))- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.assertEqual(mock_cancel.call_count, expected_cancels)if expected_cancels:mock_cancel.assert_called_once_with(@@ -542,8 +540,8 @@ class TestGitHubPRWebhook(TestCase):source="pr_closed",)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_closed_cancel_failure_keeps_webhook_successful(self, _mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretpr_url = "https://github.com/posthog/posthog/pull/781"@@ -562,10 +560,10 @@ class TestGitHubPRWebhook(TestCase):with self.captureOnCommitCallbacks(execute=True):response = self._make_webhook_request(self._closed_pr_payload(pr_url))- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_closed_without_merge_webhook(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -579,14 +577,14 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_called_once()call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["event"], "pr_closed")- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_opened_webhook(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -605,7 +603,7 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_called_once()call_kwargs = mock_capture.call_args[1]@@ -624,8 +622,8 @@ class TestGitHubPRWebhook(TestCase):("over_the_cap", _PR_BODY_MAX_CHARS + 1, True),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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@@ -638,7 +636,7 @@ class TestGitHubPRWebhook(TestCase):},}- self.assertEqual(self._make_webhook_request(payload).status_code, 200)+ self.assertEqual(self._make_webhook_request(payload).status_code, 202)props = mock_capture.call_args[1]["properties"]self.assertEqual(len(props["pr_body"]), min(body_length, _PR_BODY_MAX_CHARS))@@ -657,8 +655,8 @@ class TestGitHubPRWebhook(TestCase):("closed", {"merged": True}, "merged"),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_action_records_pr_state(self, action_name, pr_fields, expected_state, _mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretaction = "opened" if action_name == "opened_as_draft" else action_name@@ -673,13 +671,13 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.task_run.refresh_from_db()assert self.task_run.output is not Noneself.assertEqual(self.task_run.output.get("pr_state"), expected_state)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_state_only_action_records_state_without_analytics(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -693,14 +691,14 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_not_called()self.task_run.refresh_from_db()assert self.task_run.output is not Noneself.assertEqual(self.task_run.output.get("pr_state"), "draft")- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_state_not_recorded_for_unclaimed_pr(self, _mock_capture, mock_get_secret):"""A same-branch webhook for a different PR must not restate this run's PR."""mock_get_secret.return_value = self.webhook_secret@@ -717,13 +715,13 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.task_run.refresh_from_db()assert self.task_run.output is not Noneself.assertNotIn("pr_state", self.task_run.output)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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_secretrun = TaskRun.objects.create(@@ -745,7 +743,7 @@ class TestGitHubPRWebhook(TestCase):}response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)run.refresh_from_db()assert run.output is not None@@ -753,8 +751,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(run.state["verified_pr_urls"], [pr_url])@patch("products.tasks.backend.facade.api.posthoganalytics.feature_enabled", return_value=True)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_opened_repairs_missing_artifact_for_existing_pr_url(self, mock_capture, mock_get_secret, mock_feature_enabled) -> None:@@ -779,13 +777,13 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.assertTrue(TaskThreadMessage.objects.for_team(self.team.id).filter(task=self.task, payload__pr_url=pr_url).exists())- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_opened_backfills_pr_url_on_wizard_head_branch_match(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretrun = TaskRun.objects.create(@@ -808,14 +806,14 @@ class TestGitHubPRWebhook(TestCase):}response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)run.refresh_from_db()assert run.output is not Noneself.assertEqual(run.output["pr_url"], pr_url)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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_secretrun = TaskRun.objects.create(@@ -836,13 +834,13 @@ class TestGitHubPRWebhook(TestCase):}response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)run.refresh_from_db()self.assertEqual(run.output, {})- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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_secrethead_branch = "posthog-self-driving/fix-thing-abc123"@@ -890,7 +888,7 @@ class TestGitHubPRWebhook(TestCase):}response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)impl_run.refresh_from_db()review_run.refresh_from_db()@@ -900,8 +898,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(review_run.output, {})self.assertNotIn("verified_pr_urls", review_run.state or {})- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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_secretexisting = "https://github.com/posthog/posthog/pull/900"@@ -923,7 +921,7 @@ class TestGitHubPRWebhook(TestCase):}response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)run.refresh_from_db()assert run.output is not None@@ -933,7 +931,7 @@ class TestGitHubPRWebhook(TestCase):[existing, "https://github.com/posthog/posthog/pull/901"],)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_invalid_signature_rejected(self, mock_get_secret):"""Test that requests with invalid signatures are rejected."""mock_get_secret.return_value = self.webhook_secret@@ -950,7 +948,7 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 403)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_missing_signature_rejected(self, mock_get_secret):"""Test that requests without signatures are rejected."""mock_get_secret.return_value = self.webhook_secret@@ -966,8 +964,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 403)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_unmatched_pr_without_installation_not_captured(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -981,10 +979,10 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_not_called()- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_non_pr_non_issue_event_ignored(self, mock_get_secret):"""Test that events other than pull_request/issues/issue_comment are acknowledged but ignored."""mock_get_secret.return_value = self.webhook_secret@@ -993,9 +991,9 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload, event_type="push")- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_ignored_pr_actions(self, mock_get_secret):"""Test that PR actions other than opened/closed are acknowledged but ignored."""mock_get_secret.return_value = self.webhook_secret@@ -1010,11 +1008,11 @@ class TestGitHubPRWebhook(TestCase):}response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200, f"Failed for action: {action}")+ self.assertEqual(response.status_code, 202, f"Failed for action: {action}")def test_webhook_secret_not_configured(self):"""Test that webhook returns 500 if secret is not configured."""- with patch("posthog.api.github_webhooks.views.get_github_webhook_secret", return_value=None):+ with patch("posthog.ingress.github.provider.get_instance_setting", return_value=None):payload = {"action": "closed", "pull_request": {"html_url": "https://github.com/org/repo/pull/1"}}response = self.client.post(@@ -1031,8 +1029,8 @@ class TestGitHubPRWebhook(TestCase):response = self.client.get("/webhooks/github/pr/")self.assertEqual(response.status_code, 405)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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@@ -1057,7 +1055,7 @@ class TestGitHubPRWebhook(TestCase):response = self._make_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_not_called()@@ -1119,8 +1117,8 @@ class TestGitHubPRReviewWebhook(TestCase):("unresolvable_login", "stranger", None, "user-123"),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_review_submission_attributes_to_reviewer(self, _name, reviewer_login, expected_property, expected_distinct_id, mock_capture, mock_get_secret):@@ -1134,7 +1132,7 @@ class TestGitHubPRReviewWebhook(TestCase):)response = self._make_review_webhook_request(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["event"], "pr_reviewed")self.assertEqual(call_kwargs["distinct_id"], expected_distinct_id)@@ -1151,14 +1149,14 @@ class TestGitHubPRReviewWebhook(TestCase):("non_submitted_action", {"login": "octocat", "id": 583231, "type": "User"}, "dismissed"),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_review_events_not_captured(self, _name, reviewer, action, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretresponse = self._make_review_webhook_request(self._review_payload(reviewer, action=action))- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_not_called()@@ -1214,8 +1212,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):("research", True, None, "research", SignalReport.Status.READY),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_event_falls_back_to_task_links(self, _name, merged, actor_kind, relationship, expected_status, _mock_capture, mock_get_secret):@@ -1231,7 +1229,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):with self.captureOnCommitCallbacks(execute=True):response = self._post_pr_webhook(action="closed", merged=merged)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.report.refresh_from_db()self.assertEqual(self.report.status, expected_status)close_task.delay.assert_not_called()@@ -1244,7 +1242,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):self.assertEqual(pr.state, "merged" if merged else "closed")self.assertIs(pr.merged, merged)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")@patch("products.tasks.backend.models.posthoganalytics.capture")def test_secondary_task_pr_webhook_persists_only_matching_link_and_reads_the_stack(self, _capture, get_secret):from products.signals.backend.models import SignalReportPullRequest@@ -1255,7 +1253,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):second = "https://github.com/PostHog/posthog/pull/43"run = self._link_task_pr(self.report, first)TaskRun.objects.filter(id=run.id).update(output={"pr_url": first, "pr_urls": [first, second]})- assert self._post_pr_webhook("closed", True, second).status_code == 200+ assert self._post_pr_webhook("closed", True, second).status_code == 202run.refresh_from_db()assert isinstance(run.output, dict)@@ -1265,7 +1263,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):assert self.report.status == SignalReport.Status.READYassert SignalReportPullRequest.objects.for_team(self.team.id).count() == 1assert SignalReportPullRequest.objects.for_team(self.team.id).get(number=43).state == "merged"- assert self._post_pr_webhook("closed", False, first).status_code == 200+ assert self._post_pr_webhook("closed", False, first).status_code == 202self.report.refresh_from_db()assert self.report.status == SignalReport.Status.RESOLVED@@ -1322,8 +1320,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_event_transitions_linked_report(self,_name,@@ -1341,7 +1339,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):response = self._post_pr_webhook(action="closed", merged=merged)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.report.refresh_from_db()self.assignment.refresh_from_db()self.assertEqual(self.report.status, expected_status)@@ -1358,15 +1356,15 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):merged,)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_merge_without_matching_assignment_is_a_noop(self, _mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretself.assignment.delete()response = self._post_pr_webhook(action="closed", merged=True)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.report.refresh_from_db()self.assertEqual(self.report.status, SignalReport.Status.READY)@@ -1376,8 +1374,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):("closed", False, SignalReport.Status.SUPPRESSED, SignalReportAssignment.PrState.CLOSED),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_event_transitions_every_report_linked_to_the_pr(self, _name, merged, expected_status, expected_pr_state, _mock_capture, mock_get_secret):@@ -1402,7 +1400,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):response = self._post_pr_webhook(action="closed", merged=merged)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.report.refresh_from_db()second_report.refresh_from_db()self.assignment.refresh_from_db()@@ -1436,8 +1434,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):legacy_report.refresh_from_db()self.assertEqual(legacy_report.status, expected_status)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_event_does_not_transition_assignment_for_another_pr(self, _mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretassert self.assignment.pr_url is not None@@ -1448,15 +1446,15 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):response = self._post_pr_webhook(action="closed", merged=True)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.report.refresh_from_db()self.assignment.refresh_from_db()self.assertEqual(self.report.status, SignalReport.Status.READY)self.assertEqual(self.assignment.pr_state, SignalReportAssignment.PrState.OPEN)self.assertFalse(self.assignment.pr_merged)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_event_only_updates_teams_connected_to_the_installation(self, _mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretother_organization = Organization.objects.create(name="Other Org")@@ -1481,7 +1479,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):response = self._post_pr_webhook(action="closed", merged=True)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.report.refresh_from_db()other_report.refresh_from_db()self.assignment.refresh_from_db()@@ -1505,8 +1503,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):("www_host_trailing_slash", "https://www.github.com/posthog/posthog/pull/42/"),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pr_url_variants_match_by_repository_and_number(self, _name, stored_pr_url, _mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretself.assignment.pr_url = stored_pr_url@@ -1514,7 +1512,7 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):response = self._post_pr_webhook(action="closed", merged=True)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)self.report.refresh_from_db()self.assignment.refresh_from_db()self.assertEqual(self.report.status, SignalReport.Status.RESOLVED)@@ -1593,8 +1591,8 @@ class TestExternalPRWebhook(TestCase):("merged", "closed", True, "pr_merged"),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_external_pr_event_attributes_to_installation_team(self, _name, action, merged, expected_event, mock_capture, mock_get_secret):@@ -1602,7 +1600,7 @@ class TestExternalPRWebhook(TestCase):response = self._post(self._external_payload(action, merged))- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_called_once()call_kwargs = mock_capture.call_args[1]props = call_kwargs["properties"]@@ -1628,22 +1626,22 @@ class TestExternalPRWebhook(TestCase):for key in ("pr_title", "pr_body", "pr_labels", "pr_requested_reviewers", "pr_is_draft"):self.assertIsNone(props[key])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_external_pr_event_is_deduplicated_per_action(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretpayload = self._external_payload("closed", merged=True)- self.assertEqual(self._post(payload).status_code, 200)- self.assertEqual(self._post(payload).status_code, 200)+ self.assertEqual(self._post(payload).status_code, 202)+ self.assertEqual(self._post(payload).status_code, 202)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("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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@@ -1652,11 +1650,11 @@ class TestExternalPRWebhook(TestCase):response = self._post(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_not_called()- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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.@@ -1666,15 +1664,13 @@ class TestExternalPRWebhook(TestCase):payload = self._external_payload("closed", merged=True)payload["installation"]["id"] = 999999- self.assertEqual(self._post(payload).status_code, 200)+ self.assertEqual(self._post(payload).status_code, 202)mock_capture.assert_not_called()self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch(- "posthog.api.github_webhooks.pull_requests.posthoganalytics.capture", side_effect=RuntimeError("capture down")- )+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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_secretlabels = {"analytics_event": "pr_created", "reason": "capture_exception"}@@ -1682,7 +1678,7 @@ class TestExternalPRWebhook(TestCase):response = self._post(self._external_payload("opened", merged=False))- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)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):@@ -1706,10 +1702,10 @@ class TestExternalPRWebhook(TestCase):sorted([self.team.id, personal_team.id]),)# Attribution still resolves off the Integration rows alone.- self.assertEqual(_installation_team_ids(payload), [self.team.id])+ self.assertEqual(installation_team_ids(payload), [self.team.id])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.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@@ -1739,7 +1735,7 @@ class TestExternalPRWebhook(TestCase):response = self._post(self._external_payload("opened", merged=False))- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_called_once()properties = mock_capture.call_args[1]["properties"]self.assertEqual(properties["pr_source"], "external")@@ -1747,8 +1743,8 @@ class TestExternalPRWebhook(TestCase):self.assertIsNone(properties["run_id"])self.assertEqual(_sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels), before + 1)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_external_pr_shared_installation_resolves_deterministically(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretother_team = Team.objects.create(organization=self.organization, name="Other External Team")@@ -1757,14 +1753,14 @@ class TestExternalPRWebhook(TestCase):)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)+ self.assertEqual(self._post(self._external_payload("closed", merged=True)).status_code, 202)+ self.assertEqual(self._post(self._external_payload("closed", merged=True)).status_code, 202)distinct_ids = {call[1]["distinct_id"] for call in mock_capture.call_args_list}self.assertEqual(distinct_ids, {str(expected_team.uuid)})- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_external_pr_without_installation_block_is_dropped(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secretpayload = self._external_payload("opened", merged=False)@@ -1772,7 +1768,7 @@ class TestExternalPRWebhook(TestCase):response = self._post(payload)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_not_called()@@ -2253,8 +2249,8 @@ class TestGitHubWebhookFanout(TestCase):("unified_url", "/webhooks/github/"),])- @patch("products.conversations.backend.api.github_events.process_github_event")- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("products.conversations.backend.services.github_events.process_github_event")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_issues_event_dispatched_to_conversations(self, _name, url, mock_secret, mock_task):mock_secret.return_value = self.webhook_secretmock_task.delay = MagicMock()@@ -2276,8 +2272,8 @@ class TestGitHubWebhookFanout(TestCase):self.assertEqual(call_kwargs["team_id"], self.team.id)self.assertEqual(call_kwargs["repo"], "myorg/myrepo")- @patch("products.conversations.backend.api.github_events.process_github_event")- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("products.conversations.backend.services.github_events.process_github_event")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_issue_comment_event_dispatched_to_conversations(self, mock_secret, mock_task):mock_secret.return_value = self.webhook_secretmock_task.delay = MagicMock()@@ -2297,9 +2293,9 @@ class TestGitHubWebhookFanout(TestCase):mock_task.delay.assert_called_once()self.assertEqual(mock_task.delay.call_args[1]["event_type"], "issue_comment")- @patch("products.conversations.backend.api.github_events.process_github_event")- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- def test_issues_event_without_matching_team_returns_200(self, mock_secret, mock_task):+ @patch("products.conversations.backend.services.github_events.process_github_event")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ def test_issues_event_without_matching_team_is_not_dispatched(self, mock_secret, mock_task):mock_secret.return_value = self.webhook_secretmock_task.delay = MagicMock()@@ -2313,7 +2309,7 @@ class TestGitHubWebhookFanout(TestCase):response = self._make_request(payload, event_type="issues")- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_task.delay.assert_not_called()@parameterized.expand(@@ -2322,8 +2318,8 @@ class TestGitHubWebhookFanout(TestCase):("unified_url", "/webhooks/github/"),])- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")+ @patch("posthog.ingress.github.provider.get_instance_setting")+ @patch("posthog.github.pull_request_events.posthoganalytics.capture")def test_pull_request_routed(self, _name, url, mock_capture, mock_secret):mock_secret.return_value = self.webhook_secret@@ -2337,20 +2333,20 @@ class TestGitHubWebhookFanout(TestCase):response = self._make_request(payload, event_type="pull_request", url=url)- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)mock_capture.assert_called_once()self.assertEqual(mock_capture.call_args[1]["event"], "pr_merged")- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")- def test_unified_url_unknown_event_returns_200(self, mock_secret):+ @patch("posthog.ingress.github.provider.get_instance_setting")+ def test_unified_url_unknown_event_is_accepted(self, mock_secret):mock_secret.return_value = self.webhook_secretpayload = {"action": "created", "ref": "refs/heads/main"}response = self._make_request(payload, event_type="push", url="/webhooks/github/")- self.assertEqual(response.status_code, 200)+ self.assertEqual(response.status_code, 202)- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_failed_handler_releases_dedup_so_redelivery_is_processed(self, mock_secret):# The dedup mark is set before the handler runs; a handler failure must release it so# GitHub's redelivery of the same GUID gets processed instead of silently skipped for@@ -2362,22 +2358,22 @@ class TestGitHubWebhookFanout(TestCase):"installation": {"id": 77777},"repository": {"full_name": "myorg/myrepo"},}- loops_handler = "products.tasks.backend.facade.webhooks.handle_github_event_for_loops"+ loops_handler = "products.tasks.backend.loop_github_events.handle_github_event_for_loops"with patch(loops_handler, side_effect=RuntimeError("boom")):first = self._make_request(payload, event_type="push", url="/webhooks/github/", delivery_id="del-retry")- self.assertEqual(first.status_code, 200)+ self.assertEqual(first.status_code, 202)with patch(loops_handler) as mock_loops:second = self._make_request(payload, event_type="push", url="/webhooks/github/", delivery_id="del-retry")- self.assertEqual(second.status_code, 200)+ self.assertEqual(second.status_code, 202)mock_loops.assert_called_once()third = self._make_request(payload, event_type="push", url="/webhooks/github/", delivery_id="del-retry")- self.assertEqual(third.status_code, 200)+ self.assertEqual(third.status_code, 202)mock_loops.assert_called_once()- @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.ingress.github.provider.get_instance_setting")def test_unified_url_bad_signature_returns_403(self, mock_secret):mock_secret.return_value = self.webhook_secretdiff --git a/products/tasks/backend/webhook_consumers.py b/products/tasks/backend/webhook_consumers.pynew file mode 100644index 000000000000..77056250dc17--- /dev/null+++ b/products/tasks/backend/webhook_consumers.py@@ -0,0 +1,50 @@+"""Tasks' consumers on the customer-facing GitHub App endpoint.++The registry imports this module on the first delivery, so it stays cheap: every handler defers+its own product import.+"""++from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery+++def _run_pr_backstop(delivery: WebhookDelivery) -> None:+ from products.tasks.backend.facade.api import accept_github_pull_request # noqa: PLC0415++ accept_github_pull_request(delivery)+++def _run_pr_review(delivery: WebhookDelivery) -> None:+ from products.tasks.backend.facade.api import accept_github_pull_request_review # noqa: PLC0415++ accept_github_pull_request_review(delivery)+++def _run_loops(delivery: WebhookDelivery) -> None:+ from products.tasks.backend.facade.api import accept_github_event_for_loops # noqa: PLC0415++ accept_github_event_for_loops(delivery)+++WEBHOOK_CONSUMERS = (+ WebhookConsumer(+ name="tasks_pr_backstop",+ provider="github",+ app="posthog",+ event_types=frozenset({"pull_request"}),+ handler=_run_pr_backstop,+ ),+ WebhookConsumer(+ name="tasks_pr_review",+ provider="github",+ app="posthog",+ event_types=frozenset({"pull_request_review"}),+ handler=_run_pr_review,+ ),+ WebhookConsumer(+ name="loops",+ provider="github",+ app="posthog",+ event_types=frozenset({"issues", "issue_comment", "pull_request", "push"}),+ handler=_run_loops,+ ),+)diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex a4382bcdd12f..f370b3b536d8 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -1,14 +1,12 @@from django.db import transactionfrom django.db.models import Case, IntegerField, Q, Value, When-from django.http import HttpResponseimport structlog-from posthog.api.github_webhooks.contracts import PullRequestAttribution-from posthog.api.github_webhooks.integrations import _SCOPE_DB_ALIAS, _installation_id, _installation_team_ids-from posthog.api.github_webhooks.metrics import GitHubWebhookAnalyticsEvent, observe_github_webhook_pr_event_dropped-from posthog.api.github_webhooks.pull_requests import capture_pr_event, pr_state_for_actionfrom posthog.event_usage import groups+from posthog.github.installations import SCOPE_DB_ALIAS, installation_id, installation_team_ids+from posthog.github.metrics import GitHubWebhookAnalyticsEvent, observe_github_webhook_pr_event_dropped+from posthog.github.pull_request_events import PullRequestAttribution, capture_pr_event, pr_state_for_actionfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user_integration import UserIntegration@@ -194,10 +192,10 @@ def _capture_task_pr_event(payload: dict, task_run: TaskRun | None, event: GitHucapture_pr_event(payload, attribution, event)-def handle_pull_request_event(payload: dict) -> HttpResponse:- """Process a pre-verified pull_request webhook event.+def handle_pull_request_event(payload: dict) -> None:+ """Process a verified pull_request webhook event.- Called from the shared GitHub webhook dispatcher (unified dispatcher).+ Registered as the ``tasks_pr_backstop`` ingress consumer."""action = payload.get("action")pull_request = payload.get("pull_request", {})@@ -206,7 +204,7 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:if not pr_url:logger.warning("github_pr_webhook_no_pr_url", action=action)- return HttpResponse(status=200)+ returnpr_state = pr_state_for_action(action, pull_request)analytics_event: GitHubWebhookAnalyticsEvent | None = None@@ -227,7 +225,7 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:event_action = action or ""else:logger.debug("github_pr_webhook_ignored_action", action=action, pr_url=pr_url)- return HttpResponse(status=200)+ returnbranch = pull_request.get("head", {}).get("ref")repository_full_name = (payload.get("repository") or {}).get("full_name")@@ -292,19 +290,17 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:if task_run and pr_url in claimed_pr_urls:_cancel_wizard_run_on_close(task_run)- return HttpResponse(status=200)+def handle_pull_request_review_event(payload: dict) -> None:+ """Process a verified pull_request_review webhook event.-def handle_pull_request_review_event(payload: dict) -> HttpResponse:- """Process a pre-verified pull_request_review webhook event.-- Called from the shared GitHub webhook dispatcher (unified dispatcher). Captures a+ Registered as the ``tasks_pr_review`` ingress consumer. Captures a``pr_reviewed`` analytics event for human review submissions (approved,changes_requested, commented), attributed to the reviewer when their GitHublogin resolves to an org member."""if payload.get("action") != "submitted":- return HttpResponse(status=200)+ returnreview = payload.get("review") or {}reviewer = review.get("user") or {}@@ -312,13 +308,13 @@ def handle_pull_request_review_event(payload: dict) -> HttpResponse:pr_url = pull_request.get("html_url")if not pr_url:logger.warning("github_pr_review_webhook_no_pr_url")- return HttpResponse(status=200)+ return# StampHog, ReviewHog, and CI apps review every self-driving PR, so without this# filter the event stream is mostly bots and the human review signal drowns.if (reviewer.get("type") or "").lower() == "bot":logger.debug("github_pr_review_webhook_bot_review_skipped", pr_url=pr_url)- return HttpResponse(status=200)+ returnbranch = (pull_request.get("head") or {}).get("ref")repository_full_name = (payload.get("repository") or {}).get("full_name")@@ -335,7 +331,6 @@ def handle_pull_request_review_event(payload: dict) -> HttpResponse:pr_source="task" if task_run else "external",run_id=str(task_run.id) if task_run else None,)- return HttpResponse(status=200)def _record_run_pr_url(task_run: TaskRun, pr_url: str) -> None:@@ -531,26 +526,24 @@ def _task_run_scope_team_ids(payload: dict) -> list[int]:a delivery for a run they created that way stops matching. Anything with no installationid, or an installation nothing is linked to, falls back to the unscoped lookup."""- external_id = _installation_id(payload)+ external_id = installation_id(payload)if external_id is None:return []- team_ids = set(_installation_team_ids(payload))+ 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)+ 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)+ 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)- )+ team_ids.update(Team.objects.using(SCOPE_DB_ALIAS).filter(organization_id__in=org_ids).values_list("id", flat=True))return sorted(team_ids)diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.pyindex 1000c81728fc..4558aed4f854 100644--- a/products/workflows/backend/facade/api.py+++ b/products/workflows/backend/facade/api.py@@ -1,5 +1,7 @@from uuid import UUID+from posthog.ingress.contracts import WebhookDelivery+from products.workflows.backend.models import HogFlow@@ -12,3 +14,11 @@ def get_workflow_owner_id(*, team_id: int, workflow_id: UUID) -> int | None:return HogFlow.objects.values_list("created_by_id", flat=True).get(team_id=team_id, id=workflow_id)except HogFlow.DoesNotExist:raise WorkflowNotFound() from None+++def accept_github_event(delivery: WebhookDelivery) -> None:+ """The inbound GitHub App webhook enters workflows here, so its consumer needs no internal import."""+ # Deferred to keep the Kafka producer off the facade import path.+ from products.workflows.backend.github_workflow_events import emit_github_event # noqa: PLC0415++ emit_github_event(delivery.event_type, dict(delivery.payload), delivery.delivery_id or "")diff --git a/products/workflows/backend/github_workflow_events.py b/products/workflows/backend/github_workflow_events.pyindex 365a1a39da1a..fd573d066696 100644--- a/products/workflows/backend/github_workflow_events.py+++ b/products/workflows/backend/github_workflow_events.py@@ -4,8 +4,9 @@ The counterpart to ``products.slack_app.backend.slack_workflow_events``, and delthe same way: resolve the PostHog projects behind the GitHub installation, then write the deliveryout as-is. A workflow's trigger config decides what it wants, and the CDP consumer evaluates that.-Registered in the GitHub App webhook fan-out (``posthog.urls.github_webhook``), which verifies the-signature, parses the body, and dedupes redeliveries before any handler runs.+Registered by ``products/workflows/backend/webhook_consumers.py`` as the ``workflows`` consumer+on the GitHub App endpoint, which verifies the signature, parses the body, and dedupes redeliveries+before any consumer runs."""import json@@ -17,6 +18,7 @@ from django.conf import settingsimport structlogfrom posthog.cdp.internal_events import InternalEventEvent, produce_internal_event+from posthog.ingress.dispatch.database import bounded_statement_timeout, is_statement_timeoutfrom posthog.models.instance_setting import get_instance_settingfrom posthog.models.integration import Integration@@ -40,6 +42,11 @@ _MAX_EVENT_PAYLOAD_BYTES = 900_000# open an issue on a public repo, so this is what separates a maintainer from a passer-by.TRUSTED_AUTHOR_ASSOCIATIONS = ("OWNER", "MEMBER", "COLLABORATOR")+# Cap the installation lookup. This runs inside the fan-out's shared per-delivery budget, which+# cannot interrupt a query already in flight, so a slow lookup costs every other consumer on the+# delivery too. Same cap as the GitHub attribution lookup in posthog/github/attribution.py.+_INTEGRATION_LOOKUP_TIMEOUT_MS = 800+def _subject(payload: dict[str, Any]) -> dict[str, Any]:"""The issue, pull request, comment or review the delivery is about, whichever it carries.@@ -185,11 +192,21 @@ def emit_github_event(event_type: str, payload: dict[str, Any], delivery_id: strreturntry:- integrations = list(- Integration.objects.filter(kind="github", integration_id=str(installation_id)).values_list("team_id", "id")- )- except Exception:- logger.exception("github_workflow_event_integration_lookup_failed", installation_id=installation_id)+ with bounded_statement_timeout(_INTEGRATION_LOOKUP_TIMEOUT_MS, models=(Integration,)):+ integrations = list(+ Integration.objects.filter(kind="github", integration_id=str(installation_id)).values_list(+ "team_id", "id"+ )+ )+ except Exception as e:+ if is_statement_timeout(e):+ logger.warning(+ "github_workflow_event_integration_lookup_timed_out",+ installation_id=installation_id,+ delivery_id=delivery_id,+ )+ else:+ logger.exception("github_workflow_event_integration_lookup_failed", installation_id=installation_id)returndistinct_id = str((payload.get("sender") or {}).get("login") or f"installation:{installation_id}")diff --git a/products/workflows/backend/test/test_github_workflow_events.py b/products/workflows/backend/test/test_github_workflow_events.pyindex 682718bbc179..bc3239c1192d 100644--- a/products/workflows/backend/test/test_github_workflow_events.py+++ b/products/workflows/backend/test/test_github_workflow_events.py@@ -1,14 +1,20 @@+import uuid+from datetime import UTC, datetimefrom typing import Anyimport pytestfrom unittest.mock import patch+from django.db import OperationalError++from posthog.ingress.contracts import WebhookDeliveryfrom posthog.models.instance_setting import override_instance_configfrom posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team.team import Team-from products.workflows.backend.github_workflow_events import emit_github_event+from products.workflows.backend.github_workflow_events import _GITHUB_EVENT_NAMESPACE, emit_github_event+from products.workflows.backend.webhook_consumers import WEBHOOK_CONSUMERSINSTALLATION_ID = 4242@@ -272,8 +278,50 @@ def test_properties_carry_what_a_filter_needs(produce, integration) -> None:assert properties["github_event"] == ISSUE_EVENT+def test_an_integration_lookup_timeout_emits_nothing_and_is_reported(produce, integration) -> None:+ # The fan-out's per-delivery budget cannot interrupt a query already in flight, so the+ # statement cap is what keeps a slow lookup from costing the whole delivery.+ with (+ patch("django.conf.settings.GITHUB_WORKFLOW_TRIGGERS_ENABLED", True),+ patch("products.workflows.backend.github_workflow_events.logger") as logger,+ patch.object(+ Integration.objects,+ "filter",+ side_effect=OperationalError("canceling statement due to statement timeout"),+ ),+ ):+ emit_github_event("issues", ISSUE_EVENT, "delivery-1")++ produce.assert_not_called()+ assert logger.warning.call_args.args[0] == "github_workflow_event_integration_lookup_timed_out"+ logger.exception.assert_not_called()++def test_a_kafka_failure_does_not_reach_the_webhook(produce, integration) -> None:produce.side_effect = RuntimeError("kafka is down")with patch("django.conf.settings.GITHUB_WORKFLOW_TRIGGERS_ENABLED", True):emit_github_event("issues", ISSUE_EVENT, "delivery-1")+++def test_the_webhook_consumer_passes_the_whole_delivery_through_the_facade(produce, integration) -> None:+ # The facade unpacks the delivery into emit's three arguments. The delivery id only shows up+ # in the event uuid, so dropping it emits an event that looks correct and dedupes wrong.+ (consumer,) = WEBHOOK_CONSUMERS+ delivery = WebhookDelivery(+ provider="github",+ app="posthog",+ delivery_id="delivery-1",+ event_type="issues",+ payload=ISSUE_EVENT,+ received_at=datetime(2026, 1, 1, tzinfo=UTC),+ context={},+ )++ with patch("django.conf.settings.GITHUB_WORKFLOW_TRIGGERS_ENABLED", True):+ consumer.handler(delivery)++ event = produce.call_args.args[1]+ assert event.properties["event_type"] == "issues"+ assert event.properties["github_event"] == ISSUE_EVENT+ assert event.uuid == str(uuid.uuid5(_GITHUB_EVENT_NAMESPACE, f"{integration.team_id}:delivery-1"))diff --git a/products/workflows/backend/webhook_consumers.py b/products/workflows/backend/webhook_consumers.pynew file mode 100644index 000000000000..2c9be76e4624--- /dev/null+++ b/products/workflows/backend/webhook_consumers.py@@ -0,0 +1,24 @@+"""Workflows' consumer on the customer-facing GitHub App endpoint.++The registry imports this module on the first delivery, so it stays cheap: the handler defers+its own product import.+"""++from posthog.ingress.contracts import WebhookConsumer, WebhookDelivery+++def _run_workflows(delivery: WebhookDelivery) -> None:+ from products.workflows.backend.facade.api import accept_github_event # noqa: PLC0415++ accept_github_event(delivery)+++WEBHOOK_CONSUMERS = (+ WebhookConsumer(+ name="workflows",+ provider="github",+ app="posthog",+ event_types=frozenset({"issues", "issue_comment", "pull_request", "pull_request_review", "push"}),+ handler=_run_workflows,+ ),+)diff --git a/pyproject.toml b/pyproject.tomlindex f5335f2d6f2a..ea3faca0244b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -800,9 +800,7 @@ ignore_imports = [# webhook_consumers.py is the one module core reads (through posthog.ingress.dispatch.loading)# to register a product's inbound webhook consumers. Restricting what it may import gives the# chain core -> webhook_consumers -> facade as two import edges, so a handler cannot reach-# product internals. Unlike the two contracts above it, this one carries no grandfathered list:-# stamphog's is the only such module in the tree, and the ones arriving with the remaining-# endpoint migrations already import only their own facade.+# product internals.[[tool.importlinter.contracts]]name = "webhook consumers must only import facade"type = "forbidden"@@ -834,7 +832,6 @@ ignore_imports = [# TODO: existing violations — move the presentation-shaped code out of the facade, or the# facade-shaped code out of presentation, and drop the line"products.managed_warehouse.backend.facade.api -> products.managed_warehouse.backend.presentation.views",- "products.stamphog.backend.facade.webhooks -> products.stamphog.backend.presentation.webhooks","products.tasks.backend.facade.api -> products.tasks.backend.presentation.serializers","products.billing_alerts.backend.facade.api -> rest_framework","products.dashboards.backend.facade.api -> rest_framework",