: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(github): share webhook PR attribution across products (#99479)
Fernando Gomes6d8119ea87c8
diff --git a/docs/internal/github-webhooks.md b/docs/internal/github-webhooks.mdnew file mode 100644index 000000000000..b9105062ed78--- /dev/null+++ b/docs/internal/github-webhooks.md@@ -0,0 +1,62 @@+# 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/posthog/api/github_webhooks/__init__.py b/posthog/api/github_webhooks/__init__.pynew file mode 100644index 000000000000..0a5a77631d76--- /dev/null+++ b/posthog/api/github_webhooks/__init__.py@@ -0,0 +1 @@+"""GitHub App webhook transport and shared pull request analytics."""diff --git a/posthog/api/github_webhooks/attribution.py b/posthog/api/github_webhooks/attribution.pynew file mode 100644index 000000000000..71c24678999a--- /dev/null+++ b/posthog/api/github_webhooks/attribution.py@@ -0,0 +1,165 @@+from collections.abc import Iterator+from contextlib import ExitStack, contextmanager++from django.conf import settings+from django.db import OperationalError, connections, router, transaction+from django.db.backends.base.base import BaseDatabaseWrapper++import structlog+from social_django.models import UserSocialAuth++from posthog.api.github_webhooks.metrics import GitHubWebhookAttributionOutcome, observe_github_webhook_attribution+from posthog.models.integration import Integration+from posthog.models.organization import OrganizationMembership+from posthog.models.team.team import Team+from posthog.models.user import User+from posthog.models.user_integration import UserIntegration++from products.signals.backend.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+# pull_request delivery one short window and never retries it, and the merged branch runs+# functional side effects (merge bookkeeping, signal-report resolution, wizard wind-down)+# right after capture. A slow lookup on the request path can therefore cost the whole+# delivery, not just the analytics event. Bounding it degrades to no attribution instead.+_ATTRIBUTION_STATEMENT_TIMEOUT_MS = 800++# Models the org-member resolver reads. ReplicaRouter only sends a model to the replica when+# that model is named in READ_REPLICA_OPT_IN, so the set of aliases the lookup can touch is+# knowable up front.+_ATTRIBUTION_MODELS = (Team, User, OrganizationMembership, UserSocialAuth, UserIntegration, Integration)+++def _attribution_db_aliases() -> list[str]:+ """The aliases the org-member lookup actually reads from, deduped, in model order.++ Bounding an alias means opening it, and opening is itself unbounded -- ``postgres_config``+ sets no ``connect_timeout`` on these aliases. So take the set from the router rather than+ assuming: reaching for an alias the resolver never uses could stall the webhook on+ connection setup before the cap is installed, which is the failure this exists to prevent.+ That cuts both ways -- a fully replica-opted deployment must not be made to wait on the+ primary either.+ """+ aliases: list[str] = []+ for model in _ATTRIBUTION_MODELS:+ alias = router.db_for_read(model) or "default"+ if alias not in aliases and alias in settings.DATABASES:+ aliases.append(alias)+ return aliases+++def _read_statement_timeout(connection: BaseDatabaseWrapper) -> str | None:+ with connection.cursor() as cursor:+ cursor.execute("SHOW statement_timeout")+ row = cursor.fetchone()+ return row[0] if row else None+++def _apply_statement_timeout(connection: BaseDatabaseWrapper, value: str) -> None:+ # set_config(..., is_local=True) is SET LOCAL, but takes the value as a bind parameter,+ # so a restored value ("30s", "0", ...) does not have to be quoted by hand.+ with connection.cursor() as cursor:+ cursor.execute("SELECT set_config('statement_timeout', %s, true)", [value])+++@contextmanager+def _statement_timeout(connection: BaseDatabaseWrapper, timeout_ms: int, *, restore: bool) -> Iterator[None]:+ """Cap statements on one connection, optionally putting the previous value back."""+ previous = _read_statement_timeout(connection) if restore else None+ _apply_statement_timeout(connection, f"{timeout_ms}ms")++ yield++ # Only reached when the block succeeded. If it raised, the enclosing atomic() rolls the+ # (sub)transaction back and PostgreSQL undoes SET LOCAL with it, so there is nothing to+ # restore -- and a statement on an aborted transaction would error anyway.+ if previous:+ _apply_statement_timeout(connection, previous)+++@contextmanager+def _bounded_attribution_lookup() -> Iterator[None]:+ """Run a block under a per-statement timeout on each configured DB the lookup may use.++ A read routed to an alias joins that alias's open transaction, so ``SET LOCAL+ statement_timeout`` there caps the query regardless of read-replica routing.+ """+ with ExitStack() as stack:+ for alias in _attribution_db_aliases():+ connection = connections[alias]+ # SET LOCAL dies with the transaction it was set in, so the cap only needs+ # restoring when we are joining a transaction somebody else owns -- a future+ # caller wrapping this in its own atomic block, or ATOMIC_REQUESTS (which+ # PostHog does not enable today). Otherwise the commit below ends it for us.+ restore = connection.in_atomic_block+ stack.enter_context(transaction.atomic(using=alias))+ stack.enter_context(_statement_timeout(connection, _ATTRIBUTION_STATEMENT_TIMEOUT_MS, restore=restore))+ yield+++# PostgreSQL raises query_canceled when statement_timeout fires. Django wraps the driver+# error in OperationalError, so the SQLSTATE lives on the cause -- psycopg3 spells it+# `sqlstate`, psycopg2 `pgcode`. The message check is the fallback for anything that loses+# the cause on the way up.+_QUERY_CANCELED_SQLSTATE = "57014"+++def _is_statement_timeout(error: Exception) -> bool:+ if not isinstance(error, OperationalError):+ return False+ cause = error.__cause__+ if getattr(cause, "sqlstate", None) == _QUERY_CANCELED_SQLSTATE:+ return True+ if getattr(cause, "pgcode", None) == _QUERY_CANCELED_SQLSTATE:+ return True+ return "statement timeout" in str(error).lower()+++def _resolve_github_login_distinct_id(login: str | None, team_id: int) -> str | None:+ """Distinct id of the org member matching a GitHub login, or None when unresolvable.++ Runs under a per-statement timeout so a slow member lookup cannot hold the webhook+ open past GitHub's delivery timeout (see ``_ATTRIBUTION_STATEMENT_TIMEOUT_MS``).+ """+ if not login:+ return None+ try:+ with _bounded_attribution_lookup():+ resolved = resolve_github_login_distinct_id(str(login), team_id)+ except Exception as e:+ # timeout is meant to be the leading indicator for the cap we just installed, so it+ # has to mean "statement cancelled", not "any OperationalError" -- connection resets+ # and other DB incidents raise the same class and would drown the signal.+ outcome: GitHubWebhookAttributionOutcome = "timeout" if _is_statement_timeout(e) else "error"+ observe_github_webhook_attribution(outcome=outcome)+ logger.warning(+ "github_webhook_login_resolution_failed", login=login, team_id=team_id, outcome=outcome, error=str(e)+ )+ return None+ if resolved is None:+ observe_github_webhook_attribution(outcome="unresolved")+ return None+ observe_github_webhook_attribution(outcome="resolved")+ return resolved+++def _merged_by_attribution(payload: dict, team_id: int) -> tuple[dict, str | None]:+ """Identity of the GitHub user who merged the PR, resolved to a PostHog user when possible.++ Merging is the one unambiguous personal act in the loop, so when the merger's GitHub+ login 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.+ """+ merged_by = (payload.get("pull_request") or {}).get("merged_by") or {}+ login = merged_by.get("login")+ if not login:+ return {}, None+ properties: dict = {"pr_merged_by_login": login, "pr_merged_by_id": merged_by.get("id")}+ distinct_id = _resolve_github_login_distinct_id(login, team_id)+ if distinct_id is not None:+ properties["pr_merged_by_distinct_id"] = distinct_id+ return properties, distinct_iddiff --git a/posthog/api/github_webhooks/contracts.py b/posthog/api/github_webhooks/contracts.pynew file mode 100644index 000000000000..86d63b48ad6d--- /dev/null+++ b/posthog/api/github_webhooks/contracts.py@@ -0,0 +1,17 @@+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.pynew file mode 100644index 000000000000..e9d832737cac--- /dev/null+++ b/posthog/api/github_webhooks/dispatch.py@@ -0,0 +1,87 @@+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.pynew file mode 100644index 000000000000..3de824bcaf51--- /dev/null+++ b/posthog/api/github_webhooks/handlers.py@@ -0,0 +1,112 @@+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/integrations.py b/posthog/api/github_webhooks/integrations.pynew file mode 100644index 000000000000..eeffddf25572--- /dev/null+++ b/posthog/api/github_webhooks/integrations.py@@ -0,0 +1,41 @@+from posthog.models.integration import Integration+from posthog.models.team.team import Team+++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)+++# The run lookup these feed reads TaskRun off the writer, and they run on the request path+# outside the bounded attribution block. Pin them to the writer too: a replica-opted+# Integration or Team would otherwise let a slow replica stall a delivery whose own lookup+# never needed it, and replica lag could hide a freshly connected installation.+_SCOPE_DB_ALIAS = "default"+++def _installation_team_ids(payload: dict) -> list[int]:+ """Teams whose GitHub Integration matches the delivery's installation, in deterministic order.++ Empty when the payload carries no installation id or no Integration matches it — the+ lookups that take this fall back to their unscoped behaviour in that case.+ """+ external_id = _installation_id(payload)+ if external_id is None:+ return []++ # One installation can map to multiple teams; order_by makes attribution deterministic.+ return list(+ Integration.objects.using(_SCOPE_DB_ALIAS)+ .filter(kind="github", integration_id=external_id)+ .order_by("team_id")+ .values_list("team_id", flat=True)+ )+++def _resolve_external_team(payload: dict) -> Team | None:+ team_ids = _installation_team_ids(payload)+ if not team_ids:+ return None+ return Team.objects.filter(pk=team_ids[0]).first()diff --git a/posthog/api/github_webhooks/metrics.py b/posthog/api/github_webhooks/metrics.pynew file mode 100644index 000000000000..5079fe092ff2--- /dev/null+++ b/posthog/api/github_webhooks/metrics.py@@ -0,0 +1,35 @@+from typing import Literal++from prometheus_client import Counter++# analytics_event: pr_created | pr_merged | pr_closed | pr_reviewed (bounded, code-defined).+# reason: unresolved_installation (no Integration matched the delivery's installation id) or+# capture_exception (posthoganalytics.capture raised). Both paths were silent before,+# so a webhook-side event loss only showed up as a capture-rate dip in analytics.+GITHUB_WEBHOOK_PR_EVENT_DROPPED_TOTAL = Counter(+ "posthog_tasks_github_webhook_pr_event_dropped_total",+ "GitHub PR webhook events that never reached PostHog capture, labeled by event and drop reason",+ labelnames=["analytics_event", "reason"],+)++# outcome: resolved | unresolved | timeout | error. timeout means the bounded org-member+# lookup hit statement_timeout and was skipped so the delivery survives without attribution.+GITHUB_WEBHOOK_ATTRIBUTION_TOTAL = Counter(+ "posthog_tasks_github_webhook_attribution_total",+ "Outcome of the org-member lookup that attributes a GitHub login on the pr_merged/pr_reviewed webhook path",+ labelnames=["outcome"],+)++GitHubWebhookAnalyticsEvent = Literal["pr_created", "pr_merged", "pr_closed", "pr_reviewed"]+GitHubWebhookDropReason = Literal["unresolved_installation", "capture_exception"]+GitHubWebhookAttributionOutcome = Literal["resolved", "unresolved", "timeout", "error"]+++def observe_github_webhook_pr_event_dropped(+ *, analytics_event: GitHubWebhookAnalyticsEvent, reason: GitHubWebhookDropReason+) -> None:+ GITHUB_WEBHOOK_PR_EVENT_DROPPED_TOTAL.labels(analytics_event=analytics_event, reason=reason).inc()+++def observe_github_webhook_attribution(*, outcome: GitHubWebhookAttributionOutcome) -> None:+ GITHUB_WEBHOOK_ATTRIBUTION_TOTAL.labels(outcome=outcome).inc()diff --git a/posthog/api/github_webhooks/pull_requests.py b/posthog/api/github_webhooks/pull_requests.pynew file mode 100644index 000000000000..64c51fd05386--- /dev/null+++ b/posthog/api/github_webhooks/pull_requests.py@@ -0,0 +1,162 @@+"""Canonical PR analytics for product-owned and external pull requests."""++import uuid++import structlog+import 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.event_usage import groups++logger = structlog.get_logger(__name__)+++# Nulled on external PRs so their schema matches task-originated PR events.+_TASK_ATTRIBUTION_KEYS = ("task_id", "run_id", "origin_product", "signal_report_id", "environment", "mode", "title")++# What a PR says, rather than how big it is. Attributed PRs can opt into these values; an+# external PR's own words are customer business context, so it gets the keys as nulls for+# schema parity, the same way _TASK_ATTRIBUTION_KEYS works.+_PR_CONTENT_KEYS = (+ "pr_title",+ "pr_body",+ "pr_body_truncated",+ "pr_labels",+ "pr_requested_reviewers",+ "pr_is_draft",+)++# A PR body is the biggest string on the delivery, and an agent-authored one can run long.+# Cap it so one verbose body cannot push the event past the capture size limit.+_PR_BODY_MAX_CHARS = 10_000+++def _account_type(payload: dict) -> str | None:+ """Whether the webhook's repo is owned by a GitHub org or a personal account.++ ``repository.owner.type`` is "Organization" or "User"; the top-level+ ``organization`` object is present only for org-owned repos and backs it up+ when the owner block is missing. Returns None when neither signal is present.+ """+ owner_type = ((payload.get("repository") or {}).get("owner") or {}).get("type")+ if owner_type == "Organization":+ return "organization"+ if owner_type == "User":+ return "personal"+ if payload.get("organization"):+ return "organization"+ return None+++def _pr_payload_properties(payload: dict) -> dict:+ pull_request = payload.get("pull_request") or {}+ return {+ "pr_url": pull_request.get("html_url"),+ "pr_number": pull_request.get("number"),+ "pr_author": (pull_request.get("user") or {}).get("login"),+ "pr_base_ref": (pull_request.get("base") or {}).get("ref"),+ "pr_head_ref": (pull_request.get("head") or {}).get("ref"),+ "pr_additions": pull_request.get("additions"),+ "pr_deletions": pull_request.get("deletions"),+ "pr_changed_files": pull_request.get("changed_files"),+ "pr_commits": pull_request.get("commits"),+ "account_type": _account_type(payload),+ "repo_owner_type": ((payload.get("repository") or {}).get("owner") or {}).get("type"),+ }+++def _pr_content_properties(payload: dict) -> dict:+ """What a task-authored PR says: its title, body, labels, requested reviewers, draft state."""+ pull_request = payload.get("pull_request") or {}+ body = pull_request.get("body") or ""+ return {+ "pr_title": pull_request.get("title"),+ "pr_body": body[:_PR_BODY_MAX_CHARS],+ "pr_body_truncated": len(body) > _PR_BODY_MAX_CHARS,+ "pr_labels": [label.get("name") for label in (pull_request.get("labels") or []) if label.get("name")],+ "pr_requested_reviewers": [+ reviewer.get("login")+ for reviewer in (pull_request.get("requested_reviewers") or [])+ if reviewer.get("login")+ ],+ "pr_is_draft": pull_request.get("draft"),+ }+++def pr_state_for_action(action: str | None, pull_request: dict) -> str | None:+ if action in ("opened", "reopened"):+ return "draft" if pull_request.get("draft") else "open"+ if action == "ready_for_review":+ return "open"+ if action == "converted_to_draft":+ return "draft"+ if action == "closed":+ return "merged" if pull_request.get("merged") else "closed"+ return None+++def capture_pr_event(+ payload: dict,+ attribution: PullRequestAttribution | None,+ event: GitHubWebhookAnalyticsEvent,+) -> None:+ """Emit a canonical PR event with product attribution, or the external-PR fallback."""+ try:+ if attribution is None:+ team = _resolve_external_team(payload)+ if team is None:+ observe_github_webhook_pr_event_dropped(analytics_event=event, reason="unresolved_installation")+ return+ attribution = PullRequestAttribution(+ source="external",+ team_id=team.id,+ distinct_id=str(team.uuid),+ groups=groups(team=team),+ properties={+ **dict.fromkeys(_TASK_ATTRIBUTION_KEYS, None),+ "repository": ((payload.get("repository") or {}).get("full_name") or "").strip().lower() or None,+ },+ )++ properties = {**attribution.properties, **_pr_payload_properties(payload)}+ distinct_id = attribution.distinct_id+ if event == "pr_merged":+ merger_properties, merger_distinct_id = _merged_by_attribution(payload, attribution.team_id)+ properties.update(merger_properties)+ distinct_id = merger_distinct_id or distinct_id+ elif event == "pr_reviewed":+ review = payload.get("review") or {}+ reviewer = review.get("user") or {}+ reviewer_distinct_id = _resolve_github_login_distinct_id(reviewer.get("login"), attribution.team_id)+ properties.update(+ {+ "pr_review_state": review.get("state"),+ "pr_reviewed_by_login": reviewer.get("login"),+ "pr_reviewed_by_id": reviewer.get("id"),+ }+ )+ if reviewer_distinct_id is not None:+ properties["pr_reviewed_by_distinct_id"] = reviewer_distinct_id+ distinct_id = reviewer_distinct_id++ properties.update(+ _pr_content_properties(payload) if attribution.include_content else dict.fromkeys(_PR_CONTENT_KEYS, None)+ )+ properties.update({"team_id": attribution.team_id, "pr_source": attribution.source})+ pr_url = (payload.get("pull_request") or {}).get("html_url")+ review_suffix = f":{(payload.get('review') or {}).get('id')}" if event == "pr_reviewed" else ""+ event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:{event}{review_suffix}"))+ posthoganalytics.capture(+ distinct_id=distinct_id,+ event=event,+ properties=properties,+ groups=dict(attribution.groups),+ uuid=event_uuid,+ send_feature_flags=attribution.send_feature_flags,+ )+ except Exception as error:+ observe_github_webhook_pr_event_dropped(analytics_event=event, reason="capture_exception")+ logger.warning("github_pr_webhook_capture_failed", analytics_event=event, error=str(error))diff --git a/posthog/api/github_webhooks/signature.py b/posthog/api/github_webhooks/signature.pynew file mode 100644index 000000000000..de59f579c8d7--- /dev/null+++ b/posthog/api/github_webhooks/signature.py@@ -0,0 +1,24 @@+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.pynew file mode 100644index 000000000000..3ee8a3a0e300--- /dev/null+++ b/posthog/api/github_webhooks/views.py@@ -0,0 +1,38 @@+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 2bd193961bc3..8e6ebc7e84b9 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("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")@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@@ -154,7 +154,7 @@ class TestGitHubInstallationWebhook(TestCase):# Inbound side must never call out to GitHub (loop prevention).mock_client_request.assert_not_called()- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_deleted_with_no_matching_rows_is_idempotent(self, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -163,7 +163,7 @@ class TestGitHubInstallationWebhook(TestCase):self.assertEqual(response.status_code, 200)@parameterized.expand([("suspend",), ("unsuspend",)])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_reversible_action_does_not_delete_rows(self, action, mock_get_secret):mock_get_secret.return_value = self.webhook_secretself._team_integration("12345")@@ -173,7 +173,7 @@ class TestGitHubInstallationWebhook(TestCase):self.assertEqual(response.status_code, 200)self.assertTrue(Integration.objects.filter(kind="github", integration_id="12345").exists())- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_missing_installation_id_returns_200(self, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -181,7 +181,7 @@ class TestGitHubInstallationWebhook(TestCase):self.assertEqual(response.status_code, 200)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")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")@@ -220,7 +220,7 @@ class TestGitHubInstallationWebhook(TestCase):self.assertEqual(someone_else.status, GitHubInstallRequest.Status.PENDING)self.assertIsNone(someone_else.installation_id)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")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@@ -237,7 +237,7 @@ class TestGitHubInstallationWebhook(TestCase):pending.refresh_from_db()self.assertEqual(pending.status, GitHubInstallRequest.Status.PENDING)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")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")@@ -270,7 +270,7 @@ class TestGitHubInstallationWebhook(TestCase):self.assertEqual(untouched.config["repository_selection"], "selected")self.assertIsNotNone(untouched.repository_cache_updated_at)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")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/api/test/test_github_webhooks.py b/posthog/api/test/test_github_webhooks.pynew file mode 100644index 000000000000..0b1cb1a1e807--- /dev/null+++ b/posthog/api/test/test_github_webhooks.py@@ -0,0 +1,115 @@+import uuid++from unittest.mock import Mock, patch++from django.core.cache import cache+from django.http import HttpResponse+from django.test import RequestFactory, SimpleTestCase, override_settings++from 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+++class TestProductPullRequestAttribution(SimpleTestCase):+ @parameterized.expand(+ [+ ("created", "opened", False, "pr_created"),+ ("closed", "closed", False, "pr_closed"),+ ("merged", "closed", True, "pr_merged"),+ ("reviewed", "submitted", False, "pr_reviewed"),+ ]+ )+ def test_non_task_owner_uses_canonical_capture(+ self, _name: str, action: str, merged: bool, event: GitHubWebhookAnalyticsEvent+ ) -> None:+ pr_url = "https://github.com/example/app/pull/7"+ payload = {+ "action": action,+ "installation": {"id": 42},+ "repository": {"full_name": "example/app"},+ "pull_request": {+ "html_url": pr_url,+ "number": 7,+ "head": {"ref": "setup", "repo": {"full_name": "example/app"}},+ "merged": merged,+ "merged_by": {"login": "reviewer"},+ "body": "private PR content",+ },+ "review": {"id": 90, "state": "approved", "user": {"login": "reviewer", "type": "User"}},+ }+ attribution = PullRequestAttribution(+ source="wizard",+ team_id=12,+ distinct_id="creator",+ groups={"project": "12"},+ properties={"wizard_run_id": "example-run", "team_id": 999, "pr_source": "wrong", "pr_url": "wrong"},+ )++ with (+ patch(+ "posthog.api.github_webhooks.attribution.resolve_github_login_distinct_id", return_value="reviewer-id"+ ),+ patch("posthog.api.github_webhooks.attribution._bounded_attribution_lookup"),+ patch(+ "posthog.api.github_webhooks.pull_requests._resolve_github_login_distinct_id",+ return_value="reviewer-id",+ ),+ patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture") as capture,+ ):+ for _ in range(2):+ capture_pr_event(payload, attribution, event)+ self.assertEqual(capture.call_count, 2)+ first, second = capture.call_args_list+ self.assertEqual(first.kwargs, second.kwargs)+ kwargs = first.kwargs+ self.assertEqual(kwargs["event"], event)+ self.assertEqual(+ kwargs["distinct_id"], "reviewer-id" if event in ("pr_merged", "pr_reviewed") else "creator"+ )+ self.assertEqual(kwargs["groups"], {"project": "12"})+ properties = kwargs["properties"]+ self.assertEqual(properties["wizard_run_id"], "example-run")+ self.assertEqual(properties["team_id"], 12)+ self.assertEqual(properties["pr_source"], "wizard")+ self.assertEqual(properties["pr_url"], pr_url)+ self.assertNotIn("task_id", properties)+ self.assertIsNone(properties["pr_body"])+ suffix = ":90" if event == "pr_reviewed" else ""+ self.assertEqual(+ 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/urls.py b/posthog/urls.pyindex e02b68882b03..5c612e6cc642 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -1,9 +1,7 @@-from collections.abc import Callablefrom typing import Any, castfrom urllib.parse import urlencode, urlparsefrom django.conf import settings-from django.core.cache import cachefrom django.http import HttpRequest, HttpResponse, HttpResponseRedirect, HttpResponseServerErrorfrom django.template import loaderfrom django.urls import include, path, re_path@@ -33,6 +31,7 @@ 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.oauth.connected_apps import ConnectedAppsViewSetfrom posthog.api.oauth.hogli_metadata import HOGLI_METADATA_PATH, HogliClientMetadataViewfrom posthog.api.oauth.raycast_metadata import RAYCAST_METADATA_PATH, RaycastClientMetadataView@@ -42,7 +41,6 @@ from posthog.api.two_factor_qrcode import CacheAwareQRGeneratorViewfrom posthog.api.utils import hostname_in_allowed_url_listfrom posthog.api.web_experiment import web_experimentsfrom posthog.constants import PERMITTED_FORUM_DOMAINS-from posthog.exceptions_capture import capture_exceptionfrom posthog.models import Userfrom posthog.models.instance_setting import get_instance_settingfrom posthog.oauth2_urls import urlpatterns as oauth2_urls@@ -122,202 +120,6 @@ else:extend_api_router()-GithubWebhookHandler = Callable[[HttpRequest, str, dict[str, Any], str], HttpResponse | None]---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-- 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-- 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-- 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-- 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-- 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-- 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-- 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),- ],-}--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- )---@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.- """- import json-- from products.tasks.backend.facade.webhooks import get_github_webhook_secret, verify_github_signature-- 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", "")- handlers = GITHUB_WEBHOOK_HANDLERS.get(event_type, [])-- 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)--@requires_csrf_tokendef handler500(request):"""diff --git a/products/signals/backend/facade/github.py b/products/signals/backend/facade/github.pynew file mode 100644index 000000000000..284e2c273631--- /dev/null+++ b/products/signals/backend/facade/github.py@@ -0,0 +1,37 @@+"""Signals' GitHub identity and report-assignment integration."""++import structlog++from posthog.api.github_webhooks.integrations import _installation_team_ids++from products.signals.backend.report_assignments import update_assignments_for_pull_request+from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users++logger = structlog.get_logger(__name__)+++def resolve_github_login_distinct_id(login: str, team_id: int) -> str | None:+ user = resolve_org_github_login_to_users(team_id, [login]).get(login.strip().lower())+ return str(user.distinct_id) if user is not None else 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)+ if pr_state is None or not repository or not team_ids:+ return+ pull_request = payload.get("pull_request") or {}+ try:+ number = pull_request.get("number")+ if number is None:+ raise ValueError("Missing pull request number")+ update_assignments_for_pull_request(+ team_ids=team_ids,+ repository=repository,+ pr_number=int(number),+ pr_state=pr_state,+ )+ except (TypeError, ValueError):+ logger.warning("github_pr_webhook_signal_assignment_missing_number", pr_url=pull_request.get("html_url"))+ except Exception:+ logger.exception("github_pr_webhook_signal_assignment_update_failed", pr_url=pull_request.get("html_url"))diff --git a/products/tasks/backend/facade/webhooks.py b/products/tasks/backend/facade/webhooks.pyindex c6ebc1ec9bac..ad59b999ec09 100644--- a/products/tasks/backend/facade/webhooks.py+++ b/products/tasks/backend/facade/webhooks.py@@ -1,22 +1,6 @@-"""-Facade re-exports for the GitHub webhook handlers.--Core's unified GitHub webhook view dispatches to these: it verifies the signature on every-POST, routes pull-request events to the tasks handler, and fans events out to loop triggers.-"""+"""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 (- get_github_webhook_secret,- handle_pull_request_event,- handle_pull_request_review_event,- verify_github_signature,-)+from products.tasks.backend.webhooks import handle_pull_request_event, handle_pull_request_review_event-__all__ = [- "get_github_webhook_secret",- "handle_github_event_for_loops",- "handle_pull_request_event",- "handle_pull_request_review_event",- "verify_github_signature",-]+__all__ = ["handle_github_event_for_loops", "handle_pull_request_event", "handle_pull_request_review_event"]diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.pyindex 704e7997ade5..571920bf06d2 100644--- a/products/tasks/backend/metrics.py+++ b/products/tasks/backend/metrics.py@@ -429,24 +429,6 @@ def observe_compute_quota_check(outcome: ComputeQuotaOutcome) -> None:COMPUTE_QUOTA_CHECK_TOTAL.labels(outcome=outcome).inc()-# analytics_event: pr_created | pr_merged | pr_closed | pr_reviewed (bounded, code-defined).-# reason: unresolved_installation (no Integration matched the delivery's installation id) or-# capture_exception (posthoganalytics.capture raised). Both paths were silent before,-# so a webhook-side event loss only showed up as a capture-rate dip in analytics.-GITHUB_WEBHOOK_PR_EVENT_DROPPED_TOTAL = Counter(- "posthog_tasks_github_webhook_pr_event_dropped_total",- "GitHub PR webhook events that never reached PostHog capture, labeled by event and drop reason",- labelnames=["analytics_event", "reason"],-)--# outcome: resolved | unresolved | timeout | error. timeout means the bounded org-member-# lookup hit statement_timeout and was skipped so the delivery survives without attribution.-GITHUB_WEBHOOK_ATTRIBUTION_TOTAL = Counter(- "posthog_tasks_github_webhook_attribution_total",- "Outcome of the org-member lookup that attributes a GitHub login on the pr_merged/pr_reviewed webhook path",- labelnames=["outcome"],-)-# scoped: "true" when the delivery's installation resolved to at least one team, so the# TaskRun lookup could ride the team_id index. "false" means it fell back to the legacy# unscoped lookup, which walks posthog_task_run once per leg — the thing we want to watch@@ -457,20 +439,6 @@ GITHUB_WEBHOOK_TASK_RUN_LOOKUP_TOTAL = Counter(labelnames=["scoped"],)-GitHubWebhookAnalyticsEvent = Literal["pr_created", "pr_merged", "pr_closed", "pr_reviewed"]-GitHubWebhookDropReason = Literal["unresolved_installation", "capture_exception"]-GitHubWebhookAttributionOutcome = Literal["resolved", "unresolved", "timeout", "error"]---def observe_github_webhook_pr_event_dropped(- *, analytics_event: GitHubWebhookAnalyticsEvent, reason: GitHubWebhookDropReason-) -> None:- GITHUB_WEBHOOK_PR_EVENT_DROPPED_TOTAL.labels(analytics_event=analytics_event, reason=reason).inc()---def observe_github_webhook_attribution(*, outcome: GitHubWebhookAttributionOutcome) -> None:- GITHUB_WEBHOOK_ATTRIBUTION_TOTAL.labels(outcome=outcome).inc()-def observe_github_webhook_task_run_lookup(*, scoped: bool) -> None:GITHUB_WEBHOOK_TASK_RUN_LOOKUP_TOTAL.labels(scoped="true" if scoped else "false").inc()diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 6f4f198e330f..dbfdd0dd0e44 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2803,6 +2803,30 @@ class TaskRun(models.Model):props["benjamin_version"] = benjamin_versionreturn props+ def analytics_properties(self) -> dict:+ """Run context shared by run events and GitHub PR attribution."""+ return {+ "task_id": str(self.task_id),+ "run_id": str(self.id),+ "team_id": self.team_id,+ "repository": self.task.repository,+ "repositories": (self.state or {}).get("repositories")+ or self.task.repositories+ or ([self.task.repository] if self.task.repository else []),+ "origin_product": self.task.origin_product,+ "title": self.task.title,+ "signal_report_id": str(self.task.signal_report_id) if self.task.signal_report_id else None,+ "loop_id": (self.state or {}).get("loop_id"),+ "loop_trigger_id": (self.state or {}).get("loop_trigger_id"),+ "environment": self.environment,+ # The bare `environment` property gets clobbered by the analytics+ # client's deployment-region super-property, so ship the run's+ # local/cloud value under an unclobbered name too.+ "run_environment": self.environment,+ "mode": self.mode,+ **self._analytics_usage_properties(),+ }+def capture_event(self,event: str,@@ -2823,27 +2847,7 @@ class TaskRun(models.Model):if self.task.created_by_id and self.task.created_byelse str(self.team.uuid))- all_properties: dict = {- "task_id": str(self.task_id),- "run_id": str(self.id),- "team_id": self.team_id,- "repository": self.task.repository,- "repositories": (self.state or {}).get("repositories")- or self.task.repositories- or ([self.task.repository] if self.task.repository else []),- "origin_product": self.task.origin_product,- "title": self.task.title,- "signal_report_id": str(self.task.signal_report_id) if self.task.signal_report_id else None,- "loop_id": (self.state or {}).get("loop_id"),- "loop_trigger_id": (self.state or {}).get("loop_trigger_id"),- "environment": self.environment,- # The bare `environment` property gets clobbered by the analytics- # client's deployment-region super-property, so ship the run's- # local/cloud value under an unclobbered name too.- "run_environment": self.environment,- "mode": self.mode,- **self._analytics_usage_properties(),- }+ all_properties = self.analytics_properties()if properties:all_properties.update(properties)capture_kwargs: dict = {diff --git a/products/tasks/backend/tests/test_webhooks.py b/products/tasks/backend/tests/test_webhooks.pyindex 4f5bdcebb78b..877ca95d483d 100644--- a/products/tasks/backend/tests/test_webhooks.py+++ b/products/tasks/backend/tests/test_webhooks.py@@ -15,6 +15,9 @@ from prometheus_client import REGISTRYfrom rest_framework.test import APIClientfrom social_django.models import UserSocialAuth+from posthog.api.github_webhooks.attribution import _attribution_db_aliases, _bounded_attribution_lookup+from posthog.api.github_webhooks.integrations import _installation_team_ids+from posthog.api.github_webhooks.pull_requests import _PR_BODY_MAX_CHARS, _account_typefrom posthog.models.integration import Integrationfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team.team import Team@@ -25,15 +28,7 @@ from products.signals.backend.implementation_pr import fetch_implementation_pr_sfrom products.signals.backend.models import SignalActorKind, SignalReport, SignalReportAssignment, SignalReportTaskfrom products.tasks.backend.facade.api import find_signal_implementation_runfrom products.tasks.backend.models import Task, TaskRun, TaskThreadMessage-from products.tasks.backend.webhooks import (- _PR_BODY_MAX_CHARS,- _account_type,- _attribution_db_aliases,- _bounded_attribution_lookup,- _installation_team_ids,- _task_run_scope_team_ids,- find_task_run,-)+from products.tasks.backend.webhooks import _task_run_scope_team_ids, find_task_runclass TestAccountType(TestCase):@@ -111,8 +106,8 @@ class TestGitHubPRWebhook(TestCase):headers={"x-hub-signature-256": signature, "x-github-event": event_type},)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_merged_webhook(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -146,8 +141,8 @@ class TestGitHubPRWebhook(TestCase):("unresolvable_login", "stranger", None, "user-123"),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_merged_attributes_to_merger(self, _name, merged_by_login, expected_property, expected_distinct_id, mock_capture, mock_get_secret):@@ -174,9 +169,9 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(call_kwargs["properties"]["pr_merged_by_id"], 583231)self.assertEqual(call_kwargs["properties"].get("pr_merged_by_distinct_id"), expected_property)- @patch("products.tasks.backend.webhooks.resolve_org_github_login_to_users", side_effect=RuntimeError("boom"))- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @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")def test_pr_merged_by_resolution_failure_keeps_webhook_successful(self, mock_capture, mock_get_secret, _mock_resolve):@@ -200,11 +195,11 @@ class TestGitHubPRWebhook(TestCase):self.assertNotIn("pr_merged_by_distinct_id", call_kwargs["properties"])@patch(- "products.tasks.backend.webhooks.resolve_org_github_login_to_users",+ "posthog.api.github_webhooks.attribution.resolve_github_login_distinct_id",side_effect=OperationalError("canceling statement due to statement timeout"),)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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.@@ -235,11 +230,11 @@ class TestGitHubPRWebhook(TestCase):self.assertIs(self.task_run.output.get("pr_merged"), True)@patch(- "products.tasks.backend.webhooks.resolve_org_github_login_to_users",+ "posthog.api.github_webhooks.attribution.resolve_github_login_distinct_id",side_effect=OperationalError("server closed the connection unexpectedly"),)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_merged_attribution_connection_error_is_not_counted_as_timeout(self, mock_capture, mock_get_secret, _mock_resolve):@@ -269,11 +264,12 @@ class TestGitHubPRWebhook(TestCase):_sample_value("posthog_tasks_github_webhook_attribution_total", {"outcome": "timeout"}), timeouts)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture", side_effect=RuntimeError("capture down"))+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch(+ "posthog.api.github_webhooks.pull_requests.posthoganalytics.capture", side_effect=RuntimeError("capture down")+ )def test_task_backed_capture_failure_increments_drop_counter(self, _mock_capture, mock_get_secret):- # TaskRun.capture_event swallows the failure, so without a reported outcome the drop- # counter would miss the task-backed path entirely — the bulk of the traffic.+ # Capture failures must still count as dropped events for Task-owned PRs.mock_get_secret.return_value = self.webhook_secretlabels = {"analytics_event": "pr_merged", "reason": "capture_exception"}before = _sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels)@@ -288,8 +284,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 200)self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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.@@ -308,8 +304,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(mock_capture.call_args[1]["properties"]["run_id"], str(self.task_run.id))self.assertEqual(_sample_value("posthog_tasks_github_webhook_task_run_lookup_total", labels), before + 1)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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".@@ -331,8 +327,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(len(progress), 1)self.assertEqual(progress[0]["notification"]["params"]["label"], "Pull request merged")- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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(@@ -358,8 +354,8 @@ class TestGitHubPRWebhook(TestCase):run.refresh_from_db()self.assertEqual(run.output, {})- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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(@@ -411,8 +407,8 @@ class TestGitHubPRWebhook(TestCase):("already_terminal_run", {"wizard_config": {}}, TaskRun.Status.COMPLETED, {}, 0),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_merged_signals_wizard_workflow_completion(self, _name, state, status, extra_output, expected_signals, _mock_capture, mock_get_secret):@@ -435,8 +431,8 @@ class TestGitHubPRWebhook(TestCase):if expected_signals:mock_signal.assert_called_once_with(run.id, TaskRun.Status.COMPLETED, None)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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.@@ -474,8 +470,8 @@ class TestGitHubPRWebhook(TestCase):self.assertIs(active_run.output.get("pr_merged"), True)self.assertNotIn("pr_merged", terminal_run.output)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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"@@ -517,8 +513,8 @@ class TestGitHubPRWebhook(TestCase):("local_run", {"wizard_config": {}}, TaskRun.Status.IN_PROGRESS, TaskRun.Environment.LOCAL, 0),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_closed_cancels_wizard_run(self, _name, state, status, environment, expected_cancels, _mock_capture, mock_get_secret):@@ -548,8 +544,8 @@ class TestGitHubPRWebhook(TestCase):source="pr_closed",)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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"@@ -570,8 +566,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 200)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_closed_without_merge_webhook(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -591,8 +587,8 @@ class TestGitHubPRWebhook(TestCase):call_kwargs = mock_capture.call_args[1]self.assertEqual(call_kwargs["event"], "pr_closed")- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_opened_webhook(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -630,8 +626,8 @@ class TestGitHubPRWebhook(TestCase):("over_the_cap", _PR_BODY_MAX_CHARS + 1, True),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -663,8 +659,8 @@ class TestGitHubPRWebhook(TestCase):("closed", {"merged": True}, "merged"),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -684,8 +680,8 @@ class TestGitHubPRWebhook(TestCase):assert self.task_run.output is not Noneself.assertEqual(self.task_run.output.get("pr_state"), expected_state)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -705,8 +701,8 @@ class TestGitHubPRWebhook(TestCase):assert self.task_run.output is not Noneself.assertEqual(self.task_run.output.get("pr_state"), "draft")- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -728,8 +724,8 @@ class TestGitHubPRWebhook(TestCase):assert self.task_run.output is not Noneself.assertNotIn("pr_state", self.task_run.output)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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(@@ -759,8 +755,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("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_opened_repairs_missing_artifact_for_existing_pr_url(self, mock_capture, mock_get_secret, mock_feature_enabled) -> None:@@ -790,8 +786,8 @@ class TestGitHubPRWebhook(TestCase):TaskThreadMessage.objects.for_team(self.team.id).filter(task=self.task, payload__pr_url=pr_url).exists())- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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(@@ -820,8 +816,8 @@ class TestGitHubPRWebhook(TestCase):assert run.output is not Noneself.assertEqual(run.output["pr_url"], pr_url)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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(@@ -847,8 +843,8 @@ class TestGitHubPRWebhook(TestCase):run.refresh_from_db()self.assertEqual(run.output, {})- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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"@@ -906,8 +902,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(review_run.output, {})self.assertNotIn("verified_pr_urls", review_run.state or {})- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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"@@ -939,7 +935,7 @@ class TestGitHubPRWebhook(TestCase):[existing, "https://github.com/posthog/posthog/pull/901"],)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")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@@ -956,7 +952,7 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 403)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_missing_signature_rejected(self, mock_get_secret):"""Test that requests without signatures are rejected."""mock_get_secret.return_value = self.webhook_secret@@ -972,8 +968,8 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 403)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_unmatched_pr_without_installation_not_captured(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -990,7 +986,7 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 200)mock_capture.assert_not_called()- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")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@@ -1001,7 +997,7 @@ class TestGitHubPRWebhook(TestCase):self.assertEqual(response.status_code, 200)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")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@@ -1020,7 +1016,7 @@ class TestGitHubPRWebhook(TestCase):def test_webhook_secret_not_configured(self):"""Test that webhook returns 500 if secret is not configured."""- with patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret", return_value=None):+ with patch("posthog.api.github_webhooks.views.get_github_webhook_secret", return_value=None):payload = {"action": "closed", "pull_request": {"html_url": "https://github.com/org/repo/pull/1"}}response = self.client.post(@@ -1037,8 +1033,8 @@ class TestGitHubPRWebhook(TestCase):response = self.client.get("/webhooks/github/pr/")self.assertEqual(response.status_code, 405)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -1125,8 +1121,8 @@ class TestGitHubPRReviewWebhook(TestCase):("unresolvable_login", "stranger", None, "user-123"),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_review_submission_attributes_to_reviewer(self, _name, reviewer_login, expected_property, expected_distinct_id, mock_capture, mock_get_secret):@@ -1157,8 +1153,8 @@ class TestGitHubPRReviewWebhook(TestCase):("non_submitted_action", {"login": "octocat", "id": 583231, "type": "User"}, "dismissed"),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_review_events_not_captured(self, _name, reviewer, action, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -1220,8 +1216,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):("research", True, None, "research", SignalReport.Status.READY),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_event_falls_back_to_task_links(self, _name, merged, actor_kind, relationship, expected_status, _mock_capture, mock_get_secret):@@ -1301,8 +1297,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pr_event_transitions_linked_report(self,_name,@@ -1327,8 +1323,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):self.assertEqual(self.assignment.pr_state, expected_pr_state)self.assertIs(self.assignment.pr_merged, merged)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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()@@ -1345,8 +1341,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):("closed", False, SignalReport.Status.SUPPRESSED, SignalReportAssignment.PrState.CLOSED),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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):@@ -1385,8 +1381,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):legacy_report.refresh_from_db()self.assertEqual(legacy_report.status, expected_status)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -1404,8 +1400,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):self.assertEqual(self.assignment.pr_state, SignalReportAssignment.PrState.OPEN)self.assertFalse(self.assignment.pr_merged)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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")@@ -1449,8 +1445,8 @@ class TestGitHubPRWebhookResolvesSignalReports(TestCase):("www_host_trailing_slash", "https://www.github.com/posthog/posthog/pull/42/"),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -1528,8 +1524,8 @@ class TestExternalPRWebhook(TestCase):("merged", "closed", True, "pr_merged"),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_external_pr_event_attributes_to_installation_team(self, _name, action, merged, expected_event, mock_capture, mock_get_secret):@@ -1563,8 +1559,8 @@ class TestExternalPRWebhook(TestCase):for key in ("pr_title", "pr_body", "pr_labels", "pr_requested_reviewers", "pr_is_draft"):self.assertIsNone(props[key])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_external_pr_event_is_deduplicated_per_action(self, mock_capture, mock_get_secret):mock_get_secret.return_value = self.webhook_secret@@ -1577,8 +1573,8 @@ class TestExternalPRWebhook(TestCase):second_uuid = mock_capture.call_args_list[1][1]["uuid"]self.assertEqual(first_uuid, second_uuid)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -1590,8 +1586,8 @@ class TestExternalPRWebhook(TestCase):self.assertEqual(response.status_code, 200)mock_capture.assert_not_called()- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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.@@ -1606,8 +1602,10 @@ class TestExternalPRWebhook(TestCase):mock_capture.assert_not_called()self.assertEqual(_sample_value("posthog_tasks_github_webhook_pr_event_dropped_total", labels), before + 1)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture", side_effect=RuntimeError("capture down"))+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch(+ "posthog.api.github_webhooks.pull_requests.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"}@@ -1623,7 +1621,10 @@ class TestExternalPRWebhook(TestCase):# Task.github_user_integration is unindexed. Such a task lives in a team of the# installing user's org, so widen the scope there rather than give up and scan.payload = self._external_payload("opened", merged=False)- self.assertEqual(_task_run_scope_team_ids(payload), [self.team.id])+ self.assertEqual(+ _task_run_scope_team_ids(payload),+ [self.team.id],+ )personal_org = Organization.objects.create(name="Personal Org")personal_team = Team.objects.create(organization=personal_org, name="Personal Team")@@ -1631,12 +1632,15 @@ class TestExternalPRWebhook(TestCase):OrganizationMembership.objects.create(organization=personal_org, user=user)UserIntegration.objects.create(user=user, kind="github", integration_id="555000")- self.assertEqual(_task_run_scope_team_ids(payload), sorted([self.team.id, personal_team.id]))+ self.assertEqual(+ _task_run_scope_team_ids(payload),+ sorted([self.team.id, personal_team.id]),+ )# Attribution still resolves off the Integration rows alone.self.assertEqual(_installation_team_ids(payload), [self.team.id])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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@@ -1674,8 +1678,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("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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")@@ -1690,8 +1694,8 @@ class TestExternalPRWebhook(TestCase):distinct_ids = {call[1]["distinct_id"] for call in mock_capture.call_args_list}self.assertEqual(distinct_ids, {str(expected_team.uuid)})- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.webhooks.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.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)@@ -2181,7 +2185,7 @@ class TestGitHubWebhookFanout(TestCase):])@patch("products.conversations.backend.api.github_events.process_github_event")- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_issues_event_dispatched_to_conversations(self, _name, url, mock_secret, mock_task):mock_secret.return_value = self.webhook_secretmock_task.delay = MagicMock()@@ -2204,7 +2208,7 @@ class TestGitHubWebhookFanout(TestCase):self.assertEqual(call_kwargs["repo"], "myorg/myrepo")@patch("products.conversations.backend.api.github_events.process_github_event")- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_issue_comment_event_dispatched_to_conversations(self, mock_secret, mock_task):mock_secret.return_value = self.webhook_secretmock_task.delay = MagicMock()@@ -2225,7 +2229,7 @@ class TestGitHubWebhookFanout(TestCase):self.assertEqual(mock_task.delay.call_args[1]["event_type"], "issue_comment")@patch("products.conversations.backend.api.github_events.process_github_event")- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_issues_event_without_matching_team_returns_200(self, mock_secret, mock_task):mock_secret.return_value = self.webhook_secretmock_task.delay = MagicMock()@@ -2249,8 +2253,8 @@ class TestGitHubWebhookFanout(TestCase):("unified_url", "/webhooks/github/"),])- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")- @patch("products.tasks.backend.models.posthoganalytics.capture")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.pull_requests.posthoganalytics.capture")def test_pull_request_routed(self, _name, url, mock_capture, mock_secret):mock_secret.return_value = self.webhook_secret@@ -2268,7 +2272,7 @@ class TestGitHubWebhookFanout(TestCase):mock_capture.assert_called_once()self.assertEqual(mock_capture.call_args[1]["event"], "pr_merged")- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_unified_url_unknown_event_returns_200(self, mock_secret):mock_secret.return_value = self.webhook_secret@@ -2277,7 +2281,7 @@ class TestGitHubWebhookFanout(TestCase):self.assertEqual(response.status_code, 200)- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")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@@ -2304,7 +2308,7 @@ class TestGitHubWebhookFanout(TestCase):self.assertEqual(third.status_code, 200)mock_loops.assert_called_once()- @patch("products.tasks.backend.facade.webhooks.get_github_webhook_secret")+ @patch("posthog.api.github_webhooks.views.get_github_webhook_secret")def test_unified_url_bad_signature_returns_403(self, mock_secret):mock_secret.return_value = self.webhook_secret@@ -2486,7 +2490,7 @@ class TestAttributionDbAliases(TestCase):def test_default_only_when_no_replica_is_configured(self):self.assertEqual(_attribution_db_aliases(), ["default"])- @patch("products.tasks.backend.webhooks.router.db_for_read", return_value="default")+ @patch("posthog.api.github_webhooks.attribution.router.db_for_read", return_value="default")def test_skips_a_configured_replica_the_router_would_not_read_from(self, _mock_db_for_read):# Bounding an alias means opening it, and connection setup is itself unbounded (these# aliases carry no connect_timeout), so a replica the router never reads from must not@@ -2494,14 +2498,14 @@ class TestAttributionDbAliases(TestCase):with self._with_replica_configured():self.assertEqual(_attribution_db_aliases(), ["default"])- @patch("products.tasks.backend.webhooks.router.db_for_read", return_value="replica")+ @patch("posthog.api.github_webhooks.attribution.router.db_for_read", return_value="replica")def test_skips_the_primary_when_every_model_reads_from_the_replica(self, _mock_db_for_read):# Symmetric to the above: a fully replica-opted deployment must not be made to wait on# the primary either, since opening it is just as unbounded.with self._with_replica_configured():self.assertEqual(_attribution_db_aliases(), ["replica"])- @patch("products.tasks.backend.webhooks.router.db_for_read")+ @patch("posthog.api.github_webhooks.attribution.router.db_for_read")def test_covers_every_alias_the_models_read_from(self, mock_db_for_read):mock_db_for_read.side_effect = lambda model: "replica" if model is User else "default"with self._with_replica_configured():diff --git a/products/tasks/backend/webhooks.py b/products/tasks/backend/webhooks.pyindex e202a545cca5..aaa056bff599 100644--- a/products/tasks/backend/webhooks.py+++ b/products/tasks/backend/webhooks.py@@ -1,39 +1,23 @@-import hmac-import uuid-import hashlib-from collections.abc import Iterator-from contextlib import ExitStack, contextmanager--from django.conf import settings-from django.db import OperationalError, connections, router, transaction-from django.db.backends.base.base import BaseDatabaseWrapper+from django.db import transactionfrom django.db.models import Case, IntegerField, Q, Value, Whenfrom django.http import HttpResponseimport structlog-import posthoganalytics-from social_django.models import UserSocialAuth+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.models.instance_setting import get_instance_setting-from posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Team-from posthog.models.user import Userfrom posthog.models.user_integration import UserIntegration-from products.signals.backend.report_assignments import update_assignments_for_pull_request-from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users+from products.signals.backend.facade.github import update_pull_request_assignmentsfrom products.tasks.backend.constants import PR_LOOP_ENABLED_STATE_KEYfrom products.tasks.backend.facade.api import post_pr_created_thread_update, signal_workflow_completionfrom products.tasks.backend.facade.cancellation import cancel_task_run-from products.tasks.backend.metrics import (- GitHubWebhookAnalyticsEvent,- GitHubWebhookAttributionOutcome,- observe_github_webhook_attribution,- observe_github_webhook_pr_event_dropped,- observe_github_webhook_task_run_lookup,-)+from products.tasks.backend.metrics import observe_github_webhook_task_run_lookupfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.pr_urls import merge_pr_output, read_pr_urlsfrom products.tasks.backend.prompts import WIZARD_HEAD_BRANCH_PREFIX@@ -186,53 +170,34 @@ def find_task_run(return None-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.new(- secret.encode("utf-8"),- payload,- hashlib.sha256,- ).hexdigest()- )-- 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 None---def _pr_state_for_action(action: str | None, pull_request: dict) -> str | None:- """The ``output.pr_state`` a webhook action moves a run's PR to, in the- same open/draft/merged/closed vocabulary the GitHub snapshot uses. None- for actions that don't change the state (comments, labels, pushes)."""- if action in ("opened", "reopened"):- return "draft" if pull_request.get("draft") else "open"- if action == "ready_for_review":- return "open"- if action == "converted_to_draft":- return "draft"- if action == "closed":- return "merged" if pull_request.get("merged") else "closed"- return None+def _capture_task_pr_event(payload: dict, task_run: TaskRun | None, event: GitHubWebhookAnalyticsEvent) -> None:+ try:+ attribution = None+ if task_run is not None:+ attribution = PullRequestAttribution(+ source="task",+ team_id=task_run.team_id,+ distinct_id=(+ str(task_run.task.created_by.distinct_id)+ if task_run.task.created_by_id and task_run.task.created_by+ else str(task_run.team.uuid)+ ),+ groups=groups(team=task_run.team),+ properties=task_run.analytics_properties(),+ include_content=True,+ send_feature_flags=True,+ )+ except Exception as error:+ observe_github_webhook_pr_event_dropped(analytics_event=event, reason="capture_exception")+ logger.warning("github_pr_webhook_capture_failed", analytics_event=event, error=str(error))+ return+ capture_pr_event(payload, attribution, event)def handle_pull_request_event(payload: dict) -> HttpResponse:"""Process a pre-verified pull_request webhook event.- Called from ``posthog.urls.github_webhook`` (unified dispatcher).+ Called from the shared GitHub webhook dispatcher (unified dispatcher)."""action = payload.get("action")pull_request = payload.get("pull_request", {})@@ -243,7 +208,7 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:logger.warning("github_pr_webhook_no_pr_url", action=action)return HttpResponse(status=200)- pr_state = _pr_state_for_action(action, pull_request)+ pr_state = pr_state_for_action(action, pull_request)analytics_event: GitHubWebhookAnalyticsEvent | None = Noneif action == "opened":event_action = "created"@@ -267,7 +232,6 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:branch = pull_request.get("head", {}).get("ref")repository_full_name = (payload.get("repository") or {}).get("full_name")scoped_team_ids = _task_run_scope_team_ids(payload)- assignment_team_ids = _installation_team_ids(payload)task_run = find_task_run(pr_url=pr_url, branch=branch, repository=repository_full_name, team_ids=scoped_team_ids)claimed_pr_urls = (read_pr_urls(task_run.output if isinstance(task_run.output, dict) else {}) if task_run is not None else []@@ -311,23 +275,10 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:):_record_run_pr_state(task_run, pr_state)- if pr_state is not None and repository_full_name and assignment_team_ids:- try:- update_assignments_for_pull_request(- team_ids=assignment_team_ids,- repository=repository_full_name,- pr_number=int(pull_request.get("number")),- pr_state=pr_state,- )- except (TypeError, ValueError):- logger.warning("github_pr_webhook_signal_assignment_missing_number", pr_url=pr_url)- except Exception:- logger.exception("github_pr_webhook_signal_assignment_update_failed", pr_url=pr_url)+ update_pull_request_assignments(payload, pr_state)if analytics_event is not None:- # Deterministic UUID dedupes duplicate webhook deliveries of the same PR action.- event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:{analytics_event}"))- _capture_pr_event(payload, task_run, analytics_event, event_uuid)+ _capture_task_pr_event(payload, task_run, analytics_event)if action == "closed" and merged:# Only trust the merge for the run that actually claims this PR URL. The pr_url backstop@@ -347,7 +298,7 @@ def handle_pull_request_event(payload: dict) -> HttpResponse:def handle_pull_request_review_event(payload: dict) -> HttpResponse:"""Process a pre-verified pull_request_review webhook event.- Called from ``posthog.urls.github_webhook`` (unified dispatcher). Captures a+ Called from the shared GitHub webhook dispatcher (unified dispatcher). 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.@@ -375,9 +326,7 @@ def handle_pull_request_review_event(payload: dict) -> HttpResponse:pr_url=pr_url, branch=branch, repository=repository_full_name, team_ids=_task_run_scope_team_ids(payload))- # One review submission = one event; GitHub redeliveries collapse on the review id.- event_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, f"{pr_url}:pr_reviewed:{review.get('id')}"))- _capture_pr_review_event(payload, task_run, event_uuid)+ _capture_task_pr_event(payload, task_run, "pr_reviewed")logger.info("github_pr_review_webhook_processed",@@ -568,369 +517,6 @@ def _record_run_output_field(task_run: TaskRun, key: str, value: str | bool, faireturn 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")--# What a PR says, rather than how big it is. Only task-authored PRs carry these values -- an-# external PR's own words are customer business context, so it gets the keys as nulls for-# schema parity, the same way _TASK_ATTRIBUTION_KEYS works.-_PR_CONTENT_KEYS = (- "pr_title",- "pr_body",- "pr_body_truncated",- "pr_labels",- "pr_requested_reviewers",- "pr_is_draft",-)--# A PR body is the biggest string on the delivery, and an agent-authored one can run long.-# Cap it so one verbose body cannot push the event past the capture size limit.-_PR_BODY_MAX_CHARS = 10_000---def _account_type(payload: dict) -> str | None:- """Whether the webhook's repo is owned by a GitHub org or a personal account.-- ``repository.owner.type`` is "Organization" or "User"; the top-level- ``organization`` object is present only for org-owned repos and backs it up- when the owner block is missing. Returns None when neither signal is present.- """- owner_type = ((payload.get("repository") or {}).get("owner") or {}).get("type")- if owner_type == "Organization":- return "organization"- if owner_type == "User":- return "personal"- if payload.get("organization"):- return "organization"- return None---def _pr_payload_properties(payload: dict) -> dict:- pull_request = payload.get("pull_request") or {}- return {- "pr_url": pull_request.get("html_url"),- "pr_number": pull_request.get("number"),- "pr_author": (pull_request.get("user") or {}).get("login"),- "pr_base_ref": (pull_request.get("base") or {}).get("ref"),- "pr_head_ref": (pull_request.get("head") or {}).get("ref"),- "pr_additions": pull_request.get("additions"),- "pr_deletions": pull_request.get("deletions"),- "pr_changed_files": pull_request.get("changed_files"),- "pr_commits": pull_request.get("commits"),- "account_type": _account_type(payload),- "repo_owner_type": ((payload.get("repository") or {}).get("owner") or {}).get("type"),- }---def _pr_content_properties(payload: dict) -> dict:- """What a task-authored PR says: its title, body, labels, requested reviewers, draft state."""- pull_request = payload.get("pull_request") or {}- body = pull_request.get("body") or ""- return {- "pr_title": pull_request.get("title"),- "pr_body": body[:_PR_BODY_MAX_CHARS],- "pr_body_truncated": len(body) > _PR_BODY_MAX_CHARS,- "pr_labels": [label.get("name") for label in (pull_request.get("labels") or []) if label.get("name")],- "pr_requested_reviewers": [- reviewer.get("login")- for reviewer in (pull_request.get("requested_reviewers") or [])- if reviewer.get("login")- ],- "pr_is_draft": pull_request.get("draft"),- }---# Cap the org-member lookup that attributes the merger (and reviewer). GitHub gives a-# pull_request delivery one short window and never retries it, and the merged branch runs-# functional side effects (merge bookkeeping, signal-report resolution, wizard wind-down)-# right after capture. A slow lookup on the request path can therefore cost the whole-# delivery, not just the analytics event. Bounding it degrades to no attribution instead.-_ATTRIBUTION_STATEMENT_TIMEOUT_MS = 800--# Models the org-member resolver reads. ReplicaRouter only sends a model to the replica when-# that model is named in READ_REPLICA_OPT_IN, so the set of aliases the lookup can touch is-# knowable up front.-_ATTRIBUTION_MODELS = (Team, User, OrganizationMembership, UserSocialAuth, UserIntegration, Integration)---def _attribution_db_aliases() -> list[str]:- """The aliases the org-member lookup actually reads from, deduped, in model order.-- Bounding an alias means opening it, and opening is itself unbounded -- ``postgres_config``- sets no ``connect_timeout`` on these aliases. So take the set from the router rather than- assuming: reaching for an alias the resolver never uses could stall the webhook on- connection setup before the cap is installed, which is the failure this exists to prevent.- That cuts both ways -- a fully replica-opted deployment must not be made to wait on the- primary either.- """- aliases: list[str] = []- for model in _ATTRIBUTION_MODELS:- alias = router.db_for_read(model) or "default"- if alias not in aliases and alias in settings.DATABASES:- aliases.append(alias)- return aliases---def _read_statement_timeout(connection: BaseDatabaseWrapper) -> str | None:- with connection.cursor() as cursor:- cursor.execute("SHOW statement_timeout")- row = cursor.fetchone()- return row[0] if row else None---def _apply_statement_timeout(connection: BaseDatabaseWrapper, value: str) -> None:- # set_config(..., is_local=True) is SET LOCAL, but takes the value as a bind parameter,- # so a restored value ("30s", "0", ...) does not have to be quoted by hand.- with connection.cursor() as cursor:- cursor.execute("SELECT set_config('statement_timeout', %s, true)", [value])---@contextmanager-def _statement_timeout(connection: BaseDatabaseWrapper, timeout_ms: int, *, restore: bool) -> Iterator[None]:- """Cap statements on one connection, optionally putting the previous value back."""- previous = _read_statement_timeout(connection) if restore else None- _apply_statement_timeout(connection, f"{timeout_ms}ms")-- yield-- # Only reached when the block succeeded. If it raised, the enclosing atomic() rolls the- # (sub)transaction back and PostgreSQL undoes SET LOCAL with it, so there is nothing to- # restore -- and a statement on an aborted transaction would error anyway.- if previous:- _apply_statement_timeout(connection, previous)---@contextmanager-def _bounded_attribution_lookup() -> Iterator[None]:- """Run a block under a per-statement timeout on each configured DB the lookup may use.-- A read routed to an alias joins that alias's open transaction, so ``SET LOCAL- statement_timeout`` there caps the query regardless of read-replica routing.- """- with ExitStack() as stack:- for alias in _attribution_db_aliases():- connection = connections[alias]- # SET LOCAL dies with the transaction it was set in, so the cap only needs- # restoring when we are joining a transaction somebody else owns -- a future- # caller wrapping this in its own atomic block, or ATOMIC_REQUESTS (which- # PostHog does not enable today). Otherwise the commit below ends it for us.- restore = connection.in_atomic_block- stack.enter_context(transaction.atomic(using=alias))- stack.enter_context(_statement_timeout(connection, _ATTRIBUTION_STATEMENT_TIMEOUT_MS, restore=restore))- yield---# PostgreSQL raises query_canceled when statement_timeout fires. Django wraps the driver-# error in OperationalError, so the SQLSTATE lives on the cause -- psycopg3 spells it-# `sqlstate`, psycopg2 `pgcode`. The message check is the fallback for anything that loses-# the cause on the way up.-_QUERY_CANCELED_SQLSTATE = "57014"---def _is_statement_timeout(error: Exception) -> bool:- if not isinstance(error, OperationalError):- return False- cause = error.__cause__- if getattr(cause, "sqlstate", None) == _QUERY_CANCELED_SQLSTATE:- return True- if getattr(cause, "pgcode", None) == _QUERY_CANCELED_SQLSTATE:- return True- return "statement timeout" in str(error).lower()---def _resolve_github_login_distinct_id(login: str | None, team_id: int) -> str | None:- """Distinct id of the org member matching a GitHub login, or None when unresolvable.-- Runs under a per-statement timeout so a slow member lookup cannot hold the webhook- open past GitHub's delivery timeout (see ``_ATTRIBUTION_STATEMENT_TIMEOUT_MS``).- """- if not login:- return None- try:- with _bounded_attribution_lookup():- resolved = resolve_org_github_login_to_users(team_id, [login]).get(str(login).strip().lower())- except Exception as e:- # timeout is meant to be the leading indicator for the cap we just installed, so it- # has to mean "statement cancelled", not "any OperationalError" -- connection resets- # and other DB incidents raise the same class and would drown the signal.- outcome: GitHubWebhookAttributionOutcome = "timeout" if _is_statement_timeout(e) else "error"- observe_github_webhook_attribution(outcome=outcome)- logger.warning(- "github_webhook_login_resolution_failed", login=login, team_id=team_id, outcome=outcome, error=str(e)- )- return None- if resolved is None:- observe_github_webhook_attribution(outcome="unresolved")- return None- observe_github_webhook_attribution(outcome="resolved")- return str(resolved.distinct_id)---def _merged_by_attribution(payload: dict, team_id: int) -> tuple[dict, str | None]:- """Identity of the GitHub user who merged the PR, resolved to a PostHog user when possible.-- Merging is the one unambiguous personal act in the loop, so when the merger's GitHub- login 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.- """- merged_by = (payload.get("pull_request") or {}).get("merged_by") or {}- login = merged_by.get("login")- if not login:- return {}, None- properties: dict = {"pr_merged_by_login": login, "pr_merged_by_id": merged_by.get("id")}- distinct_id = _resolve_github_login_distinct_id(login, team_id)- if distinct_id is not None:- properties["pr_merged_by_distinct_id"] = distinct_id- return properties, distinct_id---def _capture_pr_review_event(payload: dict, task_run: TaskRun | None, event_uuid: str) -> None:- review = payload.get("review") or {}- reviewer = review.get("user") or {}- login = reviewer.get("login")- review_properties: dict = {- "pr_review_state": review.get("state"),- "pr_reviewed_by_login": login,- "pr_reviewed_by_id": reviewer.get("id"),- }- pr_properties = {**_pr_payload_properties(payload), **review_properties}-- if task_run is not None:- reviewer_distinct_id = _resolve_github_login_distinct_id(login, task_run.team_id)- if reviewer_distinct_id is not None:- pr_properties["pr_reviewed_by_distinct_id"] = reviewer_distinct_id- captured = task_run.capture_event(- "pr_reviewed",- {**pr_properties, **_pr_content_properties(payload), "pr_source": "task"},- event_uuid=event_uuid,- distinct_id_override=reviewer_distinct_id,- )- if not captured:- observe_github_webhook_pr_event_dropped(analytics_event="pr_reviewed", reason="capture_exception")- return-- team = _resolve_external_team(payload)- if team is None:- observe_github_webhook_pr_event_dropped(analytics_event="pr_reviewed", reason="unresolved_installation")- logger.debug("github_pr_review_webhook_unresolved_installation", pr_url=pr_properties.get("pr_url"))- return-- reviewer_distinct_id = _resolve_github_login_distinct_id(login, team.id)- if reviewer_distinct_id is not None:- pr_properties["pr_reviewed_by_distinct_id"] = reviewer_distinct_id-- properties: dict = {- **pr_properties,- "repository": ((payload.get("repository") or {}).get("full_name") or "").strip().lower() or None,- "pr_source": "external",- "team_id": team.id,- # title and PR content omitted to avoid leaking customer business context.- **dict.fromkeys(_TASK_ATTRIBUTION_KEYS, None),- **dict.fromkeys(_PR_CONTENT_KEYS, None),- }-- try:- posthoganalytics.capture(- distinct_id=reviewer_distinct_id or str(team.uuid),- event="pr_reviewed",- properties=properties,- groups=groups(team=team),- uuid=event_uuid,- )- except Exception as e:- observe_github_webhook_pr_event_dropped(analytics_event="pr_reviewed", reason="capture_exception")- logger.warning("github_pr_review_webhook_capture_failed", error=str(e))---def _capture_pr_event(- payload: dict, task_run: TaskRun | None, analytics_event: GitHubWebhookAnalyticsEvent, event_uuid: str-) -> None:- pr_properties = _pr_payload_properties(payload)-- if task_run is not None:- merger_distinct_id: str | None = None- if analytics_event == "pr_merged":- merged_by_properties, merger_distinct_id = _merged_by_attribution(payload, task_run.team_id)- pr_properties = {**pr_properties, **merged_by_properties}- captured = task_run.capture_event(- analytics_event,- {**pr_properties, **_pr_content_properties(payload), "pr_source": "task"},- event_uuid=event_uuid,- distinct_id_override=merger_distinct_id,- )- if not captured:- observe_github_webhook_pr_event_dropped(analytics_event=analytics_event, reason="capture_exception")- return-- team = _resolve_external_team(payload)- if team is None:- observe_github_webhook_pr_event_dropped(analytics_event=analytics_event, reason="unresolved_installation")- logger.debug("github_pr_webhook_unresolved_installation", pr_url=pr_properties.get("pr_url"))- return-- external_distinct_id = str(team.uuid)- if analytics_event == "pr_merged":- merged_by_properties, merger_distinct_id = _merged_by_attribution(payload, team.id)- pr_properties = {**pr_properties, **merged_by_properties}- external_distinct_id = merger_distinct_id or external_distinct_id-- properties: dict = {- **pr_properties,- "repository": ((payload.get("repository") or {}).get("full_name") or "").strip().lower() or None,- "pr_source": "external",- "team_id": team.id,- # title and PR content omitted to avoid leaking customer business context.- **dict.fromkeys(_TASK_ATTRIBUTION_KEYS, None),- **dict.fromkeys(_PR_CONTENT_KEYS, None),- }-- try:- posthoganalytics.capture(- distinct_id=external_distinct_id,- event=analytics_event,- properties=properties,- groups=groups(team=team),- uuid=event_uuid,- )- except Exception as e:- observe_github_webhook_pr_event_dropped(analytics_event=analytics_event, reason="capture_exception")- logger.warning("github_pr_webhook_capture_failed", analytics_event=analytics_event, error=str(e))---def _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)---# The run lookup these feed reads TaskRun off the writer, and they run on the request path-# outside the bounded attribution block. Pin them to the writer too: a replica-opted-# Integration or Team would otherwise let a slow replica stall a delivery whose own lookup-# never needed it, and replica lag could hide a freshly connected installation.-_SCOPE_DB_ALIAS = "default"---def _installation_team_ids(payload: dict) -> list[int]:- """Teams whose GitHub Integration matches the delivery's installation, in deterministic order.-- Empty when the payload carries no installation id or no Integration matches it — the- lookups that take this fall back to their unscoped behaviour in that case.- """- external_id = _installation_id(payload)- if external_id is None:- return []-- # One installation can map to multiple teams; order_by makes attribution deterministic.- return list(- Integration.objects.using(_SCOPE_DB_ALIAS)- .filter(kind="github", integration_id=external_id)- .order_by("team_id")- .values_list("team_id", flat=True)- )--def _task_run_scope_team_ids(payload: dict) -> list[int]:"""Teams to scope the TaskRun lookup to, or empty to leave the lookup unscoped.@@ -968,10 +554,3 @@ def _task_run_scope_team_ids(payload: dict) -> list[int]:)return sorted(team_ids)---def _resolve_external_team(payload: dict) -> Team | None:- team_ids = _installation_team_ids(payload)- if not team_ids:- return None- return Team.objects.filter(pk=team_ids[0]).first()