: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(warehouse sources): sync github pr reviews (#69623)
Julian Bez17e79e8d8cd5
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.pyindex f79108509084..d0c7730460b7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/canonical_descriptions.py@@ -56,6 +56,23 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"closed_at": "Time at which the pull request was closed, if applicable.",},},+ "reviews": {+ "description": "A submitted review on a pull request (an approval, change request, or comment). One row per submitted review, with the reviewed pull request's number attached for attribution. Rows arrive via the repository's pull_request_review webhook.",+ "docs_url": "https://docs.github.com/en/rest/pulls/reviews",+ "columns": {+ "id": "Unique identifier for the review.",+ "pr_number": "Number of the pull request this review was submitted on (injected from the parent pull request).",+ "node_id": "Global node ID for the review.",+ "user": "The user who submitted the review.",+ "body": "The review's summary text in markdown.",+ "state": "The review verdict (APPROVED, CHANGES_REQUESTED, COMMENTED, or DISMISSED).",+ "commit_id": "SHA of the commit the review was submitted against.",+ "author_association": "The reviewer's relationship to the repository (e.g. MEMBER, COLLABORATOR, CONTRIBUTOR).",+ "html_url": "Web URL for the review on GitHub.",+ "pull_request_url": "API URL for the pull request the review belongs to.",+ "submitted_at": "Time at which the review was submitted.",+ },+ },"commits": {"description": "A commit in the repository's history.","docs_url": "https://docs.github.com/en/rest/commits/commits",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.pyindex cc1d888e7cb1..ea1face026d7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py@@ -28,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basExternalWebhookInfo,WebhookCreationResult,WebhookDeletionResult,+ WebhookSyncResult,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -170,10 +171,13 @@ def _resolve_sort_mode(pagination via sort=created&direction=asc) and only flip to theirconfigured sort once a cutoff exists. workflow_runs is different: it ignoressort/direction and always returns newest-first, so it emits desc on every- sync — including the first. workflow_jobs inherits that order: it fans out- over workflow_runs newest-first, so its jobs land newest-first too.+ sync, including the first. Fan-out children inherit the parent walk's order+ on every sync too, first incremental sync included: the initial_lookback_days+ floor gives that sync a cutoff, which makes the parent walk descend. Reporting+ asc for it would let the pipeline persist the cursor per batch and, on an+ interrupted backfill, strand every row older than the batches that flushed."""- if endpoint in ("workflow_runs", "workflow_jobs"):+ if endpoint == "workflow_runs" or config.fan_out_parent is not None:return config.sort_modeif should_use_incremental_field and db_incremental_field_last_value:return config.sort_mode@@ -386,6 +390,14 @@ def _is_issue_not_pr(item: dict[str, Any]) -> bool:return "pull_request" not in item or item["pull_request"] is None+def _is_submitted_review(item: dict[str, Any]) -> bool:+ """Drop the caller's own draft (PENDING) reviews. GitHub returns them from the list endpoint with+ submitted_at=null; they are not metrics data and a null would land in the partition/cursor column.+ Keyed on submitted_at rather than the state string so the non-null invariant is enforced directly,+ whatever shape the state field takes."""+ return item.get("submitted_at") is not None++def _make_parent_field_injector(parent: dict[str, Any], field_map: dict[str, str]) -> Callable[[dict[str, Any]], dict[str, Any]]:@@ -412,6 +424,8 @@ def _get_item_mapper(endpoint: str) -> Callable[[dict[str, Any]], dict[str, Any]def _get_item_filter(endpoint: str) -> Callable[[dict[str, Any]], bool] | None:if endpoint == "issues":return _is_issue_not_pr+ if endpoint == "reviews":+ return _is_submitted_reviewreturn None@@ -567,7 +581,12 @@ def _iter_child_for_parent(egress_identity: GithubEgressIdentity | None = None,) -> Iterator[dict[str, Any]]:"""Walk a fan-out child endpoint for one parent, substituting the parent's value into the- child path placeholder (e.g. {run_id} for workflow_jobs, {team_slug} for team_members)."""+ child path placeholder (e.g. {run_id} for workflow_jobs, {team_slug} for team_members).++ Applies the endpoint's item filter and mapper (same seam as the top-level get_rows path) so a+ fan-out child gets them too, e.g. reviews drops PENDING drafts before rows leave the walk. Parent+ field injection stays in the caller, which has the parent object; the order there is filter, map,+ then inject."""fan_out_param = config.fan_out_path_parampath = config.path.format(repository=repository,@@ -576,6 +595,8 @@ def _iter_child_for_parent()params: dict[str, Any] = {"per_page": config.page_size, **(config.extra_params or {})}url = f"{GITHUB_BASE_URL}{path}?{urlencode(params)}"+ item_filter = _get_item_filter(config.name)+ item_mapper = _get_item_mapper(config.name)for items, _page_url in _iter_pages(url,headers,@@ -585,7 +606,10 @@ def _iter_child_for_parent(page_cap_context={"repository": repository, fan_out_param: parent_value},egress_identity=egress_identity,):- yield from items+ for item in items:+ if item_filter and not item_filter(item):+ continue+ yield item_mapper(item) if item_mapper else itemdef _fan_out_get_rows(@@ -596,7 +620,6 @@ def _fan_out_get_rows(resumable_source_manager: ResumableSourceManager[GithubResumeConfig],should_use_incremental_field: bool,db_incremental_field_last_value: Any,- incremental_field: str | None,egress_identity: GithubEgressIdentity | None = None,) -> Iterator[Any]:"""Single-hop parent->child fan-out: walk the parent endpoint and emit every child row for each@@ -609,6 +632,9 @@ def _fan_out_get_rows(id. Full-refresh parents (teams) have no cursor, so every parent is walked each sync; the datavolume is tiny, and there is no timestamp to bound on anyway.+ The walk bounds on the parent's own cursor field, compared against the child's watermark; see+ the parent_cursor_field comment below for the invariant that keeps that comparison sound.+Same created_at-cursor staleness workflow_runs carries applies to its jobs: a run that wasin_progress when first synced drops below the watermark once it finishes, so later job state isnot re-fetched by the poll; the workflow_run webhook is the fix, not re-scanning history.@@ -625,7 +651,13 @@ def _fan_out_get_rows(# A parent with no incremental fields (teams) has no cursor to bound on, so walk it whole.parent_is_incremental = bool(parent_config.incremental_fields)- parent_cursor_field = incremental_field or parent_config.default_incremental_field or "created_at"+ # Bound the walk on the PARENT's own cursor field, never the child's incremental field, which+ # may not exist on parent rows (reviews sync on submitted_at, which lives on the review, not+ # the pull request). Comparing the parent cursor against the child watermark is sound because+ # whatever creates a child row also bumps the parent's cursor (a submitted review bumps the+ # PR's updated_at), so a parent holding children newer than the watermark always sorts above+ # it; parents bumped for other reasons get re-fanned harmlessly since children upsert by key.+ parent_cursor_field = parent_config.default_incremental_field or "created_at"parent_cutoff = (db_incremental_field_last_value if (should_use_incremental_field and parent_is_incremental) else None)@@ -647,7 +679,24 @@ def _fan_out_get_rows(if resume_config is not None:parent_url: str = resume_config.next_urllogger.debug(f"Github: resuming {endpoint} fan-out from parent URL: {parent_url}")+ elif parent_is_incremental:+ # Build the parent list URL with the parent's own incremental params so it arrives sorted on+ # parent_cursor_field descending once a cutoff exists. Without the sort, pull_requests would+ # come back in its default order (created asc) and _should_stop_desc below would see an old+ # record on the first page and halt early, dropping newer parents. workflow_runs takes its+ # per_page-only branch inside _build_initial_params (the API ignores sort/direction and+ # always returns newest-first).+ parent_params = _build_initial_params(+ parent_config,+ parent_config.name,+ should_use_incremental_field,+ parent_cutoff,+ parent_cursor_field,+ )+ parent_url = _build_initial_url(parent_config, repository, parent_params)else:+ # Cursor-less parents (teams) take a plain paged read; the generic state/sort defaults in+ # _build_initial_params belong to list endpoints that define those params.parent_url = _build_initial_url(parent_config, repository, {"per_page": parent_config.page_size})for parents, page_url in _iter_pages(@@ -710,7 +759,6 @@ def get_rows(resumable_source_manager=resumable_source_manager,should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,- incremental_field=incremental_field,egress_identity=egress_identity,)return@@ -866,7 +914,7 @@ def github_source(# passed (or it isn't enabled), the poll path below stays unchanged.## An endpoint whose poll does no first-sync backfill (initial_lookback_days == 0,- # i.e. workflow_jobs) would otherwise deadlock a fresh webhook schema: the+ # i.e. workflow_jobs and reviews) would otherwise deadlock a fresh webhook schema: the# zero-row poll never creates a table, so initial_sync_complete is never set, so# webhook_enabled stays False forever and queued webhook files never drain. There# is no backfill to lose for these, so activate webhook mode from the first run@@ -886,6 +934,9 @@ def github_source(# job and workflow-run objects once: the "list jobs for a workflow run" REST# response object is the same schema as the workflow_job webhook event's nested# workflow_job object (same for workflow_run), so the rows are interchangeable.+ # Reviews need a reshape (the event nests the review under body.review, states+ # are lowercase, and pr_number is injected) which the template does before+ # producing, so rows land here already in the polled REST shape.## Each event for an id arrives as its own row (queued -> in_progress -> completed);# collapse them to the latest per id here, since the delta merge doesn't dedupe a@@ -981,13 +1032,32 @@ def create_repo_webhook()-def _list_repo_hooks(token: str, repo: str) -> tuple[list[dict[str, Any]] | None, str | None]:+def _list_repo_hooks(+ token: str, repo: str, egress_identity: GithubEgressIdentity | None = None+) -> tuple[list[dict[str, Any]] | None, str | None]:"""List repo webhooks via GET /repos/{repo}/hooks. Returns (hooks, error); error is- ``"permission"`` when the token lacks admin:repo_hook so callers can fall back to manual setup."""+ ``"permission"`` when the token lacks admin:repo_hook so callers can fall back to manual setup.++ Rate limits (and egress budget sheds) are classified before the permission mapping: a+ rate-limited 403 also lands in _is_repo_hook_permission_error's status set, and misreading it+ would tell the user their token lacks webhook permissions while the token is fine."""+ installation_id = egress_identity.installation_id if egress_identity is not None else Nonetry:- response = make_tracked_session().get(- f"{GITHUB_BASE_URL}/repos/{repo}/hooks", headers=_get_headers(token), params={"per_page": 100}, timeout=30+ # Gated + recorded transport, like the data plane and the reconcile PATCH. NORMAL, not+ # BATCH: webhook management on an interactive path is not deferrable bulk.+ response = github_request(+ "GET",+ f"{GITHUB_BASE_URL}/repos/{repo}/hooks?per_page=100",+ source="warehouse",+ headers=_get_headers(token),+ installation_id=installation_id,+ priority=Priority.NORMAL,+ timeout=30,+ session=make_tracked_session(),)+ raise_if_github_rate_limited(response)+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError):+ return None, "GitHub rate limit reached while listing repository webhooks; please retry shortly."except requests.exceptions.RequestException as e:return None, str(e)@@ -1010,18 +1080,22 @@ def _match_hook_by_url(hooks: list[dict[str, Any]], webhook_url: str) -> dict[streturn None-def _find_repo_hook_id(token: str, repo: str, webhook_url: str) -> tuple[int | None, str | None]:+def _find_repo_hook_id(+ token: str, repo: str, webhook_url: str, egress_identity: GithubEgressIdentity | None = None+) -> tuple[int | None, str | None]:"""Return (hook_id, error). Matches on config.url == webhook_url."""- hooks, error = _list_repo_hooks(token, repo)+ hooks, error = _list_repo_hooks(token, repo, egress_identity)if error is not None:return None, errorhook = _match_hook_by_url(hooks or [], webhook_url)return (hook.get("id") if hook else None), None-def delete_repo_webhook(token: str, repo: str, webhook_url: str) -> WebhookDeletionResult:+def delete_repo_webhook(+ token: str, repo: str, webhook_url: str, egress_identity: GithubEgressIdentity | None = None+) -> WebhookDeletionResult:"""Find the repo webhook matching webhook_url and DELETE /repos/{repo}/hooks/{id}."""- hook_id, error = _find_repo_hook_id(token, repo, webhook_url)+ hook_id, error = _find_repo_hook_id(token, repo, webhook_url, egress_identity)if error == "permission":return WebhookDeletionResult(success=False,@@ -1056,9 +1130,83 @@ def delete_repo_webhook(token: str, repo: str, webhook_url: str) -> WebhookDelet)-def get_repo_webhook_info(token: str, repo: str, webhook_url: str) -> ExternalWebhookInfo:+def _webhook_update_permission_result(events: list[str]) -> WebhookSyncResult:+ return WebhookSyncResult(+ success=False,+ error=(+ f"Your GitHub token lacks {_WEBHOOK_PERMISSION_HINT} needed to update the repository "+ f"webhook. Add it and reconnect, or add these events to the webhook manually: {', '.join(events)}."+ ),+ )+++def update_repo_webhook(+ token: str, repo: str, webhook_url: str, events: list[str], egress_identity: GithubEgressIdentity | None = None+) -> WebhookSyncResult:+ """Add ``events`` to the repo webhook matching ``webhook_url``, writing only on drift.++ Additive on purpose: the PATCH sends the union of current and desired events, so events the+ user subscribed themselves are never dropped. Permission errors return a failed (not raised)+ result so schema-enable can proceed with a warning instead of hard-failing."""+ if not events:+ return WebhookSyncResult(success=True)++ hooks, error = _list_repo_hooks(token, repo, egress_identity)+ if error == "permission":+ return _webhook_update_permission_result(events)+ if error is not None:+ return WebhookSyncResult(success=False, error=f"Failed to update webhook events: {error}")++ hook = _match_hook_by_url(hooks or [], webhook_url)+ if hook is None:+ # No matching webhook, so nothing to reconcile (creation is handled elsewhere). Same as Stripe.+ return WebhookSyncResult(success=True)++ current = set(hook.get("events") or [])+ # A "*" subscription already covers everything.+ if "*" in current or all(event in current for event in events):+ return WebhookSyncResult(success=True)++ merged = sorted(current | set(events))+ try:+ # Gated + recorded transport, like the data plane and the org permission probe. NORMAL, not+ # BATCH: a single reconcile write on a schema-enable path is not deferrable bulk. A rate+ # limit must be told apart from a permission 403 here, or a throttled reconcile would tell+ # the user their token lacks webhook permissions.+ response = github_request(+ "PATCH",+ f"{GITHUB_BASE_URL}/repos/{repo}/hooks/{hook['id']}",+ source="warehouse",+ headers=_get_headers(token),+ installation_id=egress_identity.installation_id if egress_identity is not None else None,+ priority=Priority.NORMAL,+ timeout=30,+ session=make_tracked_session(),+ json={"events": merged},+ )+ raise_if_github_rate_limited(response)+ except (GitHubEgressBudgetExhausted, GitHubRateLimitError):+ return WebhookSyncResult(+ success=False,+ error="GitHub rate limit reached while updating webhook events; it will be retried on the next schema update.",+ )+ except requests.exceptions.RequestException as e:+ return WebhookSyncResult(success=False, error=f"Failed to update webhook events: {e}")++ if response.ok:+ return WebhookSyncResult(success=True)+ if _is_repo_hook_permission_error(response):+ return _webhook_update_permission_result(events)+ return WebhookSyncResult(+ success=False, error=f"Failed to update webhook events: {response.status_code} {response.text}"+ )+++def get_repo_webhook_info(+ token: str, repo: str, webhook_url: str, egress_identity: GithubEgressIdentity | None = None+) -> ExternalWebhookInfo:"""List repo webhooks via GET /repos/{repo}/hooks and match config.url == webhook_url."""- hooks, error = _list_repo_hooks(token, repo)+ hooks, error = _list_repo_hooks(token, repo, egress_identity)if error == "permission":return ExternalWebhookInfo(exists=False,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.pyindex b2910dd0fabf..f32c2919c9f3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/settings.py@@ -98,6 +98,52 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {default_incremental_field="updated_at",sort_mode="desc", # Use descending sort to enable incremental sync),+ "reviews": GithubEndpointConfig(+ name="reviews",+ # Child of pull_requests: {pull_number} is filled per parent PR during fan-out. GitHub has no+ # repo-wide reviews list, so review metrics (reviews per PR, time-to-first-review, approval+ # latency) can only be assembled by fanning out over pull requests one at a time.+ path="/repos/{repository}/pulls/{pull_number}/reviews",+ partition_key="submitted_at", # Immutable once submitted; non-null after the PENDING filter below.+ incremental_fields=[+ {+ "label": "submitted_at",+ "type": IncrementalFieldType.DateTime,+ "field": "submitted_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="submitted_at",+ # Review ids are globally unique, so no composite key is needed even though reviews are a+ # fan-out child (the composite-key rule only applies to children whose id is unique just+ # within a parent, like team_members).+ primary_key="id",+ sort_mode="desc", # Rows land parent-newest-first, same as workflow_jobs.+ fan_out_parent="pull_requests",+ fan_out_path_param="pull_number",+ fan_out_parent_field="number",+ # The raw review only carries pull_request_url, so inject the PR number for trivial attribution+ # joins against the pull_requests table.+ fan_out_include_parent_fields={"number": "pr_number"},+ # The parent walk bounds on the PR's updated_at (the parent's own default cursor); the+ # invariant making that sound against the submitted_at watermark is documented at+ # parent_cursor_field in github.py.+ # One /reviews call per PR: any poll backfill re-fans every PR bumped for any reason, and a+ # historical crawl is one request per PR over the repo's whole life. So poll does no+ # backfill: the pull_request_review webhook is the source of truth for reviews, and the+ # poll only re-fans the tiny window since the latest synced review. Repos that want history+ # should run a deliberate one-off backfill, not pay for it on every connect.+ initial_lookback_days=0,+ # A review can emit several webhook events sharing an id (submitted, then edited or+ # dismissed) and the delta merge doesn't dedupe within a batch, so collapse each batch to+ # one row per id. submitted_at is constant across those events, so they always tie; the+ # dedupe transformer breaks ties by keeping the later-arriving row (rows arrive in+ # delivery order), so a submit followed by a dismissal in one drain keeps the dismissal.+ version_keys=["submitted_at"],+ # Reviews need only the repo Pull requests read grant the source already validates at+ # create, unlike the org-scoped teams tables, so leave the table selectable by default.+ should_sync_default=True,+ ),"commits": GithubEndpointConfig(name="commits",path="/repos/{repository}/commits",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.pyindex 88592fd209e6..5230b5b6f478 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/source.py@@ -29,6 +29,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basWebhookCreationResult,WebhookDeletionResult,WebhookSource,+ WebhookSyncResult,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,@@ -48,6 +49,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.gitdelete_repo_webhook,get_repo_webhook_info,github_source,+ update_repo_webhook,validate_credentials as validate_github_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import (@@ -62,6 +64,7 @@ from products.warehouse_sources.backend.types import ExternalDataSourceTypeGITHUB_WEBHOOK_RESOURCE_MAP: dict[str, str] = {"workflow_jobs": "workflow_job","workflow_runs": "workflow_run",+ "reviews": "pull_request_review",}@@ -159,7 +162,7 @@ class GithubSource(3. Paste the webhook URL shown below into the **Payload URL** field4. Set **Content type** to **application/json**5. Enter a **Secret** and add the same value to the **Signing secret** field below-6. Under **Which events would you like to trigger this webhook?**, choose **Let me select individual events** and tick **Workflow jobs** and **Workflow runs**+6. Under **Which events would you like to trigger this webhook?**, choose **Let me select individual events** and tick **Workflow jobs**, **Workflow runs**, and **Pull request reviews**7. Click **Add webhook**If automatic creation failed, your token needs webhook permissions — the **admin:repo_hook** scope on a classic token, or **Repository webhooks: read and write** on a fine-grained token. Add it and reconnect, or set the webhook up manually using the steps above.""",@@ -248,9 +251,9 @@ If automatic creation failed, your token needs webhook permissions — the **admdef _schema_for_endpoint(endpoint: str) -> SourceSchema:webhook_capable = endpoint in GITHUB_WEBHOOK_RESOURCE_MAP# An endpoint whose poll does no first-sync backfill (initial_lookback_days == 0,- # i.e. workflow_jobs) can only ever be populated by the webhook — the per-run- # fan-out is too expensive to backfill at run volume. Offer it as webhook-only so- # users can't pick a poll mode that would sync an empty table forever. workflow_runs+ # i.e. workflow_jobs and reviews) can only ever be populated by the webhook: the+ # per-parent fan-out is too expensive to backfill at volume. Offer it as webhook-only+ # so users can't pick a poll mode that would sync an empty table forever. workflow_runs# keeps its poll backfill; the webhook just replaces re-polling for it.webhook_only = webhook_capable and GITHUB_ENDPOINTS[endpoint].initial_lookback_days == 0supports_poll = bool(INCREMENTAL_FIELDS.get(endpoint)) and not webhook_only@@ -352,20 +355,47 @@ If automatic creation failed, your token needs webhook permissions — the **adm# hook's config.secret, and return it via extra_inputs so it lands on the hog function for# signature verification. (Contrast Stripe, which generates and returns its own secret.)secret = secrets.token_hex(32)- # Always subscribe to the full workflow event pair, not just the enabled schemas: jobs fan- # out under runs, so the two travel together and we want both regardless of which is synced.+ # Always subscribe to every webhook-capable event, not just the enabled schemas: jobs fan+ # out under runs so the workflow pair travels together, and an unmapped event no-ops in the+ # hog function anyway, so over-subscribing is harmless while enabling a table later is free.events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []return create_repo_webhook(access_token, config.repository, webhook_url, events, secret=secret)+ def sync_webhook_events(+ self,+ config: GithubSourceConfig,+ webhook_url: str,+ team_id: int,+ eligible_schema_names: list[str],+ ) -> WebhookSyncResult:+ access_token = self._get_access_token(config, team_id)+ # Every mapped event, not just the enabled schemas': mirrors create_webhook's stance+ # (over-subscribing is harmless, unmapped events no-op in the hog function) and auto-heals+ # webhooks created before GITHUB_WEBHOOK_RESOURCE_MAP gained new events. Thread the+ # installation identity so the hook list and PATCH draw from the same shared egress+ # budget as the data plane; PAT sources resolve to an empty identity (record-only).+ desired_events = self.get_desired_webhook_events(config, list(GITHUB_WEBHOOK_RESOURCE_MAP.keys())) or []+ return update_repo_webhook(+ access_token,+ config.repository,+ webhook_url,+ desired_events,+ egress_identity=self._egress_identity(config, team_id),+ )+def delete_webhook(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:access_token = self._get_access_token(config, team_id)- return delete_repo_webhook(access_token, config.repository, webhook_url)+ return delete_repo_webhook(+ access_token, config.repository, webhook_url, egress_identity=self._egress_identity(config, team_id)+ )def get_external_webhook_info(self, config: GithubSourceConfig, webhook_url: str, team_id: int) -> ExternalWebhookInfo:access_token = self._get_access_token(config, team_id)- return get_repo_webhook_info(access_token, config.repository, webhook_url)+ return get_repo_webhook_info(+ access_token, config.repository, webhook_url, egress_identity=self._egress_identity(config, team_id)+ )def source_for_pipeline(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_reviews.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_reviews.pynew file mode 100644index 000000000000..a2300ea249de--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_reviews.py@@ -0,0 +1,165 @@+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest import mock++import pyarrow as pa++from products.warehouse_sources.backend.temporal.data_imports.sources.github import github+++def _response(rows: list[dict[str, Any]], next_url: str | None = None) -> mock.Mock:+ response = mock.Mock()+ response.json.return_value = rows+ response.headers = {"Link": f'<{next_url}>; rel="next"'} if next_url else {}+ return response+++def _no_resume() -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = False+ return manager+++def _run_reviews_fan_out(+ responses_by_url: dict[str, mock.Mock], **incremental: Any+) -> tuple[list[dict[str, Any]], list[str]]:+ calls: list[str] = []++ def fetch_page(url: str, *_args: Any, **_kwargs: Any) -> mock.Mock:+ calls.append(url)+ # Longest-prefix match so a PR's /reviews path never routes to the /pulls list.+ for needle in sorted(responses_by_url, key=len, reverse=True):+ if needle in url:+ return responses_by_url[needle]+ raise AssertionError(f"Unexpected URL requested: {url}")++ with mock.patch.object(github, "_fetch_page", side_effect=fetch_page):+ tables = list(+ github.get_rows(+ personal_access_token="tok",+ repository="acme/widgets",+ endpoint="reviews",+ logger=mock.Mock(),+ resumable_source_manager=_no_resume(),+ **incremental,+ )+ )++ rows: list[dict[str, Any]] = []+ for table in tables:+ assert isinstance(table, pa.Table)+ rows.extend(table.to_pylist())+ return rows, calls+++def test_reviews_fan_out_drops_pending_and_injects_pr_number() -> None:+ # PENDING reviews come back with submitted_at=null and must be dropped before rows leave the+ # fan-out walk, otherwise a null lands in the partition/cursor column. This also guards that the+ # item filter runs on the fan-out path (not just the top-level path), and that each surviving+ # review carries its PR number injected from the parent.+ responses = {+ "/pulls/10/reviews": _response(+ [+ {"id": 500, "state": "APPROVED", "submitted_at": "2026-01-20T10:00:00Z", "user": {"login": "ada"}},+ {"id": 501, "state": "PENDING", "submitted_at": None, "user": {"login": "self"}},+ {+ "id": 502,+ "state": "CHANGES_REQUESTED",+ "submitted_at": "2026-01-21T10:00:00Z",+ "user": {"login": "grace"},+ },+ ]+ ),+ "/pulls": _response([{"id": 10, "number": 10, "updated_at": "2026-01-30T10:00:00Z"}]),+ }++ rows, _calls = _run_reviews_fan_out(responses)++ assert [row["id"] for row in rows] == [500, 502]+ assert all(row["pr_number"] == 10 for row in rows)+ # Review fields pass through untouched (scalar columns; nested structs like user are+ # JSON-serialized by the pipeline on write, so don't pin their shape here).+ assert [row["state"] for row in rows] == ["APPROVED", "CHANGES_REQUESTED"]+ assert rows[0]["submitted_at"] == "2026-01-20T10:00:00Z"+++def test_reviews_parent_walk_bounds_on_pr_updated_at_not_submitted_at() -> None:+ # The child incremental field is submitted_at, which pull requests do not carry. The parent walk+ # must bound on the PR's updated_at instead. With a watermark set, a PR whose updated_at predates+ # it is skipped (no /reviews request), and a PR above it is fanned out. If the parent-cursor+ # decoupling regressed, the walk would read parent["submitted_at"] = None, skip nothing, and fan+ # out every PR. This pins that it reads updated_at.+ watermark = datetime(2026, 1, 25, tzinfo=UTC)+ responses = {+ "/pulls/11/reviews": _response(+ [{"id": 600, "state": "APPROVED", "submitted_at": "2026-01-28T10:00:00Z", "user": {"login": "ada"}}]+ ),+ "/pulls/12/reviews": _response(+ [{"id": 601, "state": "APPROVED", "submitted_at": "2026-01-10T10:00:00Z", "user": {"login": "bob"}}]+ ),+ # PR 11 updated after the watermark; PR 12 updated before it. Newest-first (desc) order.+ "/pulls": _response(+ [+ {"id": 11, "number": 11, "updated_at": "2026-01-28T10:00:00Z"},+ {"id": 12, "number": 12, "updated_at": "2026-01-20T10:00:00Z"},+ ]+ ),+ }++ rows, calls = _run_reviews_fan_out(+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ incremental_field="submitted_at",+ )++ assert [row["id"] for row in rows] == [600]+ assert any("/pulls/11/reviews" in c for c in calls)+ assert not any("/pulls/12/reviews" in c for c in calls)+++def test_reviews_parent_walk_requests_pull_requests_sorted_updated_desc() -> None:+ # The parent list URL must request pull_requests sorted by updated descending once a cutoff+ # exists, so the desc early-stop bounding is correct. Without the sort the PRs would arrive in+ # GitHub's default created-asc order and _should_stop_desc would halt on the first old row,+ # dropping newer PRs.+ watermark = datetime(2026, 1, 25, tzinfo=UTC)+ responses = {+ "/pulls/11/reviews": _response(+ [{"id": 600, "state": "APPROVED", "submitted_at": "2026-01-28T10:00:00Z", "user": {"login": "ada"}}]+ ),+ "/pulls": _response([{"id": 11, "number": 11, "updated_at": "2026-01-28T10:00:00Z"}]),+ }++ _rows, calls = _run_reviews_fan_out(+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ incremental_field="submitted_at",+ )++ parent_call = next(c for c in calls if "/pulls?" in c)+ assert "sort=updated" in parent_call+ assert "direction=desc" in parent_call+++ "endpoint,last_value,expected",+ [+ # First incremental sync: no watermark yet, but the lookback floor makes the parent walk+ # descend, so reviews emit newest-first. Declaring asc here would let the pipeline persist+ # the submitted_at watermark per batch and strand older reviews if the backfill is+ # interrupted; desc defers the watermark commit to end of sync.+ ("reviews", None, "desc"),+ ("reviews", datetime(2026, 1, 25, tzinfo=UTC), "desc"),+ # Top-level endpoints still start asc on the first sync (stable created-asc pagination).+ ("issues", None, "asc"),+ ],+)+def test_resolve_sort_mode_matches_fan_out_emission_order(+ endpoint: str, last_value: datetime | None, expected: str+) -> None:+ config = github.GITHUB_ENDPOINTS[endpoint]+ assert github._resolve_sort_mode(config, endpoint, True, last_value) == expecteddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.pyindex 511940a5e784..991ee93eb401 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_source_class.py@@ -119,6 +119,26 @@ class TestGithubSource:assert schemas["workflow_jobs"].supports_webhooks is Trueassert all(s.should_sync_default for s in schemas.values() if s.name not in ("teams", "team_members"))+ def test_reviews_schema_is_webhook_only_and_default_on(self):+ # reviews does no poll backfill (zero lookback floor), so it must be offered webhook-only;+ # advertising a poll mode would sync an empty table forever. It needs only the repo grant+ # validated at create, unlike the org tables, so it stays selected by default. If the+ # webhook map entry or the zero floor regressed, these flags would flip and the picker+ # would offer a broken mode.+ config = GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=None, selection="pat", personal_access_token="t"),+ repository="acme/widgets",+ )+ schemas = {s.name: s for s in self.source.get_schemas(config, self.team_id)}++ reviews = schemas["reviews"]+ assert reviews.supports_webhooks is True+ assert reviews.webhook_only is True+ assert reviews.supports_incremental is False+ assert reviews.supports_append is False+ assert reviews.should_sync_default is True+ assert [f["field"] for f in reviews.incremental_fields] == ["submitted_at"]+def test_get_access_token_returns_pat(self):config = GithubSourceConfig(auth_method=GithubAuthMethodConfig(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.pyindex a04d446450d7..7b44c06a7bb0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_teams.py@@ -18,9 +18,10 @@ def _response(rows: list[dict[str, Any]], next_url: str | None = None) -> mock.Mdef _fetch_page_by_url(responses_by_url: dict[str, mock.Mock]):def fetch_page(url: str, *_args: Any, **_kwargs: Any) -> mock.Mock:- for needle, response in responses_by_url.items():+ # Longest needle first, so "/orgs/acme/teams/core/members" never routes to "/orgs/acme/teams".+ for needle in sorted(responses_by_url, key=len, reverse=True):if needle in url:- return response+ return responses_by_url[needle]raise AssertionError(f"Unexpected URL requested: {url}")return fetch_page@@ -142,8 +143,6 @@ def test_team_members_fan_out_injects_parent_fields_and_keeps_composite_rows() -# The same user (id 7) belongs to two teams. Each membership must become its own row carrying# its team's id/slug/name, so ["team_id", "id"] stays unique table-wide. If parent injection or# the per-team fan-out regressed, the user would collapse to one row or lose team context.- # Member URLs first: substring matching would otherwise route them to the teams list, since- # "/orgs/acme/teams" is a prefix of "/orgs/acme/teams/core/members".responses = {"/orgs/acme/teams/core/members": _response([{"id": 7, "login": "ada"}]),"/orgs/acme/teams/growth/members": _response([{"id": 7, "login": "ada"}]),diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_dedupe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_dedupe.pyindex 43e26ec2a25e..a5e2f144dca1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_dedupe.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_dedupe.py@@ -5,6 +5,7 @@ import pyarrow as pafrom products.warehouse_sources.backend.temporal.data_imports.sources.github.github import (_make_webhook_dedupe_transformer,)+from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import GITHUB_ENDPOINTS_JOB_VERSION_KEYS = ["completed_at", "started_at", "created_at"]_JOB_FIELDS: dict[str, pa.DataType] = {@@ -103,3 +104,21 @@ def test_returns_table_unchanged_when_version_columns_absent() -> None:table = pa.table({"id": [1, 1], "status": ["queued", "in_progress"]})out = _make_webhook_dedupe_transformer("id", _JOB_VERSION_KEYS)(table)assert out.num_rows == 2+++def test_reviews_config_collapses_events_sharing_an_id() -> None:+ # A review emits submitted then edited/dismissed events sharing an id; without version_keys on+ # the reviews config the transformer is never built and the delta merge multi-matches the batch.+ # submitted_at is constant across those events, so the tie keeps the later arrival.+ version_keys = GITHUB_ENDPOINTS["reviews"].version_keys+ assert version_keys is not None+ table = pa.table(+ {+ "id": [900, 900],+ "state": ["APPROVED", "DISMISSED"],+ "submitted_at": ["2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"],+ }+ )+ out = _make_webhook_dedupe_transformer("id", version_keys)(table)+ assert out.num_rows == 1+ assert out.column("state")[0].as_py() == "DISMISSED"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.pynew file mode 100644index 000000000000..bf010b8bfde1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_template.py@@ -0,0 +1,97 @@+import json+from typing import Any++from parameterized import parameterized++from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest++from products.warehouse_sources.backend.temporal.data_imports.sources.github.webhook_template import template+++def _review_body(**overrides: Any) -> dict[str, Any]:+ body: dict[str, Any] = {+ "action": "submitted",+ "review": {+ "id": 500,+ "state": "approved",+ "submitted_at": "2026-01-20T10:00:00Z",+ "user": {"login": "ada"},+ },+ "pull_request": {"number": 10, "title": "Fix layout"},+ }+ body.update(overrides)+ return body+++class TestGithubWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):+ template = template++ def createHogGlobals(self, globals=None) -> dict:+ data: dict = {+ "request": {+ "method": "POST",+ "headers": {},+ "body": {},+ "query": {},+ "stringBody": "",+ "ip": "127.0.0.1",+ },+ }+ if globals and globals.get("request"):+ data["request"].update(globals["request"])+ return data++ def _run(self, event_type: str, body: dict[str, Any], schema_mapping: dict[str, str]) -> Any:+ return self.run_function(+ {"signing_secret": "", "bypass_signature_check": True, "schema_mapping": schema_mapping},+ globals={+ "request": {+ "method": "POST",+ "headers": {"x-github-event": event_type},+ "body": body,+ "stringBody": json.dumps(body),+ "query": {},+ }+ },+ )++ def test_pull_request_review_row_is_reshaped_to_poll_shape(self):+ # The review event nests the object under body.review (not the event-type key), uses+ # lowercase states, and carries no PR number on the review itself. The template must+ # reshape it to the polled REST shape or webhook rows diverge from poll rows in the table.+ self._run("pull_request_review", _review_body(), {"pull_request_review": "schema_reviews"})++ row, schema_id = self.mock_produce_to_warehouse_webhooks.call_args.args+ assert schema_id == "schema_reviews"+ assert row["id"] == 500+ assert row["state"] == "APPROVED"+ assert row["pr_number"] == 10+ assert row["submitted_at"] == "2026-01-20T10:00:00Z"+ assert row["user"] == {"login": "ada"}++ @parameterized.expand(+ [+ ("no_submitted_at", _review_body(review={"id": 500, "state": "pending", "submitted_at": None})),+ ("missing_review", {"action": "submitted", "pull_request": {"number": 10}}),+ ("missing_pull_request", {"action": "submitted", "review": {"id": 500, "state": "approved"}}),+ ]+ )+ def test_incomplete_review_payload_is_skipped_with_200(self, _name: str, body: dict[str, Any]):+ res = self._run("pull_request_review", body, {"pull_request_review": "schema_reviews"})++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_workflow_job_row_lands_unchanged(self):+ job = {"id": 1, "status": "completed", "conclusion": "success"}+ self._run("workflow_job", {"action": "completed", "workflow_job": job}, {"workflow_job": "schema_jobs"})++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(job, "schema_jobs")++ def test_unmapped_event_type_no_ops(self):+ # Sources whose schema_mapping predates the pull_request_review entry must 200-skip the+ # event, not error, so enabling the webhook event repo-wide is safe for old deployments.+ res = self._run("pull_request_review", _review_body(), {"workflow_job": "schema_jobs"})++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/webhook_template.pyindex 32ef48b56c7b..fd913181f978 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/webhook_template.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/webhook_template.py@@ -84,6 +84,41 @@ if (empty(schemaId)) {// nested webhook object matches the REST "list jobs for a workflow run" response shape.let row := request.body?.[eventType]+// pull_request_review does not nest the object under the event-type key: the review is at+// body.review and its PR at body.pull_request. Reshape so webhook rows match poll rows, which+// carry pr_number injected from the parent PR. The source-webhooks consumer substitutes the+// current template bytecode by template_id at request time, so existing functions run this code+// too; a source whose schema_mapping predates an event type no-ops on it above.+if (eventType = 'pull_request_review') {+ let review := request.body?.review+ let pullRequest := request.body?.pull_request+ if (empty(review) or empty(pullRequest)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No review or pull_request object in payload, skipping'+ }+ }+ }+ // The poll path drops reviews without submitted_at (unsubmitted drafts); mirror it so+ // the partition/cursor column stays non-null.+ if (empty(review?.submitted_at)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'Review has no submitted_at, skipping'+ }+ }+ }+ // REST returns uppercase review states ('APPROVED') while webhook payloads use lowercase+ // ('approved'); normalize to the REST shape so a fallback poll never mixes casings in one column.+ if (not empty(review?.state)) {+ review.state := upper(review.state)+ }+ review.pr_number := pullRequest?.number+ row := review+}+if (empty(row)) {return {'httpResponse': {@@ -117,7 +152,7 @@ produceToWarehouseWebhooks(row, schemaId)""","type": "json","key": "schema_mapping","label": "Schema mapping",- "description": "Maps GitHub event types (workflow_job, workflow_run) to ExternalDataSchema IDs",+ "description": "Maps GitHub event types (workflow_job, workflow_run, pull_request_review) to ExternalDataSchema IDs","required": True,"secret": False,"hidden": True,diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.pyindex 6e386230c75b..18c5d33bec7d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/github/test_github_source.py@@ -14,12 +14,14 @@ from tenacity import Future, RetryCallStatefrom posthog.egress.github.transport import GitHubRateLimitErrorfrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import WebhookSyncResultfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (GithubAuthMethodConfig,GithubSourceConfig,)from products.warehouse_sources.backend.temporal.data_imports.sources.github.github import (GITHUB_MAX_RETRY_AFTER_SECONDS,+ GithubEgressIdentity,GithubResumeConfig,GithubRetryableError,_build_initial_params,@@ -38,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.git_should_stop_desc,get_rows,github_source,+ update_repo_webhook,validate_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import GITHUB_ENDPOINTS@@ -1407,6 +1410,7 @@ class TestGithubWebhookSource:assert self.source.webhook_resource_map == {"workflow_jobs": "workflow_job","workflow_runs": "workflow_run",+ "reviews": "pull_request_review",}def test_webhook_template_identity(self) -> None:@@ -1415,10 +1419,10 @@ class TestGithubWebhookSource:assert template.id == "template-warehouse-source-github"assert template.type == "warehouse_source_webhook"- def test_get_schemas_marks_only_workflow_schemas_webhook_capable(self) -> None:+ def test_get_schemas_marks_only_mapped_schemas_webhook_capable(self) -> None:schemas = self.source.get_schemas(_pat_config(), team_id=1)webhook_capable = {s.name for s in schemas if s.supports_webhooks}- assert webhook_capable == {"workflow_jobs", "workflow_runs"}+ assert webhook_capable == {"workflow_jobs", "workflow_runs", "reviews"}def test_workflow_jobs_is_webhook_only_but_workflow_runs_keeps_poll(self) -> None:# workflow_jobs does no poll backfill (zero floor), so it must not be offered as a@@ -1439,7 +1443,11 @@ class TestGithubWebhookSource:@parameterized.expand([- ("both", ["workflow_jobs", "workflow_runs"], ["workflow_job", "workflow_run"]),+ (+ "all_webhook_schemas",+ ["workflow_jobs", "workflow_runs", "reviews"],+ ["workflow_job", "workflow_run", "pull_request_review"],+ ),("jobs_only", ["workflow_jobs"], ["workflow_job"]),("drops_non_webhook_schemas", ["workflow_jobs", "issues", "commits"], ["workflow_job"]),]@@ -1486,10 +1494,25 @@ class TestGithubWebhookSource:assert result.error is not Noneassert "admin:repo_hook" in result.error+ @staticmethod+ def _hook_session(list_response: mock.Mock, patch_response: mock.Mock | None = None) -> mock.Mock:+ # The hook list rides github_request, which sends via session.request(method, url, ...);+ # route by method so a stray write (e.g. a PATCH on a no-drift path) fails loudly.+ session = mock.Mock()++ def route(method: str, url: str, **kwargs: Any) -> mock.Mock:+ if method == "GET":+ return list_response+ if method == "PATCH" and patch_response is not None:+ return patch_response+ raise AssertionError(f"Unexpected {method} request: {url}")++ session.request.side_effect = route+ return session+def test_delete_webhook_lists_then_deletes_matching_hook(self) -> None:webhook_url = "https://app.posthog.com/webhook"- session = mock.Mock()- session.get.return_value = _make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}])+ session = self._hook_session(_make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}]))session.delete.return_value = _make_response(status=204)with mock.patch(@@ -1504,18 +1527,19 @@ class TestGithubWebhookSource:def test_get_external_webhook_info_reports_existing_hook(self) -> None:webhook_url = "https://app.posthog.com/webhook"- session = mock.Mock()- session.get.return_value = _make_response(- status=200,- body=[- {- "id": 42,- "active": True,- "events": ["workflow_job", "workflow_run"],- "config": {"url": webhook_url},- "created_at": "2026-01-01T00:00:00Z",- }- ],+ session = self._hook_session(+ _make_response(+ status=200,+ body=[+ {+ "id": 42,+ "active": True,+ "events": ["workflow_job", "workflow_run"],+ "config": {"url": webhook_url},+ "created_at": "2026-01-01T00:00:00Z",+ }+ ],+ ))with mock.patch(@@ -1533,8 +1557,7 @@ class TestGithubWebhookSource:# The hook is found in the list but DELETE races a concurrent removal and# 404s — the desired end state, so it must not surface as a permission error.webhook_url = "https://app.posthog.com/webhook"- session = mock.Mock()- session.get.return_value = _make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}])+ session = self._hook_session(_make_response(status=200, body=[{"id": 42, "config": {"url": webhook_url}}]))session.delete.return_value = _make_response(status=404, body={"message": "Not Found"})with mock.patch(@@ -1550,13 +1573,14 @@ class TestGithubWebhookSource:# A hook whose `config` is present-but-null must be skipped, not crash the# match loop — the real hook still resolves.webhook_url = "https://app.posthog.com/webhook"- session = mock.Mock()- session.get.return_value = _make_response(- status=200,- body=[- {"id": 7, "config": None},- {"id": 42, "active": True, "events": ["workflow_job"], "config": {"url": webhook_url}},- ],+ session = self._hook_session(+ _make_response(+ status=200,+ body=[+ {"id": 7, "config": None},+ {"id": 42, "active": True, "events": ["workflow_job"], "config": {"url": webhook_url}},+ ],+ ))with mock.patch(@@ -1568,6 +1592,149 @@ class TestGithubWebhookSource:assert info.exists is Trueassert info.url == webhook_url+ def test_sync_webhook_events_targets_every_mapped_event(self) -> None:+ # Reconciliation must push the full event map, not just the enabled schema's event;+ # otherwise a webhook created before the map grew never gains the new events. It must also+ # carry the resolved egress identity so the hook list and PATCH draw from the shared+ # installation budget instead of running identity-blind.+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.source.update_repo_webhook",+ return_value=WebhookSyncResult(success=True),+ ) as update:+ result = self.source.sync_webhook_events(+ _pat_config(), "https://app.posthog.com/webhook", team_id=1, eligible_schema_names=["reviews"]+ )++ assert result.success is True+ _token, repo, url, events = update.call_args.args+ assert repo == "owner/repo"+ assert url == "https://app.posthog.com/webhook"+ assert sorted(events) == ["pull_request_review", "workflow_job", "workflow_run"]+ # A PAT config resolves to the empty record-only identity; the point pinned here is that+ # the identity is resolved and passed at all.+ assert update.call_args.kwargs["egress_identity"] == GithubEgressIdentity()++ def test_update_repo_webhook_merges_events_additively(self) -> None:+ # The PATCH must send the union of current and desired events against the matching hook,+ # through the gated egress transport. Replacing instead of merging would drop events the+ # user subscribed themselves (push).+ webhook_url = "https://app.posthog.com/webhook"+ session = self._hook_session(+ _make_response(+ status=200,+ body=[{"id": 42, "events": ["workflow_job", "workflow_run", "push"], "config": {"url": webhook_url}}],+ ),+ patch_response=_make_response(status=200, body={"id": 42}),+ )++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",+ return_value=session,+ ):+ result = update_repo_webhook(+ "tok", "owner/repo", webhook_url, ["workflow_job", "workflow_run", "pull_request_review"]+ )++ assert result.success is True+ patch_calls = [c for c in session.request.call_args_list if c.args[0] == "PATCH"]+ assert len(patch_calls) == 1+ assert "/repos/owner/repo/hooks/42" in patch_calls[0].args[1]+ sent_events = patch_calls[0].kwargs["json"]["events"]+ assert sent_events == ["pull_request_review", "push", "workflow_job", "workflow_run"]++ @parameterized.expand(+ [+ ("on_the_hook_list", True),+ ("on_the_patch", False),+ ]+ )+ def test_update_repo_webhook_rate_limit_is_not_a_permission_error(self, _name: str, on_list: bool) -> None:+ # A rate-limited 403 carries limit markers; misreading it as a missing admin:repo_hook+ # grant would send the user off to rotate a token that is fine. Both request stages+ # must classify the rate limit before the permission mapping.+ webhook_url = "https://app.posthog.com/webhook"+ rate_limited = _make_response(status=403, body={"message": "API rate limit exceeded"})+ rate_limited.headers = {"x-ratelimit-remaining": "0"}+ rate_limited.text = "API rate limit exceeded"+ hooks_list = _make_response(+ status=200, body=[{"id": 42, "events": ["workflow_job"], "config": {"url": webhook_url}}]+ )+ session = (+ self._hook_session(rate_limited) if on_list else self._hook_session(hooks_list, patch_response=rate_limited)+ )++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",+ return_value=session,+ ):+ result = update_repo_webhook("tok", "owner/repo", webhook_url, ["pull_request_review"])++ assert result.success is False+ assert result.error is not None+ assert "rate limit" in result.error+ assert "admin:repo_hook" not in result.error++ @parameterized.expand(+ [+ ("already_subscribed", ["workflow_job", "workflow_run", "pull_request_review"]),+ ("wildcard", ["*"]),+ ]+ )+ def test_update_repo_webhook_no_ops_without_drift(self, _name: str, current_events: list[str]) -> None:+ # Reconciliation runs on every schema enable, so it must not PATCH when nothing is+ # missing (or "*" already covers everything); a write per enable would churn the hook.+ # The routed session has no PATCH response, so a stray write raises.+ webhook_url = "https://app.posthog.com/webhook"+ session = self._hook_session(+ _make_response(status=200, body=[{"id": 42, "events": current_events, "config": {"url": webhook_url}}])+ )++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",+ return_value=session,+ ):+ result = update_repo_webhook("tok", "owner/repo", webhook_url, ["pull_request_review"])++ assert result.success is True+ assert all(call.args[0] == "GET" for call in session.request.call_args_list)++ def test_update_repo_webhook_permission_error_fails_with_hint(self) -> None:+ # A 403 must come back as a failed result naming the missing grant, never raise:+ # reconciliation runs non-fatally after the table is enabled, and a raise would only+ # be swallowed with a generic log instead of the actionable message.+ denied = _make_response(status=403, body={"message": "Forbidden"})+ denied.text = "Forbidden" # no rate-limit markers, so this must map to the grant hint+ session = self._hook_session(denied)++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",+ return_value=session,+ ):+ result = update_repo_webhook(+ "tok", "owner/repo", "https://app.posthog.com/webhook", ["pull_request_review"]+ )++ assert result.success is False+ assert result.error is not None+ assert "admin:repo_hook" in result.error+ assert "pull_request_review" in result.error++ def test_update_repo_webhook_with_no_matching_hook_is_a_no_op(self) -> None:+ # A manually deleted webhook must not fail reconciliation (creation is handled+ # elsewhere); failing here would warn on every schema enable for no reason.+ session = self._hook_session(_make_response(status=200, body=[]))++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",+ return_value=session,+ ):+ result = update_repo_webhook(+ "tok", "owner/repo", "https://app.posthog.com/webhook", ["pull_request_review"]+ )++ assert result.success is True+ assert all(call.args[0] == "GET" for call in session.request.call_args_list)+# A response that raise_if_github_rate_limited classifies as rate limited: 429 is# rate limited regardless of body, 403 only when the body mentions a rate limit.