: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): ingest github deployments and deployment statuses (#73300)
Georges-Antoine Assi6b32329e01f1
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 d0c7730460b7..202ad279bdd3 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@@ -156,6 +156,44 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"created_at": "Time at which the job was created.",},},+ "deployments": {+ "description": "A request to deploy a specific ref (branch, SHA, or tag) to an environment. Rows arrive via the repository's deployment webhook.",+ "docs_url": "https://docs.github.com/en/rest/deployments/deployments",+ "columns": {+ "id": "Unique identifier for the deployment.",+ "sha": "Commit SHA that was requested to be deployed.",+ "ref": "The ref that was deployed (branch, tag, or SHA).",+ "task": "The name of the task for the deployment (e.g. deploy, deploy:migrations).",+ "environment": "Name of the environment the ref was deployed to (e.g. production, staging).",+ "original_environment": "The environment the deployment originally targeted, before any later override.",+ "description": "Description of the deployment.",+ "creator": "The user who created the deployment.",+ "payload": "Arbitrary JSON payload with extra deployment information.",+ "production_environment": "Whether the deployment targets a production environment.",+ "transient_environment": "Whether the environment is ephemeral and torn down after the ref stops being deployed.",+ "url": "API URL for the deployment.",+ "statuses_url": "API URL for the deployment's statuses.",+ "created_at": "Time at which the deployment was created.",+ "updated_at": "Time at which the deployment was last updated.",+ },+ },+ "deployment_statuses": {+ "description": "A status update on a deployment, marking its progress (pending, in_progress, success, failure, error, or inactive). The sequence of statuses is how a rollback shows up: an earlier deployment returning to success, or a later one going inactive. One row per status, with the parent deployment's id attached. Rows arrive via the repository's deployment_status webhook.",+ "docs_url": "https://docs.github.com/en/rest/deployments/statuses",+ "columns": {+ "id": "Unique identifier for the deployment status.",+ "deployment_id": "Identifier of the deployment this status belongs to (injected from the parent deployment).",+ "state": "The state of the deployment (success, failure, error, pending, in_progress, queued, or inactive).",+ "creator": "The user who created the deployment status.",+ "description": "A short human-readable description of the status.",+ "environment": "Name of the environment the deployment targeted.",+ "target_url": "Deprecated link for the status; superseded by log_url.",+ "log_url": "URL of the deployment output / logs for this status.",+ "environment_url": "URL of the deployed environment, if any.",+ "created_at": "Time at which the status was created.",+ "updated_at": "Time at which the status was last updated.",+ },+ },"teams": {"description": "A team within the repository's organization.","docs_url": "https://docs.github.com/en/rest/teams/teams",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 ade6adb2b5f2..c85674b0e4c5 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@@ -1,5 +1,6 @@import reimport random+import asyncioimport dataclassesfrom collections.abc import AsyncIterator, Callable, Iteratorfrom datetime import UTC, date, datetime, timedelta@@ -104,6 +105,12 @@ def _format_incremental_value(value: Any) -> str:return str(value)+# Endpoints whose list API ignores state/sort/direction and always returns newest-first by+# created_at. They take a minimal paged read (below) and must report sort_mode=desc on every sync,+# including the first (see _resolve_sort_mode) — the two must stay in lockstep, hence one set.+_ALWAYS_NEWEST_FIRST_ENDPOINTS = ("workflow_runs", "deployments")++def _build_initial_params(config: GithubEndpointConfig,endpoint: str,@@ -111,14 +118,12 @@ def _build_initial_params(db_incremental_field_last_value: Any,incremental_field: str | None,) -> dict[str, Any]:- # workflow_runs has a different param surface: it accepts neither- # state/sort/direction nor `since`, and always returns newest-first by- # created_at. We intentionally send no time filter either — its `created`- # filter would cap the result set to GitHub's 1,000-result search limit and- # silently drop rows on busy repos. Incremental sync is handled instead by- # paginating newest-first and stopping at the cursor (see get_rows), so the- # request stays a plain paged read regardless of incremental state.- if endpoint == "workflow_runs":+ # These endpoints accept neither state/sort/direction nor `since`. We intentionally send no+ # time filter either — a `created` filter would cap the result set to GitHub's 1,000-result+ # search limit and silently drop rows on busy repos. Incremental sync is handled instead by+ # paginating newest-first and stopping at the cursor (see get_rows), so the request stays a+ # plain paged read regardless of incremental state.+ if endpoint in _ALWAYS_NEWEST_FIRST_ENDPOINTS:return {"per_page": config.page_size}params: dict[str, Any] = {@@ -175,15 +180,16 @@ def _resolve_sort_mode(Most endpoints emit asc on the first sync / full refresh (stable offsetpagination via sort=created&direction=asc) and only flip to their- configured sort once a cutoff exists. workflow_runs is different: it ignores- sort/direction and always returns newest-first, so it emits desc on every- 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+ configured sort once a cutoff exists. The _ALWAYS_NEWEST_FIRST_ENDPOINTS+ (workflow_runs, deployments) are different: they ignore sort/direction and+ always return newest-first, so they emit desc on every 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 any of+ these would let the pipeline persist the cursor per batch and, on aninterrupted backfill, strand every row older than the batches that flushed."""- if endpoint == "workflow_runs" or config.fan_out_parent is not None:+ if endpoint in _ALWAYS_NEWEST_FIRST_ENDPOINTS 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@@ -639,6 +645,7 @@ def _fan_out_get_rows(db_incremental_field_last_value: Any,egress_identity: GithubEgressIdentity | None = None,api_version: str = GITHUB_DEFAULT_API_VERSION,+ parent_cutoff_override: datetime | None = None,) -> Iterator[Any]:"""Single-hop parent->child fan-out: walk the parent endpoint and emit every child row for eachparent, substituting the parent's field into the child path (workflow_jobs -> {run_id},@@ -680,11 +687,16 @@ def _fan_out_get_rows(db_incremental_field_last_value if (should_use_incremental_field and parent_is_incremental) else None)+ # A reconciliation pass re-walks a fixed recent window regardless of the watermark (which is+ # newer and would stop the walk too early), so an explicit override beats both the watermark+ # and the first-sync floor below.+ if parent_cutoff_override is not None:+ parent_cutoff = parent_cutoff_override# First incremental sync (watermark set up, but nothing synced yet): floor the# backfill at a recent window instead of fanning out over the parent's entire# history. Scoped to the incremental first run on purpose — an explicit full# refresh still pulls everything, and later syncs advance from their watermark.- if (+ elif (parent_is_incrementaland should_use_incremental_fieldand db_incremental_field_last_value is None@@ -693,6 +705,19 @@ def _fan_out_get_rows(parent_cutoff = _now_utc() - timedelta(days=child_config.initial_lookback_days)logger.debug(f"Github: flooring {endpoint} first-sync fan-out at {parent_cutoff.isoformat()}")+ # Parents whose recency field (bumped by any new child) predates the child watermark hold no+ # unseen children, so their child fetch is skipped. The watermark is pulled back one second+ # because _is_older_than_cutoff is inclusive and GitHub timestamps are second-coarse: a parent+ # whose recency equals the watermark may hold a child from that same second, so it re-fans.+ parent_recency_field = child_config.fan_out_parent_recency_field+ parent_recency_cutoff: datetime | None = None+ if (+ parent_recency_field is not None+ and should_use_incremental_field+ and isinstance(db_incremental_field_last_value, datetime)+ ):+ parent_recency_cutoff = db_incremental_field_last_value - timedelta(seconds=1)+resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Noneif resume_config is not None:parent_url: str = resume_config.next_url@@ -734,6 +759,12 @@ def _fan_out_get_rows(# Only fan out parents at/above the watermark; older ones were synced before.if parent_cutoff is not None and _is_older_than_cutoff(parent.get(parent_cursor_field), parent_cutoff):continue+ if (+ parent_recency_field is not None+ and parent_recency_cutoff is not None+ and _is_older_than_cutoff(parent.get(parent_recency_field), parent_recency_cutoff)+ ):+ continueinject = (_make_parent_field_injector(parent, child_config.fan_out_include_parent_fields)if child_config.fan_out_include_parent_fields@@ -767,6 +798,7 @@ def get_rows(incremental_field: str | None = None,egress_identity: GithubEgressIdentity | None = None,api_version: str = GITHUB_DEFAULT_API_VERSION,+ parent_cutoff_override: datetime | None = None,) -> Iterator[Any]:config = GITHUB_ENDPOINTS[endpoint]if config.fan_out_parent is not None:@@ -780,6 +812,7 @@ def get_rows(db_incremental_field_last_value=db_incremental_field_last_value,egress_identity=egress_identity,api_version=api_version,+ parent_cutoff_override=parent_cutoff_override,)return@@ -911,6 +944,28 @@ def _make_webhook_dedupe_transformer(primary_key: str, version_keys: list[str])return transform+async def _chain_webhook_items_with_reconciliation(+ webhook_items: AsyncIterator[pa.Table],+ make_reconcile_rows: Callable[[], Iterator[Any]],+) -> AsyncIterator[Any]:+ """Drain the webhook files, then run the bounded reconciliation poll. The poll is a blocking+ requests-based generator, so each step runs in a worker thread to keep the event loop (and+ the async S3 client the drain used) responsive."""+ async for table in webhook_items:+ yield table+ reconcile_rows = make_reconcile_rows()+ done = object()++ def next_or_done() -> Any:+ return next(reconcile_rows, done)++ while True:+ table = await asyncio.to_thread(next_or_done)+ if table is done:+ return+ yield table++def github_source(personal_access_token: str,repository: str,@@ -991,7 +1046,32 @@ def github_source(if endpoint_config.version_keyselse None)- return webhook_source_manager.get_items(table_transformer=transformer)+ webhook_items = webhook_source_manager.get_items(table_transformer=transformer)+ reconcile_days = endpoint_config.webhook_reconcile_lookback_days+ if reconcile_days is None:+ return webhook_items+ # GitHub never fires a deployment_status webhook for the inactive state, so a pure+ # webhook drain would miss rollback/auto_inactive transitions; chase the drain with a+ # bounded fan-out over recent parents so those rows still arrive from the list API.+ # should_use_incremental_field is forced on so the fan-out applies the parent recency+ # skip against the real child watermark; the window override below, not the watermark,+ # bounds the parent walk either way.+ return _chain_webhook_items_with_reconciliation(+ webhook_items,+ lambda: get_rows(+ personal_access_token=personal_access_token,+ repository=repository,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ egress_identity=egress_identity,+ api_version=api_version,+ parent_cutoff_override=_now_utc() - timedelta(days=reconcile_days),+ ),+ )if webhook_only_poll_noop:return iter([])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 357cc1cdd610..7ff5a35baace 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@@ -54,6 +54,15 @@ class GithubEndpointConfig:# 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.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+ # child rows that never got a webhook (deployment statuses marked inactive) are still+ # collected from the list API. None = webhook drain only.+ webhook_reconcile_lookback_days: Optional[int] = None+ # Parent field bumped whenever a child row is created (deployments.updated_at). When set,+ # an incremental fan-out skips parents whose value predates the child watermark — they can+ # hold no unseen children — keeping the reconciliation window cheap to re-walk every sync.+ fan_out_parent_recency_field: Optional[str] = NoneGITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {@@ -256,6 +265,76 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {# the job reaches that stage, so NULLs-last ordering keeps the latest state.version_keys=["completed_at", "started_at", "created_at"],),+ "deployments": GithubEndpointConfig(+ name="deployments",+ path="/repos/{repository}/deployments",+ partition_key="created_at",+ incremental_fields=[+ # The deployments list endpoint returns newest-first by created_at and (like+ # /actions/runs) does not honor sort/direction, so created_at is the only viable+ # cursor. We sync incrementally by paginating newest-first and stopping once we cross+ # below the cursor (see github.py). created_at is immutable; a deployment's latest+ # state lives on its deployment_statuses children and on updated_at, so the+ # created_at cursor won't refresh a deployment once newer ones land — that is handled+ # by the deployment webhook, not by re-scanning history.+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="created_at",+ sort_mode="desc", # API returns newest-first and ignores sort/direction, like workflow_runs+ # deployment carries updated_at (bumped when a new status is added), the recency key so a+ # completed deployment is never frozen by a stale earlier webhook event.+ version_keys=["updated_at"],+ # Webhook-only marker, like workflow_runs: the deployment webhook is the source of truth.+ # initial_lookback_days == 0 makes source.py report this schema as webhook_only, activates+ # webhook mode from the first sync, and makes the poll path yield no rows instead of+ # crawling the full /deployments history against a shared, rate-limited budget. History,+ # if wanted, is a deliberate one-off backfill.+ initial_lookback_days=0,+ ),+ "deployment_statuses": GithubEndpointConfig(+ name="deployment_statuses",+ # Child of deployments: {deployment_id} is filled per parent deployment during fan-out.+ # GitHub has no repo-wide deployment-statuses list, so a deployment's status history (the+ # success/failure/inactive transitions that mark a rollback) can only be assembled by+ # fanning out over deployments one at a time.+ path="/repos/{repository}/deployments/{deployment_id}/statuses",+ partition_key="created_at", # Set at status creation; immutable and non-null.+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ default_incremental_field="created_at",+ # Deployment-status ids are globally unique (like review ids), so no composite key is+ # needed even though this is a fan-out child.+ primary_key="id",+ sort_mode="desc", # Rows land parent-newest-first, same as workflow_jobs and reviews.+ fan_out_parent="deployments",+ fan_out_path_param="deployment_id",+ fan_out_parent_field="id",+ # The raw status only carries the deployment API URL, so inject the deployment id for+ # trivial attribution joins against the deployments table (mirrors reviews' pr_number).+ fan_out_include_parent_fields={"id": "deployment_id"},+ # Webhook-first (zero first-sync backfill), but not webhook-alone: GitHub never fires a+ # deployment_status webhook for the inactive state, so a pure webhook feed would miss+ # rollbacks and auto_inactive transitions, leaving a superseded deployment looking current.+ # Each sync therefore chases the webhook drain with a bounded reconciliation fan-out over+ # deployments created in the last 30 days; the updated_at recency skip keeps that to+ # parents that actually gained a status since the child watermark.+ initial_lookback_days=0,+ webhook_reconcile_lookback_days=30,+ fan_out_parent_recency_field="updated_at",+ # A deployment status is append-only (each transition is a new, immutable id), so no+ # webhook dedupe is needed — unlike reviews/runs, one id never emits multiple events.+ ),"teams": GithubEndpointConfig(name="teams",# Org-scoped: {organization} is derived from the repository owner (owner/repo -> owner).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 8272241d40fc..4be70b60124c 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@@ -81,6 +81,8 @@ GITHUB_WEBHOOK_RESOURCE_MAP: dict[str, str] = {"workflow_jobs": "workflow_job","workflow_runs": "workflow_run","reviews": "pull_request_review",+ "deployments": "deployment",+ "deployment_statuses": "deployment_status",}@@ -203,7 +205,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**, **Workflow runs**, and **Pull request reviews**+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**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.""",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.pyindex a3f4c318b630..2b1f6e0d1ef1 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@@ -218,6 +218,23 @@ class TestGithubSource:assert reviews.should_sync_default is Trueassert [f["field"] for f in reviews.incremental_fields] == ["submitted_at"]+ @pytest.mark.parametrize("endpoint", ["deployments", "deployment_statuses"])+ def test_deployment_schemas_are_webhook_only_and_default_on(self, endpoint):+ # Both deploy endpoints do no poll backfill (zero lookback floor), so they must be offered+ # webhook-only and stay selected by default (they need only the repo grant). If the webhook+ # map entry or the zero floor regressed, the picker would offer a poll mode that syncs an+ # empty table forever.+ config = GithubSourceConfig(+ auth_method=GithubAuthMethodConfig(github_integration_id=None, selection="pat", personal_access_token="t"),+ repository="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.should_sync_default is True+def test_get_access_token_returns_pat(self):config = GithubSourceConfig(auth_method=GithubAuthMethodConfig(@@ -319,6 +336,10 @@ class TestGithubSource:# Repo names can contain dots — a naive rpartition('.') would split `next.js` wrong.("posthog/next.js.issues", ("posthog/next.js", "issues")),("posthog/next.js.pull_requests", ("posthog/next.js", "pull_requests")),+ # deployment_statuses must win over deployments (longest suffix first) — a plain+ # endswith('deployments') would strip 'deployment_statuses' to '_statuses' and misroute.+ ("posthog/posthog.deployments", ("posthog/posthog", "deployments")),+ ("posthog/posthog.deployment_statuses", ("posthog/posthog", "deployment_statuses")),# Unrecognized suffixes stay whole so unknown rows don't get misrouted.("posthog/posthog.not_an_endpoint", (None, "posthog/posthog.not_an_endpoint")),],@@ -374,6 +395,8 @@ class TestGithubSource:("workflow_runs", "workflow_run"),("workflow_jobs", "workflow_job"),("reviews", "pull_request_review"),+ ("deployments", "deployment"),+ ("deployment_statuses", "deployment_status"),# Qualified rows get repo-qualified keys — two repos' workflow_runs would otherwise# collide on one "workflow_run" key and route all events to a single schema.("acme/Widgets.workflow_runs", "acme/widgets.workflow_run"),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.pyindex f8e2a453b6f7..23788a0cb6e6 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@@ -1,8 +1,12 @@-from collections.abc import Iterable+import asyncio+from collections.abc import AsyncIterator, Iterable+from datetime import UTC, datetime, timedeltaimport pytestfrom unittest import mock+import pyarrow as pa+from products.warehouse_sources.backend.temporal.data_imports.sources.github import github@@ -12,7 +16,17 @@ def _no_resume() -> mock.Mock:return manager[email protected]("endpoint", ["workflow_runs", "workflow_jobs", "reviews"])+def _iso(value: datetime) -> str:+ return value.strftime("%Y-%m-%dT%H:%M:%SZ")+++async def _collect(tables: AsyncIterator[pa.Table]) -> list[pa.Table]:+ return [table async for table in tables]+++ "endpoint", ["workflow_runs", "workflow_jobs", "reviews", "deployments", "deployment_statuses"]+)def test_webhook_only_poll_yields_no_rows_when_webhook_inactive(endpoint: str) -> None:webhook_source_manager = mock.Mock()webhook_source_manager.webhook_enabled = mock.AsyncMock(return_value=False)@@ -39,6 +53,74 @@ def test_webhook_only_poll_yields_no_rows_when_webhook_inactive(endpoint: str) -webhook_source_manager.get_items.assert_not_called()+def test_webhook_enabled_deployment_statuses_reconciles_inactive_statuses() -> None:+ # GitHub fires no deployment_status webhook for the inactive state, so the webhook drain must+ # be chased by a bounded fan-out over recent deployments; without it, rollback/auto_inactive+ # statuses are silently never ingested and a superseded deployment keeps looking current.+ now = datetime(2026, 7, 24, 12, 0, 0, tzinfo=UTC)+ watermark = now - timedelta(hours=1)++ webhook_table = pa.table({"id": [99]})++ async def webhook_items() -> AsyncIterator[pa.Table]:+ yield webhook_table++ webhook_source_manager = mock.Mock()+ webhook_source_manager.webhook_enabled = mock.AsyncMock(return_value=True)+ webhook_source_manager.get_items = mock.Mock(return_value=webhook_items())++ deployments_page = [+ # Updated since the watermark (a new status landed): its statuses are re-fetched.+ {"id": 1, "created_at": _iso(now - timedelta(days=1)), "updated_at": _iso(now - timedelta(minutes=5))},+ # In the window but not updated since the watermark: holds no unseen statuses, skipped.+ {"id": 2, "created_at": _iso(now - timedelta(days=2)), "updated_at": _iso(now - timedelta(days=2))},+ # Freshly updated but created outside the 30-day reconcile window: skipped.+ {"id": 3, "created_at": _iso(now - timedelta(days=40)), "updated_at": _iso(now - timedelta(minutes=5))},+ ]+ statuses_page = [+ {"id": 11, "state": "success", "created_at": _iso(now - timedelta(minutes=10))},+ {"id": 12, "state": "inactive", "created_at": _iso(now - timedelta(minutes=5))},+ ]++ def fetch_page(url: str, *args: object, **kwargs: object) -> mock.Mock:+ response = mock.Mock()+ response.headers = {}+ if "/deployments/1/statuses" in url:+ response.json.return_value = statuses_page+ elif "/deployments?" in url:+ response.json.return_value = deployments_page+ else:+ raise AssertionError(f"unexpected fetch: {url}")+ return response++ with (+ mock.patch.object(github, "_fetch_page", side_effect=fetch_page) as fetch_mock,+ mock.patch.object(github, "_now_utc", return_value=now),+ ):+ response = github.github_source(+ personal_access_token="tok",+ repository="acme/widgets",+ endpoint="deployment_statuses",+ logger=mock.Mock(),+ resumable_source_manager=_no_resume(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ webhook_source_manager=webhook_source_manager,+ )+ result = response.items()+ assert isinstance(result, AsyncIterator)+ tables = asyncio.run(_collect(result))++ assert tables[0] is webhook_table+ reconciled = pa.concat_tables(tables[1:])+ assert reconciled.column("id").to_pylist() == [11, 12]+ assert reconciled.column("state").to_pylist() == ["success", "inactive"]+ assert reconciled.column("deployment_id").to_pylist() == [1, 1]+ fetched_urls = [call.args[0] for call in fetch_mock.call_args_list]+ assert not any("/deployments/2/statuses" in url for url in fetched_urls)+ assert not any("/deployments/3/statuses" in url for url in fetched_urls)++def test_poll_mode_workflow_runs_still_polls() -> None:# A legacy workflow_runs schema still configured for poll sync (is_webhook False) must keep# polling, not get short-circuited to empty — otherwise it silently freezes once workflow_runsdiff --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.pyindex e97c4fd61659..ccd50440279f 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@@ -101,6 +101,43 @@ class TestGithubWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):self.mock_produce_to_warehouse_webhooks.assert_called_once_with(job, "schema_jobs")+ def test_deployment_row_lands_unchanged(self):+ # The deployment event nests the object under body.deployment, matching the polled REST+ # shape, so it lands as-is like workflow_job / workflow_run.+ deployment = {"id": 7, "environment": "production", "sha": "abc123"}+ self._run("deployment", {"action": "created", "deployment": deployment}, {"deployment": "schema_deploys"})++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(deployment, "schema_deploys")++ def test_deployment_status_row_is_reshaped_to_poll_shape(self):+ # The deployment_status event nests the status under body.deployment_status and its+ # deployment under body.deployment; the status carries no deployment_id. The template must+ # inject deployment_id so webhook rows match poll rows (which carry it from the parent).+ body = {+ "action": "created",+ "deployment_status": {"id": 900, "state": "success", "created_at": "2026-01-20T10:00:00Z"},+ "deployment": {"id": 7, "environment": "production"},+ }+ self._run("deployment_status", body, {"deployment_status": "schema_statuses"})++ row, schema_id = self.mock_produce_to_warehouse_webhooks.call_args.args+ assert schema_id == "schema_statuses"+ assert row["id"] == 900+ assert row["state"] == "success"+ assert row["deployment_id"] == 7++ @parameterized.expand(+ [+ ("missing_status", {"action": "created", "deployment": {"id": 7}}),+ ("missing_deployment", {"action": "created", "deployment_status": {"id": 900, "state": "success"}}),+ ]+ )+ def test_incomplete_deployment_status_payload_is_skipped_with_200(self, _name: str, body: dict[str, Any]):+ res = self._run("deployment_status", body, {"deployment_status": "schema_statuses"})++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()+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.pyindex 23cb9a8ca6ed..a7d05045989c 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@@ -133,6 +133,25 @@ if (eventType = 'pull_request_review') {row := review}+// deployment_status nests the status under body.deployment_status and its deployment under+// body.deployment. Reshape so webhook rows match poll rows, which carry deployment_id injected+// from the parent deployment. States are already lowercase in both REST and webhook, so no case+// normalization is needed (unlike pull_request_review).+if (eventType = 'deployment_status') {+ let status := request.body?.deployment_status+ let deployment := request.body?.deployment+ if (empty(status) or empty(deployment)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No deployment_status or deployment object in payload, skipping'+ }+ }+ }+ status.deployment_id := deployment?.id+ row := status+}+if (empty(row)) {return {'httpResponse': {@@ -166,7 +185,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) 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, pull_request_review, deployment, deployment_status) 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.pyindex bb38a816e728..e5ca065ed8f0 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@@ -199,6 +199,22 @@ class TestBuildInitialParams:# early-stop in get_rows, so the request never changes shape.assert params == {"per_page": 100}+ def test_deployments_uses_minimal_params_with_cutoff(self) -> None:+ # deployments shares workflow_runs' param surface: the list endpoint ignores+ # sort/direction and returns newest-first, so even with a cutoff it must stay a plain paged+ # read (incremental bounding is the client-side desc early-stop). Regressing it into the+ # generic branch would send sort=created&direction=desc, which the endpoint silently ignores+ # while the desc early-stop still relies on the natural newest-first order.+ params = _build_initial_params(+ GITHUB_ENDPOINTS["deployments"],+ "deployments",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 15, 10, 0, 0, tzinfo=UTC),+ incremental_field="created_at",+ )++ assert params == {"per_page": 100}+class TestBuildInitialUrl:def test_with_params(self) -> None:@@ -534,6 +550,14 @@ class TestGithubSourceSortMode:datetime(2026, 1, 15, tzinfo=UTC),"desc",),+ # deployments is the same category as workflow_runs (minimal params, API ignores+ # sort/direction, always newest-first), so it must report desc even on the first sync /+ # full refresh — never the asc default. Guards the _build_initial_params /+ # _resolve_sort_mode parity.+ ("deployments_full_refresh", "deployments", False, None, "desc"),+ ("deployments_first_sync_no_cutoff", "deployments", True, None, "desc"),+ # deployment_statuses fans out over deployments newest-first, desc on every sync.+ ("deployment_statuses_first_sync_no_cutoff", "deployment_statuses", True, None, "desc"),])def test_sort_mode(@@ -1412,6 +1436,8 @@ class TestGithubWebhookSource:"workflow_jobs": "workflow_job","workflow_runs": "workflow_run","reviews": "pull_request_review",+ "deployments": "deployment",+ "deployment_statuses": "deployment_status",}def test_webhook_template_identity(self) -> None:@@ -1423,7 +1449,13 @@ class TestGithubWebhookSource: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", "reviews"}+ assert webhook_capable == {+ "workflow_jobs",+ "workflow_runs",+ "reviews",+ "deployments",+ "deployment_statuses",+ }def test_workflow_runs_and_jobs_are_webhook_only(self) -> None:# workflow_jobs and workflow_runs both do no poll backfill (zero floor), so neither is@@ -1610,7 +1642,13 @@ class TestGithubWebhookSource:_token, repo, url, events = update.call_args.argsassert repo == "owner/repo"assert url == "https://app.posthog.com/webhook"- assert sorted(events) == ["pull_request_review", "workflow_job", "workflow_run"]+ assert sorted(events) == [+ "deployment",+ "deployment_status",+ "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()