Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(devex): feed github comment and status tables by webhook (#85381)

Julian Bez2bf6457d53c7
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.py
index 41dbf4665b99..6fd9f25e1279 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
@@ -182,6 +182,7 @@ def _build_initial_params(
params["sort"] = "created"
params["direction"] = "asc"
+ since_capable = endpoint in ("issues", "commits") or config.supports_since_param
if should_use_incremental_field and db_incremental_field_last_value:
formatted_value = _format_incremental_value(db_incremental_field_last_value)
incremental = incremental_field or config.default_incremental_field or "updated_at"
@@ -195,8 +196,18 @@ def _build_initial_params(
)
params["sort"] = sort_field_mapping[incremental]
params["direction"] = config.sort_mode
- if endpoint in ("issues", "commits") or config.supports_since_param:
+ if since_capable:
params["since"] = formatted_value
+ elif should_use_incremental_field and config.initial_lookback_days is not None and since_capable:
+ # First incremental sync with no watermark: floor the backfill with a server-side `since`
+ # window instead of walking the endpoint's whole history, the repo-wide counterpart of the
+ # fan-out parent floor in _fan_out_get_rows. Scoped to the first incremental run on
+ # purpose, because an explicit full refresh should still pull everything, and once a
+ # watermark exists the branch above bounds the read with it. History past the window is a
+ # deliberate one-off backfill, not a connect-time cost. `is not None` keeps the field's
+ # zero contract uniform with the fan-out floor: zero floors at now, so the poll backfills
+ # nothing, rather than reading as "no floor" and walking the whole history.
+ params["since"] = _format_incremental_value(_now_utc() - timedelta(days=config.initial_lookback_days))
return params
@@ -1472,9 +1483,11 @@ def github_source(
# 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
# source batch. Same pattern as the Stripe webhook source.
- # Webhook-capable endpoints all key on a single column; the dedupe transformer
- # collapses one pk column, so pass the first (only) key. Fan-out children with
- # composite keys have no version_keys, so this branch never runs for them.
+ # The dedupe transformer collapses on one pk column, so pass the first key. That is
+ # sound only while every endpoint declaring version_keys keys on a single column:
+ # commit_statuses is webhook-capable with a composite ["commit_sha", "id"] key, and
+ # giving it version_keys would collapse a commit's statuses to one row. Guarded by
+ # test_no_composite_key_endpoint_declares_version_keys.
transformer = (
_make_webhook_dedupe_transformer(
_normalize_primary_key(endpoint_config.primary_key)[0], endpoint_config.version_keys
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.py
index aa57bc49bd70..a3ce9cab5a68 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
@@ -4,7 +4,9 @@ from typing import Literal, Optional
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+# Tests patch fields on these config records, so freezing them is a change of its own. The class
+# stays tracked in dataclass_frozen_baseline.txt for that migration.
+@dataclass # nosemgrep: prefer-frozen-dataclasses -- tests mutate these config records
class GithubEndpointConfig:
name: str
path: str # Path template with {repository}, {organization}, and fan-out placeholders
@@ -49,10 +51,13 @@ class GithubEndpointConfig:
# Hard cap on pages fetched per parent in a fan-out, to bound runaway
# pagination. A structured warning is logged if the cap is reached.
max_pages_per_parent: int = 50
- # First-sync floor: when set, the very first incremental sync only fans out
- # over parents created within this many days, instead of crawling the whole
- # repo history. The webhook carries steady-state, so only the one-off backfill
- # needs a bound; later syncs advance from the stored watermark and ignore this.
+ # First-sync floor: the very first incremental sync only reaches back this many
+ # days instead of crawling the whole repo history. For a fan-out child it bounds
+ # the parent walk; for a repo-wide endpoint with `since` support it becomes a
+ # server-side `since` floor. The webhook carries steady-state, so only the
+ # one-off backfill needs a bound; later syncs advance from the stored watermark
+ # and ignore this. Zero means the poll does no backfill at all, which is what
+ # marks a webhook-capable endpoint webhook-only.
initial_lookback_days: Optional[int] = None
# Steady-state reconciliation for a webhook-fed fan-out child whose events GitHub does not
# always deliver: after each webhook drain, re-fan parents created within this many days so
@@ -471,6 +476,17 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
default_incremental_field="updated_at",
param_style="sorted",
supports_since_param=True,
+ # A comment is editable, so created/edited/deleted deliveries for one id can land in the
+ # same webhook batch. GitHub bumps updated_at on every edit, so it ranks them; the delta
+ # merge does not dedupe within a batch, so without this the row keeps whichever event
+ # happened to arrive last rather than the latest edit.
+ version_keys=["updated_at"],
+ # Bound the bootstrap: without a floor the first sync walks every comment ever written
+ # before webhook mode can activate (webhook_enabled needs initial_sync_complete), which on
+ # a large repo is thousands of requests against the shared budget. Steady state is the
+ # webhook, or a `since`-bounded poll, so only the backfill window is at stake; deeper
+ # history is a deliberate one-off backfill.
+ initial_lookback_days=14,
),
"pull_request_comments": GithubEndpointConfig(
name="pull_request_comments",
@@ -482,6 +498,8 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
default_incremental_field="updated_at",
param_style="sorted",
supports_since_param=True,
+ version_keys=["updated_at"], # Editable, same as issue_comments.
+ initial_lookback_days=14, # Bound the bootstrap, same as issue_comments.
),
"commit_comments": GithubEndpointConfig(
name="commit_comments",
@@ -490,9 +508,12 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
path="/repos/{repository}/comments",
partition_key="created_at",
# Rows come back ordered by ascending id and the endpoint takes no `since` filter or sort,
- # so an incremental sync would still walk every page. Full refresh only.
+ # so an incremental sync would still walk every page. Full refresh only, which is why the
+ # commit_comment webhook matters more here than for the other two comment tables: it is the
+ # only way this table stops re-pulling the whole collection on every sync.
incremental_fields=[],
param_style="plain",
+ version_keys=["updated_at"], # Editable, same as issue_comments.
),
"issue_types": GithubEndpointConfig(
name="issue_types",
@@ -647,13 +668,19 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
# filter=all returns every check run for the ref, not just the latest per check name —
# required for re-run and flake analysis.
extra_params={"filter": "all"},
- # One call per commit, so a first incremental sync would otherwise crawl the repo's entire
- # commit history against a shared, rate-limited budget. Floor it at a recent window; later
- # syncs advance from the watermark. A deliberate full refresh still pulls everything.
- initial_lookback_days=7,
- # A commit-grained fan-out is far more expensive than the repo-wide tables, so leave it
- # deselected and let users opt in rather than paying for it on every default connection.
+ # Webhook-only marker, like reviews: the poll costs one call per commit, so any poll mode
+ # is a per-commit fan-out over a shared, rate-limited budget however tight the window is.
+ # initial_lookback_days == 0 makes source.py offer this schema webhook-only, activates
+ # webhook mode from the first sync, and makes the poll path yield no rows. History, if
+ # wanted, is a deliberate one-off backfill.
+ initial_lookback_days=0,
+ # A busy repo produces check runs at commit x check-name grain, which is far more volume
+ # than most connections want, so leave it deselected and let users opt in.
should_sync_default=False,
+ # A check run emits queued -> in_progress -> completed events sharing an id and carries no
+ # updated_at, so rank by how far the run progressed: completed_at (terminal) outranks
+ # started_at, and both are NULL while queued, so NULLs-last ordering keeps the latest state.
+ version_keys=["completed_at", "started_at"],
),
"commit_statuses": GithubEndpointConfig(
name="commit_statuses",
@@ -670,10 +697,22 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
fan_out_parent="commits",
fan_out_path_param="ref",
fan_out_parent_field="sha",
- # A status carries no sha of its own, so inject the commit it was posted against.
+ # A status carries no sha of its own, so inject the commit it was posted against. The Hog
+ # template fills the same column from the `status` event's top-level `sha`, so webhook rows
+ # carry both halves of the composite key too.
fan_out_include_parent_fields={"sha": "commit_sha"},
- initial_lookback_days=7,
- should_sync_default=False, # Same commit-grained fan-out cost as check_runs.
+ # Webhook-only marker, like check_runs: the poll is a per-commit fan-out, and it also
+ # bounds the parent walk on the commit's immutable created_at with no
+ # fan_out_parent_recency_field, so a status posted after the watermark passed its commit is
+ # never fetched. The `status` webhook carries every status as it is posted, which fixes both.
+ initial_lookback_days=0,
+ # Statuses arrive at commit x context grain on a busy repo, so leave the table deselected
+ # and let users opt in.
+ should_sync_default=False,
+ # No version_keys on purpose: statuses are append-only (a re-run posts a new status id
+ # rather than mutating one), so there is nothing to collapse within a batch. The dedupe
+ # transformer would also be wrong here, because it ranks on the first primary-key column
+ # only, which is commit_sha for this composite key, and would keep one status per commit.
),
# --- Security posture ------------------------------------------------------------------
"code_scanning_alerts": GithubEndpointConfig(
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.py
index aa5912abcac7..9290272562b5 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
@@ -89,13 +89,46 @@ GITHUB_WEBHOOK_RESOURCE_MAP: dict[str, str] = {
# path injects no parent column (check run ids are globally unique), so the webhook row already
# matches the poll row and needs no reshaping.
"check_runs": "check_run",
+ # The one mapped event with no nesting key at all: the status fields sit at the top level of
+ # the body, wrapped in commit/repository/sender/branches objects the poll row never carries.
+ # The template rebuilds the row from the top-level fields and injects commit_sha from the
+ # event's `sha`, which is the column the poll fan-out copies off the parent commit.
+ "commit_statuses": "status",
+ # The three comment tables all nest the row under `comment`, and GitHub's comment objects are
+ # the same shape its REST list endpoints return, so the template only unwraps them. Their
+ # initial_lookback_days stays non-zero, which leaves them poll-capable: the poll bootstraps the
+ # table and the webhook takes over once initial_sync_complete is set.
+ "issue_comments": "issue_comment",
+ "pull_request_comments": "pull_request_review_comment",
+ "commit_comments": "commit_comment",
}
+# GitHub's own checkbox label for each mapped event, used to build the manual webhook setup
+# instructions. Deriving that list from the map keeps it from drifting: it already lost `Check
+# runs` once, which silently left manually-created hooks missing a mapped event.
+GITHUB_WEBHOOK_EVENT_LABELS: dict[str, str] = {
+ "workflow_job": "Workflow jobs",
+ "workflow_run": "Workflow runs",
+ "pull_request_review": "Pull request reviews",
+ "deployment": "Deployments",
+ "deployment_status": "Deployment statuses",
+ "check_run": "Check runs",
+ "status": "Statuses",
+ "issue_comment": "Issue comments",
+ "pull_request_review_comment": "Pull request review comments",
+ "commit_comment": "Commit comments",
+}
+
+# Rendered into the manual setup instructions. A mapped event with no label raises on import, so
+# drift fails in CI rather than shipping instructions that miss an event.
+GITHUB_WEBHOOK_EVENT_CHECKLIST: str = "\n".join(
+ f" - {GITHUB_WEBHOOK_EVENT_LABELS[event]}" for event in dict.fromkeys(GITHUB_WEBHOOK_RESOURCE_MAP.values())
+)
+
# Everything else stays poll-only. GitHub does emit events for several of the other tables, but the
-# template lands `body[eventType]` as the row and these nest the object under a different key —
-# `alert` for the code-scanning/Dependabot/secret-scanning alerts, `comment` for issue and review
-# comments, `forkee` for forks, `commit` for statuses — so each needs its own reshaping branch
-# before its webhook rows would match what the poll path writes.
+# template lands `body[eventType]` as the row and these nest the object under a different key
+# (`alert` for the code-scanning/Dependabot/secret-scanning alerts, `forkee` for forks), so each
+# needs its own reshaping branch before its webhook rows would match what the poll path writes.
@SourceRegistry.register
@@ -210,14 +243,15 @@ class GithubSource(
),
],
),
- webhookSetupCaption="""To set up the webhook manually, repeat these steps for **each selected repository**, using the **same Secret** every time:
+ webhookSetupCaption=f"""To set up the webhook manually, repeat these steps for **each selected repository**, using the **same Secret** every time:
1. Go to the repository's **Settings > Webhooks** on GitHub
2. Click **Add webhook**
3. Paste the webhook URL shown below into the **Payload URL** field
4. 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**, **Workflow runs**, **Pull request reviews**, **Deployments**, and **Deployment statuses**
+6. Under **Which events would you like to trigger this webhook?**, choose **Let me select individual events**, then tick:
+{GITHUB_WEBHOOK_EVENT_CHECKLIST}
7. Click **Add webhook**
If automatic creation failed with a permissions error, the fix depends on how you connected:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py
index 7851fbb2ec2d..f1412e5a2346 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_repository_endpoints.py
@@ -1,5 +1,5 @@
import json
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any
import pytest
@@ -152,10 +152,50 @@ class TestListParams:
)
assert ("since" in params) is expects_since
+ if expects_since:
+ # The watermark, not the first-sync lookback floor, must bound a sync that has one.
+ assert params["since"] == github._format_incremental_value(_CUTOFF)
assert params["sort"] == incremental_field.removesuffix("_at")
assert params["direction"] == GITHUB_ENDPOINTS[endpoint].sort_mode
assert "state" not in params
+ @parameterized.expand(
+ [
+ ("issue_comments",),
+ ("pull_request_comments",),
+ ]
+ )
+ def test_first_sync_since_floor(self, endpoint: str) -> None:
+ # Without the floor the bootstrap walks every comment ever written before webhook mode can
+ # activate, so dropping it turns connect-time into a full-history crawl on large repos.
+ lookback = GITHUB_ENDPOINTS[endpoint].initial_lookback_days
+ assert lookback
+
+ params = github._build_initial_params(
+ GITHUB_ENDPOINTS[endpoint],
+ endpoint,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="updated_at",
+ )
+
+ floor = datetime.fromisoformat(params["since"].replace("Z", "+00:00"))
+ expected = datetime.now(UTC) - timedelta(days=lookback)
+ assert abs((expected - floor).total_seconds()) < 60
+
+ def test_full_refresh_ignores_since_floor(self) -> None:
+ # An explicit full refresh must still pull the whole history; the floor only bounds the
+ # first incremental run.
+ params = github._build_initial_params(
+ GITHUB_ENDPOINTS["issue_comments"],
+ "issue_comments",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+
+ assert "since" not in params
+
@parameterized.expand(
[
# issue_events and forks answer newest-first whatever we ask for, so reporting "asc" on
diff --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.py
index 723168786912..1a149b5b8c73 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
@@ -396,6 +396,33 @@ class TestGithubSource:
assert schema.supports_incremental is False
assert schema.should_sync_default is True
+ @pytest.mark.parametrize("endpoint", ["check_runs", "commit_statuses"])
+ def test_commit_fan_out_schemas_are_webhook_only(self, endpoint):
+ # Both fan out over commits, so any poll mode costs one API call per commit on every sync
+ # against a shared, rate-limited budget. The zero lookback floor is what stops the picker
+ # from offering that mode; if it regressed, a user could select incremental and a large
+ # repository would pay the per-commit fan-out indefinitely. They stay deselected by
+ # default because of their volume, unlike the deploy and review tables.
+ config = _pat_config("acme/widgets")
+ schema = {s.name: s for s in self.source.get_schemas(config, self.team_id)}[endpoint]
+
+ assert schema.supports_webhooks is True
+ assert schema.webhook_only is True
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.should_sync_default is False
+
+ @pytest.mark.parametrize("endpoint", ["issue_comments", "pull_request_comments", "commit_comments"])
+ def test_comment_schemas_stay_pollable_alongside_the_webhook(self, endpoint):
+ # The comment webhooks are a freshness win, not a load guard: their poll is the bootstrap
+ # feed that fills the table before webhook_enabled can flip (it needs initial_sync_complete),
+ # so giving them a zero lookback floor would strand them empty until the first delivery.
+ config = _pat_config("acme/widgets")
+ schema = {s.name: s for s in self.source.get_schemas(config, self.team_id)}[endpoint]
+
+ assert schema.supports_webhooks is True
+ assert schema.webhook_only is False
+
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_webhook_dedupe.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_dedupe.py
index a5e2f144dca1..82db6fae2643 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
@@ -1,5 +1,7 @@
from typing import Any
+import pytest
+
import pyarrow as pa
from products.warehouse_sources.backend.temporal.data_imports.sources.github.github import (
@@ -106,19 +108,51 @@ def test_returns_table_unchanged_when_version_columns_absent() -> None:
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"],
- }
- )
+ "endpoint,expected_version_keys,version_values",
+ [
+ # A review emits submitted then edited/dismissed events sharing an id, and submitted_at is
+ # constant across them, so the tie keeps the later arrival.
+ ("reviews", ["submitted_at"], {"submitted_at": ["2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"]}),
+ # A comment emits created then edited events sharing an id, and GitHub bumps updated_at on
+ # the edit, so ranking decides rather than arrival order.
+ ("issue_comments", ["updated_at"], {"updated_at": ["2026-01-01T00:00:00Z", "2026-01-01T00:05:00Z"]}),
+ ("pull_request_comments", ["updated_at"], {"updated_at": ["2026-01-01T00:00:00Z", "2026-01-01T00:05:00Z"]}),
+ ("commit_comments", ["updated_at"], {"updated_at": ["2026-01-01T00:00:00Z", "2026-01-01T00:05:00Z"]}),
+ # A check run emits in_progress then completed events sharing an id; completed_at is NULL
+ # until terminal, so NULLs-last ranking keeps the completed row whatever the file order.
+ (
+ "check_runs",
+ ["completed_at", "started_at"],
+ {
+ "completed_at": [None, "2026-01-01T00:05:00Z"],
+ "started_at": ["2026-01-01T00:00:00Z", "2026-01-01T00:00:00Z"],
+ },
+ ),
+ ],
+)
+def test_mutable_endpoint_configs_collapse_events_sharing_an_id(
+ endpoint: str, expected_version_keys: list[str], version_values: dict[str, list[str | None]]
+) -> None:
+ # Without version_keys on the config the transformer is never built, and the delta merge
+ # multi-matches every id that appears twice in one batch.
+ version_keys = GITHUB_ENDPOINTS[endpoint].version_keys
+ assert version_keys == expected_version_keys
+ table = pa.table({"id": [900, 900], "state": ["first", "latest"], **version_values})
+
out = _make_webhook_dedupe_transformer("id", version_keys)(table)
+
assert out.num_rows == 1
- assert out.column("state")[0].as_py() == "DISMISSED"
+ assert out.column("state")[0].as_py() == "latest"
+
+
+def test_no_composite_key_endpoint_declares_version_keys() -> None:
+ # github_source builds the transformer from the FIRST primary-key column only, so a
+ # composite-key endpoint that declared version_keys would collapse every row sharing that
+ # column: commit_statuses keys on ["commit_sha", "id"], so one commit would keep one status.
+ offenders = [
+ name
+ for name, config in GITHUB_ENDPOINTS.items()
+ if config.version_keys and not isinstance(config.primary_key, str)
+ ]
+ assert offenders == []
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_only.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_only.py
index 23788a0cb6e6..259b27096f8f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_only.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_webhook_only.py
@@ -25,7 +25,16 @@ async def _collect(tables: AsyncIterator[pa.Table]) -> list[pa.Table]:
@pytest.mark.parametrize(
- "endpoint", ["workflow_runs", "workflow_jobs", "reviews", "deployments", "deployment_statuses"]
+ "endpoint",
+ [
+ "workflow_runs",
+ "workflow_jobs",
+ "reviews",
+ "deployments",
+ "deployment_statuses",
+ "check_runs",
+ "commit_statuses",
+ ],
)
def test_webhook_only_poll_yields_no_rows_when_webhook_inactive(endpoint: str) -> None:
webhook_source_manager = mock.Mock()
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.py
index 0dbf9ace2d73..db7ff3a0658a 100644
--- 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.py
@@ -23,6 +23,31 @@ def _review_body(**overrides: Any) -> dict[str, Any]:
return body
+_COMMIT_SHA = "0f1e2d3c4b5a69788796a5b4c3d2e1f009182736"
+
+
+def _status_body(**overrides: Any) -> dict[str, Any]:
+ body: dict[str, Any] = {
+ "id": 4100,
+ "sha": _COMMIT_SHA,
+ "name": "acme/widgets",
+ "node_id": "SE_fakecommitstatusnode",
+ "state": "success",
+ "description": "Build passed",
+ "target_url": "https://ci.example.com/builds/4100",
+ "context": "ci/build",
+ "avatar_url": "https://avatars.example.com/u/12",
+ "created_at": "2026-02-01T09:00:00Z",
+ "updated_at": "2026-02-01T09:00:30Z",
+ "commit": {"sha": _COMMIT_SHA, "url": "https://api.example.com/repos/acme/widgets/commits/0f1e2d3c"},
+ "branches": [{"name": "main"}],
+ "repository": {"full_name": "acme/widgets"},
+ "sender": {"login": "ci-bot"},
+ }
+ body.update(overrides)
+ return body
+
+
class TestGithubWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):
template = template
@@ -146,6 +171,65 @@ class TestGithubWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):
assert res.result["httpResponse"]["status"] == 200
self.mock_produce_to_warehouse_webhooks.assert_not_called()
+ def test_status_row_is_rebuilt_from_top_level_body_fields(self):
+ # The status event has no nesting key: its fields sit at the top level of the body next to
+ # commit/repository/sender/branches envelope objects and a `name` holding the repository.
+ # Without the rebuild the row is either empty (there is no body.status) or carries envelope
+ # columns the poll never writes, and commit_sha stays null even though it is the first half
+ # of the table's composite primary key, so every later merge multi-matches.
+ self._run("status", _status_body(), {"status": "schema_commit_statuses"})
+
+ row, schema_id = self.mock_produce_to_warehouse_webhooks.call_args.args
+ assert schema_id == "schema_commit_statuses"
+ assert row == {
+ "id": 4100,
+ "node_id": "SE_fakecommitstatusnode",
+ "state": "success",
+ "description": "Build passed",
+ "target_url": "https://ci.example.com/builds/4100",
+ "context": "ci/build",
+ "avatar_url": "https://avatars.example.com/u/12",
+ "creator": {"login": "ci-bot"},
+ "created_at": "2026-02-01T09:00:00Z",
+ "updated_at": "2026-02-01T09:00:30Z",
+ "commit_sha": _COMMIT_SHA,
+ }
+
+ @parameterized.expand(
+ [
+ ("missing_id", {"sha": _COMMIT_SHA, "state": "success"}),
+ ("missing_sha", {"id": 4100, "state": "success"}),
+ ]
+ )
+ def test_status_payload_without_id_or_sha_is_skipped_with_200(self, _name: str, body: dict[str, Any]):
+ # The rebuilt row is a non-empty dict whatever the payload holds, so the shared empty-row
+ # guard below it never fires; without this check a status missing either half of the
+ # composite key would land a row the merge can't match.
+ res = self._run("status", body, {"status": "schema_commit_statuses"})
+
+ assert res.result["httpResponse"]["status"] == 200
+ self.mock_produce_to_warehouse_webhooks.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("issue_comment", {"id": 7010, "body": "Looks good", "issue_url": "https://api.example.com/issues/3"}),
+ (
+ "pull_request_review_comment",
+ {"id": 7011, "body": "Rename this", "path": "src/app.py", "pull_request_review_id": 55},
+ ),
+ ("commit_comment", {"id": 7012, "body": "Nice fix", "commit_id": _COMMIT_SHA}),
+ ]
+ )
+ def test_comment_events_land_the_nested_comment_object(self, event_type: str, comment: dict[str, Any]):
+ # All three comment events nest the row under `comment` rather than the event-type key, so
+ # without the unwrap branch the default lookup finds nothing and every comment delivery
+ # 200-skips: the table silently keeps only whatever the bootstrap poll left behind.
+ body = {"action": "created", "comment": comment, "repository": {"full_name": "acme/widgets"}}
+
+ self._run(event_type, body, {event_type: "schema_comments"})
+
+ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(comment, "schema_comments")
+
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.
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.py
index a7d05045989c..5450851889e7 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
@@ -152,6 +152,46 @@ if (eventType = 'deployment_status') {
row := status
}
+// The status event is the only mapped event with no nesting key: the status fields sit at the top
+// level of the body, alongside commit/repository/sender/branches envelope objects and a `name`
+// holding the repository's full name, none of which the polled row carries. Build the row from the
+// wanted fields rather than deleting the envelope, so the shape is pinned here and a new envelope
+// field GitHub adds can never leak into the table. commit_sha comes from the event's top-level
+// `sha`, matching what the poll fan-out copies off the parent commit. The poll's `creator` maps
+// from the event's `sender`: a status event fires only on status creation, so the sender is the
+// user or app that posted it. The poll's `url` has no equivalent and stays null on webhook rows.
+if (eventType = 'status') {
+ if (empty(request.body?.id) or empty(request.body?.sha)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No status id or commit sha in payload, skipping'
+ }
+ }
+ }
+ row := {
+ 'id': request.body?.id,
+ 'node_id': request.body?.node_id,
+ 'state': request.body?.state,
+ 'description': request.body?.description,
+ 'target_url': request.body?.target_url,
+ 'context': request.body?.context,
+ 'avatar_url': request.body?.avatar_url,
+ 'creator': request.body?.sender,
+ 'created_at': request.body?.created_at,
+ 'updated_at': request.body?.updated_at,
+ 'commit_sha': request.body?.sha
+ }
+}
+
+// The three comment events nest the row under `comment`, not under the event-type key, and the
+// nested object is the same shape the REST list endpoints return, so unwrapping is the whole
+// reshape. Every action is landed, including `deleted`: the warehouse merge only upserts, so
+// there is no way to remove a row, and the created delivery already put it in the table.
+if (eventType in ['issue_comment', 'pull_request_review_comment', 'commit_comment']) {
+ row := request.body?.comment
+}
+
if (empty(row)) {
return {
'httpResponse': {
@@ -185,7 +225,7 @@ produceToWarehouseWebhooks(row, schemaId)""",
"type": "json",
"key": "schema_mapping",
"label": "Schema mapping",
- "description": "Maps GitHub event types to ExternalDataSchema IDs. Keys are either a bare event type (workflow_job, workflow_run, pull_request_review, deployment, deployment_status) for legacy single-repo sources, or 'owner/repo.event_type' for multi-repo sources.",
+ "description": "Maps GitHub event types to ExternalDataSchema IDs. Keys are either a bare event type (workflow_job, workflow_run, and the rest of GITHUB_WEBHOOK_RESOURCE_MAP) for legacy single-repo sources, or 'owner/repo.event_type' for multi-repo sources.",
"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.py
index 9ad8f1cc2832..504b429b1c7b 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
@@ -45,7 +45,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.github.git
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.github.settings import GITHUB_ENDPOINTS
-from products.warehouse_sources.backend.temporal.data_imports.sources.github.source import GithubSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.github.source import (
+ GITHUB_WEBHOOK_EVENT_LABELS,
+ GITHUB_WEBHOOK_RESOURCE_MAP,
+ GithubSource,
+)
def _make_response(status: int = 200, body: Any = None, link: str = "") -> mock.Mock:
@@ -1467,8 +1471,20 @@ class TestGithubWebhookSource:
"deployments": "deployment",
"deployment_statuses": "deployment_status",
"check_runs": "check_run",
+ "commit_statuses": "status",
+ "issue_comments": "issue_comment",
+ "pull_request_comments": "pull_request_review_comment",
+ "commit_comments": "commit_comment",
}
+ def test_manual_setup_instructions_list_every_mapped_event(self) -> None:
+ # A mapped event missing from the instructions leaves a manually-created hook unsubscribed
+ # from it, so the table stays empty with no error. The list already lost check_runs once.
+ caption = self.source.get_source_config.webhookSetupCaption
+ assert caption is not None
+ for event in set(GITHUB_WEBHOOK_RESOURCE_MAP.values()):
+ assert GITHUB_WEBHOOK_EVENT_LABELS[event] in caption
+
def test_webhook_template_identity(self) -> None:
template = self.source.webhook_template
assert template is not None
@@ -1485,6 +1501,10 @@ class TestGithubWebhookSource:
"deployments",
"deployment_statuses",
"check_runs",
+ "commit_statuses",
+ "issue_comments",
+ "pull_request_comments",
+ "commit_comments",
}
def test_workflow_runs_and_jobs_are_webhook_only(self) -> None:
@@ -1674,9 +1694,13 @@ class TestGithubWebhookSource:
assert url == "https://app.posthog.com/webhook"
assert sorted(events) == [
"check_run",
+ "commit_comment",
"deployment",
"deployment_status",
+ "issue_comment",
"pull_request_review",
+ "pull_request_review_comment",
+ "status",
"workflow_job",
"workflow_run",
]