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.

fix(warehouse-sources): sync startup_failure github workflow runs (#111715)

Julian Bez94f37f152c00
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 d01434404635..c059ea44ef6c 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
@@ -62,6 +62,10 @@ FAN_OUT_PARENT_CAP_HITS = Counter(
# for clock skew between the two before trusting it to skip a parent.
_RECONCILE_SKEW_ALLOWANCE = timedelta(minutes=5)
+_STARTUP_FAILURE_FIRST_SYNC_LOOKBACK = timedelta(days=1)
+_STARTUP_FAILURE_MIN_WINDOW = timedelta(minutes=1)
+_GITHUB_FILTERED_RESULT_CAP = 1000
+
# GitHub's date-based REST API versions are sent in the X-GitHub-Api-Version header. Every caller —
# sync, credential validation, webhook management — passes the source's resolved pin; this constant
# is only the fallback for callers outside a source instance. Response shapes are not compatible
@@ -1805,6 +1809,85 @@ async def _chain_webhook_items_with_reconciliation(
yield table
+def _format_github_time(value: datetime) -> str:
+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _iter_startup_failure_runs(
+ url_for_window: Callable[[datetime, datetime], str],
+ fetch_pages: Callable[[str], Iterator[tuple[list[dict[str, Any]], str]]],
+ logger: FilteringBoundLogger,
+ window_start: datetime,
+ window_end: datetime,
+) -> Iterator[dict[str, Any]]:
+ """Yield the startup_failure runs created in the window. A window that returns GitHub's 1,000-run
+ cap is split in half and polled again, so a dense range is not truncated and a quiet range costs
+ one call. Runs at a split boundary or from the capped query come back more than once, so the
+ caller dedupes by run id."""
+ window_count = 0
+ for runs, _page_url in fetch_pages(url_for_window(window_start, window_end)):
+ for run in runs:
+ window_count += 1
+ yield run
+ if window_count < _GITHUB_FILTERED_RESULT_CAP:
+ return
+ if window_end - window_start <= _STARTUP_FAILURE_MIN_WINDOW:
+ logger.warning(
+ "Github: startup_failure poll hit the 1,000-run cap in its smallest window, so some runs stay queued: "
+ f"window_start={window_start}, window_end={window_end}"
+ )
+ return
+ midpoint = window_start + (window_end - window_start) / 2
+ yield from _iter_startup_failure_runs(url_for_window, fetch_pages, logger, window_start, midpoint)
+ yield from _iter_startup_failure_runs(url_for_window, fetch_pages, logger, midpoint, window_end)
+
+
+def _get_startup_failure_runs(
+ personal_access_token: str,
+ repository: str,
+ logger: FilteringBoundLogger,
+ created_since: datetime,
+ egress_identity: GithubEgressIdentity | None = None,
+ api_version: str = GITHUB_DEFAULT_API_VERSION,
+) -> Iterator[pa.Table]:
+ """Poll the runs that ended in startup_failure since ``created_since``. GitHub sends only the
+ `requested` workflow_run webhook (status queued) for such a run and never a `completed` one, so
+ without this poll the webhook-fed table keeps the run queued forever."""
+ headers = _get_headers(personal_access_token, "workflow_runs", api_version)
+
+ def url_for_window(window_start: datetime, window_end: datetime) -> str:
+ params = {
+ "status": "startup_failure",
+ "created": f"{_format_github_time(window_start)}..{_format_github_time(window_end)}",
+ "per_page": GITHUB_ENDPOINTS["workflow_runs"].page_size,
+ }
+ return f"{GITHUB_BASE_URL}/repos/{repository}/actions/runs?{urlencode(params)}"
+
+ def fetch_pages(url: str) -> Iterator[tuple[list[dict[str, Any]], str]]:
+ return _iter_pages(
+ url,
+ headers,
+ "workflow_runs",
+ logger,
+ egress_identity=egress_identity,
+ repository=repository,
+ required_permission=ENDPOINT_REQUIRED_PERMISSION.get("workflow_runs"),
+ )
+
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # The delta merge doesn't dedupe within a source batch, so a run polled twice must be dropped here.
+ seen_run_ids: set[int] = set()
+ for run in _iter_startup_failure_runs(url_for_window, fetch_pages, logger, created_since, _now_utc()):
+ if run["id"] in seen_run_ids:
+ continue
+ seen_run_ids.add(run["id"])
+ batcher.batch(run)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
def github_source(
personal_access_token: str,
repository: str,
@@ -1889,6 +1972,25 @@ def github_source(
else None
)
webhook_items = webhook_source_manager.get_items(table_transformer=transformer)
+ if endpoint == "workflow_runs":
+ # The poll runs after the drain, so its completed row lands after the queued
+ # webhook row of the same run and wins the merge.
+ created_since = (
+ reconcile_since - _RECONCILE_SKEW_ALLOWANCE
+ if reconcile_since
+ else _now_utc() - _STARTUP_FAILURE_FIRST_SYNC_LOOKBACK
+ )
+ return _chain_webhook_items_with_reconciliation(
+ webhook_items,
+ lambda: _get_startup_failure_runs(
+ personal_access_token=personal_access_token,
+ repository=repository,
+ logger=logger,
+ created_since=created_since,
+ egress_identity=egress_identity,
+ api_version=api_version,
+ ),
+ )
reconcile_days = endpoint_config.webhook_reconcile_lookback_days
if reconcile_days is None:
return webhook_items
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 6ddd00d1513d..160be825682f 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,5 +1,5 @@
import asyncio
-from collections.abc import AsyncIterator, Iterable
+from collections.abc import AsyncIterator, Iterable, Iterator
from datetime import UTC, datetime, timedelta
import pytest
@@ -199,6 +199,105 @@ def test_webhook_enabled_deployment_statuses_reconciliation_caps_the_parent_fan_
assert [url.args[0].split("/deployments/")[1].split("/")[0] for url in status_fetches] == ["1", "2"]
+ "reconcile_since_offset, expected_window",
+ [
+ (None, "2026-10-04T12%3A00%3A00Z..2026-10-05T12%3A00%3A00Z"),
+ (timedelta(hours=1), "2026-10-05T10%3A55%3A00Z..2026-10-05T12%3A00%3A00Z"),
+ ],
+)
+def test_webhook_enabled_workflow_runs_polls_startup_failures_after_the_drain(
+ reconcile_since_offset: timedelta | None, expected_window: str
+) -> None:
+ now = datetime(2026, 10, 5, 12, 0, 0, tzinfo=UTC)
+ webhook_table = pa.table({"id": [1], "status": ["queued"]})
+
+ async def webhook_items() -> AsyncIterator[pa.Table]:
+ yield webhook_table
+
+ webhook_source_manager = _webhook_manager(enabled=True, items=webhook_items())
+
+ page = mock.Mock()
+ page.headers = {}
+ page.json.return_value = {
+ "workflow_runs": [{"id": 1, "status": "completed", "conclusion": "startup_failure"}],
+ }
+
+ with (
+ mock.patch.object(github, "_fetch_page", return_value=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="workflow_runs",
+ logger=mock.Mock(),
+ resumable_source_manager=_no_resume(),
+ webhook_source_manager=webhook_source_manager,
+ reconcile_since=None if reconcile_since_offset is None else now - reconcile_since_offset,
+ )
+ result = response.items()
+ assert isinstance(result, AsyncIterator)
+ tables = asyncio.run(_collect(result))
+
+ assert tables[0] is webhook_table
+ polled = pa.concat_tables(tables[1:])
+ assert polled.column("conclusion").to_pylist() == ["startup_failure"]
+ fetched_url = fetch_mock.call_args.args[0]
+ assert "status=startup_failure" in fetched_url
+ assert f"created={expected_window}&" in fetched_url
+
+
+ "runs_per_hour, expected_windows",
+ [
+ (10, [(0, 24)]),
+ (
+ 300,
+ [
+ (0, 24),
+ (0, 12),
+ (0, 6),
+ (0, 3),
+ (3, 6),
+ (6, 12),
+ (6, 9),
+ (9, 12),
+ (12, 24),
+ (12, 18),
+ (12, 15),
+ (15, 18),
+ (18, 24),
+ (18, 21),
+ (21, 24),
+ ],
+ ),
+ ],
+)
+def test_startup_failure_poll_splits_only_windows_that_hit_the_cap(
+ runs_per_hour: int, expected_windows: list[tuple[int, int]]
+) -> None:
+ day_start = datetime(2026, 10, 4, 0, 0, 0, tzinfo=UTC)
+ fetched_windows: list[tuple[int, int]] = []
+
+ def url_for_window(window_start: datetime, window_end: datetime) -> str:
+ return f"{(window_start - day_start) // timedelta(hours=1)}..{(window_end - day_start) // timedelta(hours=1)}"
+
+ def fetch_pages(url: str) -> Iterator[tuple[list[dict[str, int]], str]]:
+ start_hour, end_hour = (int(part) for part in url.split(".."))
+ fetched_windows.append((start_hour, end_hour))
+ matching = (end_hour - start_hour) * runs_per_hour
+ yield [{"id": index} for index in range(min(matching, 1000))], url
+
+ list(
+ github._iter_startup_failure_runs(
+ url_for_window, fetch_pages, mock.Mock(), day_start, day_start + timedelta(days=1)
+ )
+ )
+
+ assert fetched_windows == expected_windows
+
+
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
@@ -226,3 +325,29 @@ def test_poll_mode_workflow_runs_still_polls() -> None:
# A legacy poll-mode schema is NOT webhook_only, so a reset still wipes and rebuilds.
assert response.webhook_only is False
webhook_source_manager.get_items.assert_not_called()
+
+
+def test_startup_failure_poll_drops_runs_seen_in_an_earlier_window() -> None:
+ def page_of(run_ids: Iterable[int]) -> mock.Mock:
+ page = mock.Mock()
+ page.headers = {}
+ page.json.return_value = {"workflow_runs": [{"id": run_id} for run_id in run_ids]}
+ return page
+
+ capped_page = page_of(range(1000))
+ half_page = page_of([7])
+
+ with (
+ mock.patch.object(github, "_fetch_page", side_effect=[capped_page, half_page, half_page]),
+ mock.patch.object(github, "_now_utc", return_value=datetime(2026, 10, 5, 12, 0, 0, tzinfo=UTC)),
+ ):
+ tables = list(
+ github._get_startup_failure_runs(
+ personal_access_token="tok",
+ repository="acme/widgets",
+ logger=mock.Mock(),
+ created_since=datetime(2026, 10, 4, 12, 0, 0, tzinfo=UTC),
+ )
+ )
+
+ assert pa.concat_tables(tables).column("id").to_pylist() == list(range(1000))