: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
fix(data-warehouse): make github workflow_jobs webhook-driven (#65599)
Julian Beze14148d89ae8
diff --git a/posthog/temporal/data_imports/sources/github/github.py b/posthog/temporal/data_imports/sources/github/github.pyindex 67cd99ab0c69..bbb0c387ea79 100644--- a/posthog/temporal/data_imports/sources/github/github.py+++ b/posthog/temporal/data_imports/sources/github/github.py@@ -1,4 +1,5 @@import re+import randomimport dataclassesfrom collections.abc import AsyncIterator, Callable, Iteratorfrom datetime import UTC, date, datetime, timedelta@@ -9,8 +10,10 @@ import requestsfrom asgiref.sync import async_to_syncfrom dateutil import parser as dateutil_parserfrom structlog.types import FilteringBoundLogger-from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry+from posthog.models.integration import GitHubRateLimitError, raise_if_github_rate_limitedfrom posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponsefrom posthog.temporal.data_imports.sources.common.base import (@@ -310,18 +313,57 @@ def _get_item_filter(endpoint: str) -> Callable[[dict[str, Any]], bool] | None:return None+# Upper bound on how long we'll honor GitHub's rate-limit reset before retrying,+# so a misreported reset header can't stall a worker indefinitely. The source+# iterator runs in a thread pool while the activity's liveness heartbeat fires+# from the event loop every heartbeat_timeout/30 (~4s), so a 300s wait here does+# not trip the 2-min heartbeat timeout. Mirrors common/rest_source/rest_client.py.+GITHUB_MAX_RETRY_AFTER_SECONDS = 300.0++# Plain backoff for transient blips (5xx, connection resets) where GitHub gives+# us no reset to honor.+_github_backoff_wait = wait_exponential_jitter(initial=1, max=30)++# Disable the tracked session's default adapter retries on this path. That policy+# retries 429/5xx and honors Retry-After *uncapped*, underneath _fetch_page — which+# would defeat the 300s cap below and stack a second, untested retry layer. With+# adapter retries off, _fetch_page sees every response/exception and our tenacity+# layer is the single, rate-limit-aware retry authority.+_NO_ADAPTER_RETRY = Retry(total=0)+++def _github_retry_wait(state: RetryCallState) -> float:+ """Sleep until GitHub's advertised rate-limit reset when it gave us one+ (capped, plus a little jitter so the sources sharing one installation's+ budget don't all wake at the same reset instant); otherwise fall back to+ exponential backoff."""+ if state.outcome is not None and state.outcome.failed:+ exc = state.outcome.exception()+ if isinstance(exc, GitHubRateLimitError) and exc.retry_after_seconds is not None:+ return min(exc.retry_after_seconds, GITHUB_MAX_RETRY_AFTER_SECONDS) + random.uniform(0, 1)+ return _github_backoff_wait(state)++@retry(- retry=retry_if_exception_type((GithubRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ retry=retry_if_exception_type(+ (GithubRetryableError, GitHubRateLimitError, requests.ReadTimeout, requests.ConnectionError)+ ),stop=stop_after_attempt(5),- wait=wait_exponential_jitter(initial=1, max=30),+ wait=_github_retry_wait,reraise=True,)def _fetch_page(page_url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> requests.Response:- response = make_tracked_session().get(page_url, headers=headers, timeout=60)+ response = make_tracked_session(retry=_NO_ADAPTER_RETRY).get(page_url, headers=headers, timeout=60)- if response.status_code == 429 or response.status_code >= 500:+ # Transient server errors: retry with plain exponential backoff.+ if response.status_code >= 500:raise GithubRetryableError(f"Github API error (retryable): status={response.status_code}, url={page_url}")+ # Rate limited (secondary 429, or primary 403 with a rate-limit body): raise+ # so we retry honoring the reset/Retry-After. A genuine permission 403 carries+ # no rate-limit body and falls through to raise_for_status below, staying fatal.+ raise_if_github_rate_limited(response)+# An empty repository (no commits yet) returns 409 on the commits# endpoint. Signal it so the loop can sync zero rows without raising# a hard error (which would otherwise retry the activity indefinitely).@@ -588,8 +630,18 @@ def github_source(# Steady-state webhook ingestion replaces the poll fan-out once the initial# backfill is complete and a webhook function is enabled. When no manager is# passed (or it isn't enabled), the poll path below stays unchanged.+ #+ # An endpoint whose poll does no first-sync backfill (initial_lookback_days == 0,+ # i.e. workflow_jobs) would otherwise deadlock a fresh webhook schema: the+ # zero-row poll never creates a table, so initial_sync_complete is never set, so+ # webhook_enabled stays False forever and queued webhook files never drain. There+ # is no backfill to lose for these, so activate webhook mode from the first run+ # (skip the initial_sync_complete gate), the same way the Slack source does.+ skip_initial_sync_complete_check = endpoint_config.initial_lookback_days == 0webhook_enabled = (- async_to_sync(webhook_source_manager.webhook_enabled)() if webhook_source_manager is not None else False+ async_to_sync(webhook_source_manager.webhook_enabled)(skip_initial_sync_complete_check)+ if webhook_source_manager is not None+ else False)def items() -> Iterator[Any] | AsyncIterator[Any]:diff --git a/posthog/temporal/data_imports/sources/github/settings.py b/posthog/temporal/data_imports/sources/github/settings.pyindex 7d1dbab0455b..2e18a6157db6 100644--- a/posthog/temporal/data_imports/sources/github/settings.py+++ b/posthog/temporal/data_imports/sources/github/settings.py@@ -164,12 +164,16 @@ GITHUB_ENDPOINTS: dict[str, GithubEndpointConfig] = {# filter=all returns jobs across every run_attempt (retries), not just the# latest execution — required for retry/runner-utilization analysis.extra_params={"filter": "all"},- # One /jobs call per run makes an unbounded first sync a multi-day,- # rate-limited crawl of the whole repo history (the OAuth budget is shared- # with Tasks/Code/deploys). A busy repo merges ~100 PRs/day, so even a few- # days seeds plenty of rows to start from; the webhook carries everything- # after. Keep the initial backfill tiny — just enough to not start empty.- initial_lookback_days=3,+ # One /jobs call per run, and a busy repo produces tens of thousands of runs+ # per day (every push, re-run, scheduled trigger, and matrix leg is a run —+ # not just PRs). At that volume even a few days of fan-out is hundreds of+ # thousands of requests against a shared, rate-limited OAuth budget. So poll+ # does no historical backfill: the webhook is the source of truth for jobs.+ # With a zero-day floor the first sync fans out over nothing, the watermark+ # stays unset, and once webhook rows land the poll only re-fans the tiny+ # window since the latest job. Repos that genuinely want history should run a+ # deliberate one-off backfill, not pay for it on every connect.+ initial_lookback_days=0,),}diff --git a/posthog/temporal/data_imports/sources/github/source.py b/posthog/temporal/data_imports/sources/github/source.pyindex 804ae829a1ce..a89979cc64a7 100644--- a/posthog/temporal/data_imports/sources/github/source.py+++ b/posthog/temporal/data_imports/sources/github/source.py@@ -40,7 +40,7 @@ from posthog.temporal.data_imports.sources.github.github import (github_source,validate_credentials as validate_github_credentials,)-from posthog.temporal.data_imports.sources.github.settings import ENDPOINTS, INCREMENTAL_FIELDS+from posthog.temporal.data_imports.sources.github.settings import ENDPOINTS, GITHUB_ENDPOINTS, INCREMENTAL_FIELDSfrom products.data_warehouse.backend.types import ExternalDataSourceType@@ -210,6 +210,25 @@ If automatic creation failed, your token needs webhook permissions — the **admraise ValueError("GitHub access token not found")return integration.access_token+ @staticmethod+ def _schema_for_endpoint(endpoint: str) -> SourceSchema:+ webhook_capable = endpoint in GITHUB_WEBHOOK_RESOURCE_MAP+ # An endpoint whose poll does no first-sync backfill (initial_lookback_days == 0,+ # i.e. workflow_jobs) can only ever be populated by the webhook — the per-run+ # fan-out is too expensive to backfill at run volume. Offer it as webhook-only so+ # users can't pick a poll mode that would sync an empty table forever. workflow_runs+ # keeps its poll backfill; the webhook just replaces re-polling for it.+ webhook_only = webhook_capable and GITHUB_ENDPOINTS[endpoint].initial_lookback_days == 0+ supports_poll = bool(INCREMENTAL_FIELDS.get(endpoint)) and not webhook_only+ return SourceSchema(+ name=endpoint,+ supports_incremental=supports_poll,+ supports_append=supports_poll,+ supports_webhooks=webhook_capable,+ webhook_only=webhook_only,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ )+def get_schemas(self,config: GithubSourceConfig,@@ -218,18 +237,7 @@ If automatic creation failed, your token needs webhook permissions — the **admnames: list[str] | None = None,force_refresh: bool = False,) -> list[SourceSchema]:- schemas = [- SourceSchema(- name=endpoint,- supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),- supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),- # Only the workflow endpoints can be steady-state webhook-fed; the- # poll fan-out is the backfill, the webhook replaces re-polling.- supports_webhooks=endpoint in GITHUB_WEBHOOK_RESOURCE_MAP,- incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- )- for endpoint in list(ENDPOINTS)- ]+ schemas = [self._schema_for_endpoint(endpoint) for endpoint in list(ENDPOINTS)]if names is not None:names_set = set(names)schemas = [s for s in schemas if s.name in names_set]diff --git a/posthog/temporal/tests/data_imports/github/test_github_source.py b/posthog/temporal/tests/data_imports/github/test_github_source.pyindex 7d80a2de848d..355f346ecd93 100644--- a/posthog/temporal/tests/data_imports/github/test_github_source.py+++ b/posthog/temporal/tests/data_imports/github/test_github_source.py@@ -1,6 +1,7 @@import dataclasses+from collections.abc import Iteratorfrom datetime import UTC, date, datetime-from typing import Any+from typing import Any, castfrom urllib.parse import parse_qs, urlparseimport pytest@@ -8,15 +9,21 @@ from unittest import mockimport requestsfrom parameterized import parameterized+from tenacity import Future, RetryCallState+from posthog.models.integration import GitHubRateLimitErrorfrom posthog.temporal.data_imports.sources.generated_configs import GithubAuthMethodConfig, GithubSourceConfigfrom posthog.temporal.data_imports.sources.github.github import (+ GITHUB_MAX_RETRY_AFTER_SECONDS,GithubResumeConfig,+ GithubRetryableError,_build_initial_params,_build_initial_url,+ _fetch_page,_flatten_commit,_flatten_stargazer,_format_incremental_value,+ _github_retry_wait,_is_empty_repository_response,_is_issue_not_pr,_is_older_than_cutoff,@@ -525,6 +532,58 @@ class TestGithubSourceSortMode:assert response.sort_mode == expected_sort_mode+# A fresh webhook schema must not deadlock: workflow_jobs does no poll backfill+# (initial_lookback_days == 0), so webhook mode has to activate before the zero-row+# poll could mark initial_sync_complete — otherwise the gate never opens and queued+# webhook files never drain. workflow_runs (and the non-webhook endpoints) keep their+# historical poll backfill, so they must NOT skip that gate.+class TestGithubWebhookActivationGate:+ def _make_webhook_manager(self, enabled: bool) -> mock.Mock:+ manager = mock.Mock()+ manager.webhook_enabled = mock.AsyncMock(return_value=enabled)+ manager.get_items = mock.Mock(return_value=iter([{"id": 1}]))+ return manager++ @parameterized.expand(+ [+ ("workflow_jobs_skips_gate", "workflow_jobs", True),+ ("workflow_runs_keeps_gate", "workflow_runs", False),+ ("issues_keeps_gate", "issues", False),+ ]+ )+ def test_skip_check_scoped_to_zero_backfill_endpoint(self, _name: str, endpoint: str, expected_skip: bool) -> None:+ manager = self._make_webhook_manager(enabled=False)+ github_source(+ personal_access_token="token",+ repository="owner/repo",+ endpoint=endpoint,+ logger=mock.Mock(),+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ webhook_source_manager=manager,+ )+ manager.webhook_enabled.assert_called_once_with(expected_skip)++ def test_webhook_path_drains_manager_when_enabled(self) -> None:+ # Gate skipped + webhook_enabled True: items() reads the webhook manager (S3+ # parquet) instead of running the zero-row workflow_jobs poll.+ manager = self._make_webhook_manager(enabled=True)+ response = github_source(+ personal_access_token="token",+ repository="owner/repo",+ endpoint="workflow_jobs",+ logger=mock.Mock(),+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ webhook_source_manager=manager,+ )+ # items() is typed Iterator | AsyncIterator; the webhook path returns the sync one.+ assert list(cast(Iterator[Any], response.items())) == [{"id": 1}]+ manager.get_items.assert_called_once()++class TestGetRowsResume:"""Integration tests for the fresh-run and resume flows in get_rows."""@@ -1133,11 +1192,8 @@ class TestFanOutJobs:assert any("/runs/1003/jobs" in c for c in jobs_calls)assert not any("/runs/1001/jobs" in c for c in jobs_calls)- def test_first_incremental_sync_floors_fan_out_to_lookback_window(self) -> None:- # First incremental sync (watermark configured, nothing synced yet): the- # backfill is floored at settings' initial_lookback_days instead of crawling- # all history. Runs are newest-first; 1003 lands a day before the frozen now- # (inside any small window) and 1001 over a month back (outside).+ def _make_first_sync_session(self) -> tuple[datetime, _RoutingSession]:+ # Two runs newest-first: 1003 a day before the frozen now, 1001 over a month back.frozen_now = datetime(2026, 2, 20, tzinfo=UTC)session = _RoutingSession(runs_pages=[(_runs_envelope(_run("2026-02-19T00:00:00Z", 1003), _run("2026-01-10T00:00:00Z", 1001)), "")],@@ -1146,13 +1202,31 @@ class TestFanOutJobs:1001: (_jobs_envelope({"id": 1, "run_id": 1001}), ""),},)+ return frozen_now, session++ def _fan_out_with_lookback(self, session: _RoutingSession, lookback_days: int | None, **kwargs: Any) -> list[Any]:+ # Override the production initial_lookback_days so the floor mechanism can be+ # tested independently of whatever default the workflow_jobs endpoint ships.+ patched = dict(GITHUB_ENDPOINTS)+ patched["workflow_jobs"] = dataclasses.replace(+ GITHUB_ENDPOINTS["workflow_jobs"], initial_lookback_days=lookback_days+ )+ with mock.patch("posthog.temporal.data_imports.sources.github.github.GITHUB_ENDPOINTS", patched):+ return self._fan_out(session, **kwargs)++ def test_first_incremental_sync_floors_fan_out_to_lookback_window(self) -> None:+ # First incremental sync (watermark configured, nothing synced yet) with a+ # non-zero floor: the backfill is bounded at initial_lookback_days instead of+ # crawling all history. 1003 is inside a 30-day window, 1001 is outside.+ frozen_now, session = self._make_first_sync_session()with mock.patch("posthog.temporal.data_imports.sources.github.github._now_utc",return_value=frozen_now,):- rows = self._fan_out(+ rows = self._fan_out_with_lookback(session,+ lookback_days=30,should_use_incremental_field=True,db_incremental_field_last_value=None,)@@ -1164,6 +1238,26 @@ class TestFanOutJobs:assert any("/runs/1003/jobs" in c for c in jobs_calls)assert not any("/runs/1001/jobs" in c for c in jobs_calls)+ def test_first_incremental_sync_does_no_backfill_by_default(self) -> None:+ # The shipped default is initial_lookback_days=0: the per-run fan-out is too+ # expensive to backfill at high run volume, so the first sync fans out over+ # nothing and the webhook becomes the source of truth. Both historical runs+ # are skipped — no jobs request is made for either.+ frozen_now, session = self._make_first_sync_session()++ with mock.patch(+ "posthog.temporal.data_imports.sources.github.github._now_utc",+ return_value=frozen_now,+ ):+ rows = self._fan_out(+ session,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )++ assert rows == []+ assert not any("/jobs" in c for c in session.calls)+def test_resume_starts_from_saved_parent_page_url(self) -> None:saved_url = "https://api.github.com/repos/owner/repo/actions/runs?per_page=100&page=3"manager = _make_manager(can_resume=True, resume_state=GithubResumeConfig(next_url=saved_url))@@ -1311,6 +1405,23 @@ class TestGithubWebhookSource:webhook_capable = {s.name for s in schemas if s.supports_webhooks}assert webhook_capable == {"workflow_jobs", "workflow_runs"}+ def test_workflow_jobs_is_webhook_only_but_workflow_runs_keeps_poll(self) -> None:+ # workflow_jobs does no poll backfill (zero floor), so it must not be offered as a+ # poll mode that would sync an empty table forever — it's webhook-only. workflow_runs+ # still has a real poll backfill and stays incremental/append-capable.+ by_name = {s.name: s for s in self.source.get_schemas(_pat_config(), team_id=1)}++ jobs = by_name["workflow_jobs"]+ assert jobs.webhook_only is True+ assert jobs.supports_incremental is False+ assert jobs.supports_append is False+ assert jobs.supports_webhooks is True++ runs = by_name["workflow_runs"]+ assert runs.webhook_only is False+ assert runs.supports_incremental is True+ assert runs.supports_webhooks is True+@parameterized.expand([("both", ["workflow_jobs", "workflow_runs"], ["workflow_job", "workflow_run"]),@@ -1441,3 +1552,116 @@ class TestGithubWebhookSource:assert info.exists is Trueassert info.url == webhook_url+++# A response that raise_if_github_rate_limited classifies as rate limited: 429 is+# rate limited regardless of body, 403 only when the body mentions a rate limit.+# headers carry x-ratelimit-reset / retry-after for the wait.+def _rate_limited_response(status: int, body_text: str, headers: dict[str, str]) -> mock.Mock:+ resp = mock.Mock()+ resp.status_code = status+ resp.text = body_text+ resp.headers = headers+ return resp+++def _retry_state_with_exception(exc: BaseException) -> RetryCallState:+ state = RetryCallState(retry_object=mock.Mock(), fn=None, args=(), kwargs={})+ state.attempt_number = 1+ state.outcome = Future.construct(1, exc, has_exception=True)+ return state+++# _github_retry_wait must honor GitHub's advertised rate-limit reset (capped) and+# fall back to plain backoff for transient errors that carry no reset.+class TestGithubRetryWait:+ def test_honors_retry_after_with_jitter(self) -> None:+ wait = _github_retry_wait(_retry_state_with_exception(GitHubRateLimitError("rl", retry_after=60)))+ # The honored reset plus up to a second of jitter — not the short backoff.+ assert 60.0 <= wait <= 61.0++ def test_caps_oversized_retry_after(self) -> None:+ # A misreported reset header must not stall a worker past the cap.+ wait = _github_retry_wait(_retry_state_with_exception(GitHubRateLimitError("rl", retry_after=99999)))+ assert GITHUB_MAX_RETRY_AFTER_SECONDS <= wait <= GITHUB_MAX_RETRY_AFTER_SECONDS + 1.0++ @parameterized.expand(+ [+ # Rate limit with no parseable reset -> falls back to backoff, not a 0s spin.+ ("rate_limit_without_reset", GitHubRateLimitError("rl", retry_after=None)),+ # Transient server / connection blips never carry a reset.+ ("retryable_error", GithubRetryableError("boom")),+ ("connection_error", requests.ConnectionError("boom")),+ ]+ )+ def test_falls_back_to_backoff(self, _name: str, exc: BaseException) -> None:+ wait = _github_retry_wait(_retry_state_with_exception(exc))+ # wait_exponential_jitter(initial=1, max=30) stays well under the rate-limit cap.+ assert 0.0 <= wait <= 31.0+++# _fetch_page must retry GitHub rate limits (honoring the reset) instead of treating+# the 403 as fatal, while a genuine permission 403 stays fatal.+class TestFetchPageRateLimit:+ @parameterized.expand(+ [+ # Secondary limit: 429 regardless of body.+ ("secondary_429", 429, "Too Many Requests"),+ # Primary limit: 403 whose body names a rate limit.+ ("primary_403", 403, "API rate limit exceeded for installation"),+ ]+ )+ def test_rate_limited_response_is_retried_then_reraised(self, _name: str, status: int, body_text: str) -> None:+ resp = _rate_limited_response(status, body_text, {"retry-after": "1"})++ with (+ mock.patch("time.sleep"),+ mock.patch("posthog.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get,+ ):+ mock_get.return_value.get.return_value = resp+ with pytest.raises(GitHubRateLimitError):+ _fetch_page("https://api.github.com/x", {}, mock.Mock())++ # stop_after_attempt(5): the rate limit is retried, not treated as fatal on first hit.+ assert mock_get.return_value.get.call_count == 5++ def test_recovers_when_rate_limit_clears(self) -> None:+ rate_limited = _rate_limited_response(429, "Too Many Requests", {"retry-after": "1"})+ ok = _make_response(status=200, body=[{"id": 1}])++ with (+ mock.patch("time.sleep"),+ mock.patch("posthog.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get,+ ):+ mock_get.return_value.get.side_effect = [rate_limited, ok]+ response = _fetch_page("https://api.github.com/x", {}, mock.Mock())++ assert response is ok+ assert mock_get.return_value.get.call_count == 2++ def test_permission_403_is_fatal_not_retried(self) -> None:+ # A 403 with no rate-limit body is a real permission error: surface it+ # immediately rather than burning retries on something that won't clear.+ resp = _make_response(status=403, body={"message": "Resource not accessible by integration"})+ resp.text = '{"message": "Resource not accessible by integration"}'+ resp.raise_for_status.side_effect = requests.HTTPError("403 Client Error", response=resp)++ with mock.patch("posthog.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get:+ mock_get.return_value.get.return_value = resp+ with pytest.raises(requests.HTTPError):+ _fetch_page("https://api.github.com/x", {}, mock.Mock())++ assert mock_get.return_value.get.call_count == 1++ def test_disables_adapter_retries_so_cap_is_authoritative(self) -> None:+ # The tracked session's default adapter retries 429/5xx and honors Retry-After+ # uncapped, underneath us — which would defeat the 300s cap. _fetch_page must+ # request a no-retry adapter so our tenacity layer owns the backoff.+ ok = _make_response(status=200, body=[{"id": 1}])++ with mock.patch("posthog.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get:+ mock_get.return_value.get.return_value = ok+ _fetch_page("https://api.github.com/x", {}, mock.Mock())++ retry = mock_get.call_args.kwargs["retry"]+ assert retry.total == 0