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.

perf(warehouse_sources): cap the github deployment_statuses reconciliation fan-out (#90305)

Raúl Negrón-Oteroe7d9b0293017
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 983cc2b41a71..19cc4a67ae75 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
@@ -1094,6 +1094,7 @@ def _fan_out_get_rows(
egress_identity: GithubEgressIdentity | None = None,
api_version: str = GITHUB_DEFAULT_API_VERSION,
parent_cutoff_override: datetime | None = None,
+ max_parents: int | None = None,
) -> Iterator[Any]:
"""Single-hop parent->child fan-out: walk the parent endpoint and emit every child row for each
parent, substituting the parent's field into the child path (workflow_jobs -> {run_id},
@@ -1196,6 +1197,8 @@ def _fan_out_get_rows(
# workflow_runs).
parent_mapper = _get_item_mapper(parent_config.name)
+ fanned_out_parents = 0
+
for raw_parents, page_url in _iter_pages(
parent_url,
headers,
@@ -1222,6 +1225,17 @@ def _fan_out_get_rows(
and _is_older_than_cutoff(parent.get(parent_recency_field), parent_recency_cutoff)
):
continue
+ if max_parents is not None and fanned_out_parents >= max_parents:
+ logger.warning(
+ "Github: fan-out parent cap reached; older parents in the window skipped",
+ endpoint=endpoint,
+ repository=repository,
+ max_parents=max_parents,
+ )
+ # The walk is newest-first, so no later page holds a parent worth fanning out.
+ stop_after_this_page = True
+ break
+ fanned_out_parents += 1
inject = (
_make_parent_field_injector(parent, child_config.fan_out_include_parent_fields)
if child_config.fan_out_include_parent_fields
@@ -1256,6 +1270,7 @@ def get_rows(
egress_identity: GithubEgressIdentity | None = None,
api_version: str = GITHUB_DEFAULT_API_VERSION,
parent_cutoff_override: datetime | None = None,
+ max_parents: int | None = None,
) -> Iterator[Any]:
config = GITHUB_ENDPOINTS[endpoint]
if config.fan_out_parent is not None:
@@ -1270,6 +1285,7 @@ def get_rows(
egress_identity=egress_identity,
api_version=api_version,
parent_cutoff_override=parent_cutoff_override,
+ max_parents=max_parents,
)
return
@@ -1544,8 +1560,9 @@ def github_source(
# 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.
+ # skip when a watermark exists. A webhook schema configures no incremental field, so in
+ # that case the watermark arrives as None and only the window override and the parent
+ # cap bound the walk.
return _chain_webhook_items_with_reconciliation(
webhook_items,
lambda: get_rows(
@@ -1560,6 +1577,14 @@ def github_source(
egress_identity=egress_identity,
api_version=api_version,
parent_cutoff_override=_now_utc() - timedelta(days=reconcile_days),
+ # The recency skip bounds the walk on its own once a watermark exists, and every
+ # parent it admits is known to hold an unseen child, so a count bound would drop
+ # one for good: the run advances the watermark past it either way.
+ max_parents=(
+ None
+ if isinstance(db_incremental_field_last_value, datetime)
+ else endpoint_config.max_fan_out_parents
+ ),
),
)
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 a3ce9cab5a68..ed9222659b37 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
@@ -64,6 +64,12 @@ class GithubEndpointConfig:
# 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
+ # Ceiling on how many parents one fan-out walks, the peer of max_pages_per_parent on the other
+ # axis. A walk bounded only by a time window costs whatever the customer's write rate puts in
+ # that window. Every walk restarts at the newest parent, so this narrows the window rather than
+ # rotating through it: set it above the number of parents created within the span a child can
+ # still arrive in, or the tail below it is never revisited. None = no cap.
+ max_fan_out_parents: 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.
@@ -367,6 +373,9 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {
# parents that actually gained a status since the child watermark.
initial_lookback_days=0,
webhook_reconcile_lookback_days=30,
+ # Statuses stop arriving within hours of the deployment, and 500 spans over a day even on a
+ # repository deploying fast enough to reach the cap.
+ max_fan_out_parents=500,
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.
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 259b27096f8f..b2cd277ce76c 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
@@ -16,6 +16,16 @@ def _no_resume() -> mock.Mock:
return manager
+def _webhook_manager(*, enabled: bool, schema_is_webhook: bool | None = None, items: object = None) -> mock.Mock:
+ manager = mock.Mock()
+ manager.webhook_enabled = mock.AsyncMock(return_value=enabled)
+ if schema_is_webhook is not None:
+ manager.schema_is_webhook = mock.AsyncMock(return_value=schema_is_webhook)
+ if items is not None:
+ manager.get_items = mock.Mock(return_value=items)
+ return manager
+
+
def _iso(value: datetime) -> str:
return value.strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -37,9 +47,7 @@ async def _collect(tables: AsyncIterator[pa.Table]) -> list[pa.Table]:
],
)
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)
- webhook_source_manager.schema_is_webhook = mock.AsyncMock(return_value=True)
+ webhook_source_manager = _webhook_manager(enabled=False, schema_is_webhook=True)
with mock.patch.object(github, "_fetch_page") as fetch_page:
response = github.github_source(
@@ -74,9 +82,7 @@ def test_webhook_enabled_deployment_statuses_reconciles_inactive_statuses() -> N
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())
+ webhook_source_manager = _webhook_manager(enabled=True, items=webhook_items())
deployments_page = [
# Updated since the watermark (a new status landed): its statuses are re-fetched.
@@ -130,13 +136,77 @@ def test_webhook_enabled_deployment_statuses_reconciles_inactive_statuses() -> N
assert not any("/deployments/3/statuses" in url for url in fetched_urls)
+ "watermark_offset,expected_parents",
+ [
+ # No watermark: the recency skip is inert, so the cap is the only bound, and it keeps the
+ # newest parents.
+ (None, ["1", "2"]),
+ # Watermark set: every parent past the skip is known to hold an unseen child, and the run
+ # advances the watermark past it either way, so capping would drop it permanently.
+ (timedelta(days=3), ["1", "2", "3", "4"]),
+ ],
+)
+def test_webhook_enabled_deployment_statuses_reconciliation_caps_the_parent_fan_out(
+ watermark_offset: timedelta | None, expected_parents: list[str]
+) -> None:
+ now = datetime(2026, 7, 24, 12, 0, 0, tzinfo=UTC)
+
+ async def webhook_items() -> AsyncIterator[pa.Table]:
+ yield pa.table({"id": [99]})
+
+ webhook_source_manager = _webhook_manager(enabled=True, items=webhook_items())
+
+ # Newest first, the order GitHub returns deployments in and the order the cap relies on.
+ # All four sit inside the reconcile window and above any watermark below.
+ deployments_page = [
+ {
+ "id": index,
+ "created_at": _iso(now - timedelta(hours=index)),
+ "updated_at": _iso(now - timedelta(hours=index)),
+ }
+ for index in range(1, 5)
+ ]
+
+ def fetch_page(url: str, *args: object, **kwargs: object) -> mock.Mock:
+ response = mock.Mock()
+ response.headers = {}
+ if "/statuses" in url:
+ response.json.return_value = [{"id": 11, "state": "success", "created_at": _iso(now)}]
+ elif "/deployments?" in url:
+ response.json.return_value = deployments_page
+ else:
+ raise AssertionError(f"unexpected fetch: {url}")
+ return response
+
+ with (
+ mock.patch.object(github.GITHUB_ENDPOINTS["deployment_statuses"], "max_fan_out_parents", 2),
+ 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=None if watermark_offset is None else now - watermark_offset,
+ webhook_source_manager=webhook_source_manager,
+ )
+ result = response.items()
+ assert isinstance(result, AsyncIterator)
+ asyncio.run(_collect(result))
+
+ status_fetches = [url for url in fetch_mock.call_args_list if "/statuses" in url.args[0]]
+ assert [url.args[0].split("/deployments/")[1].split("/")[0] for url in status_fetches] == expected_parents
+
+
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_runs
# becomes webhook-only.
- webhook_source_manager = mock.Mock()
- webhook_source_manager.webhook_enabled = mock.AsyncMock(return_value=False)
- webhook_source_manager.schema_is_webhook = mock.AsyncMock(return_value=False)
+ webhook_source_manager = _webhook_manager(enabled=False, schema_is_webhook=False)
empty_page = mock.Mock()
empty_page.json.return_value = {"workflow_runs": []}