: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): wait out our own github egress budget instead of hammering it (#104414)
Tom Owersb6e53159e5b1
diff --git a/posthog/egress/github/transport.py b/posthog/egress/github/transport.pyindex 56e9b4cf51de..76bc97119270 100644--- a/posthog/egress/github/transport.py+++ b/posthog/egress/github/transport.py@@ -106,7 +106,9 @@ class GitHubClient(EgressClient):)def _budget_exhausted_error(self, scope: str) -> GitHubEgressBudgetExhausted:- return GitHubEgressBudgetExhausted(f"GitHub egress budget exhausted for installation {scope}; deferring")+ return GitHubEgressBudgetExhausted(+ f"GitHub egress budget exhausted for installation {scope}; deferring", scope=scope+ )# Stateless — one shared instance for the whole process.diff --git a/posthog/egress/transport/transport.py b/posthog/egress/transport/transport.pyindex 62c5641fe433..6c89c82da65a 100644--- a/posthog/egress/transport/transport.py+++ b/posthog/egress/transport/transport.py@@ -37,7 +37,19 @@ class EgressBudgetExhausted(Exception):"""A *sheddable* (non-CRITICAL) outbound call was denied by the egress limiter before it was sent.Callers that can defer should catch this and back off/retry — it means our own shared budget isspent, not that the third-party API returned an error. CRITICAL calls are never raised on; they- proceed and let the API's own rate limiting be the backstop."""+ proceed and let the API's own rate limiting be the backstop.++ ``scope`` is the budget key that was denied (a GitHub installation id, say). It rides on the+ exception because this is *our* budget: unlike a third-party 429, the limiter can say how long+ until it frees, and a caller that wants to wait for it needs the key to ask. Subclasses that+ name the scope in their message should pass it here too rather than leaving callers to parse+ it back out."""++ def __init__(self, message: str = "", *, scope: str | None = None) -> None:+ # Defaulted so this stays a pure addition: before ``scope`` existed this was a bare+ # Exception, and callers that raise it as a marker construct it with no arguments.+ super().__init__(message)+ self.scope = scopedef _raise_if_denied(granted: bool, priority: Priority, make_error: Callable[[], EgressBudgetExhausted]) -> None: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 5e42ba124e0e..596b03619c3a 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@@ -863,14 +863,30 @@ def _repository_resolves(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."""+ """Sleep until the limit that shed this call frees, whichever limit it was.++ Both twins get a timed wait, capped, plus a little jitter so the sources sharing one+ installation's budget don't all wake at the same instant:++ - ``GitHubRateLimitError`` is GitHub's own limit, and it advertises the reset.+ - ``GitHubEgressBudgetExhausted`` is *our* limit, and the limiter knows the pace — the+ same question :func:`_pace_before_request` asks before every request.++ Only the fall-through is blind exponential backoff, which is capped at 30 seconds and so+ cannot outlast either window. Leaving our own budget on that path meant a shed page+ retried five times inside ~2 minutes, failed the activity, and let Temporal restart the+ whole extraction — the shape behind a burst of ~9,700 shed-call errors in one hour.+ """if state.outcome is not None and state.outcome.failed:exc = state.outcome.exception()if isinstance(exc, GitHubRateLimitError) and exc.retry_after is not None:return min(float(exc.retry_after), GITHUB_MAX_RETRY_AFTER_SECONDS) + random.uniform(0, 1)+ if isinstance(exc, GitHubEgressBudgetExhausted) and exc.scope:+ # Zero means the budget already refilled between the denial and now, so fall through+ # rather than returning a no-wait retry that would just hammer the gate again.+ pace = github_installation_pace_seconds(exc.scope, priority=Priority.BATCH)+ if pace > 0:+ return min(pace, GITHUB_MAX_RETRY_AFTER_SECONDS) + random.uniform(0, 1)return _github_backoff_wait(state)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 38c9903d6d2b..74a6fc264bc0 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@@ -375,8 +375,14 @@ If automatic creation failed with a permissions error, the fix depends on how yo# Either way it's a dropped connection, not a GitHub or customer problem, so once Temporal# retries the activity the failure is transient and self-recovering. Mirrors ClickHouse's# equivalent classification of the same urllib3/OpenSSL wording.+ #+ # A GitHubEgressBudgetExhausted gets the same treatment as the GitHub-side rate limit it is+ # the twin of. It is our own limiter shedding a deferrable call on purpose, so it is the+ # least surprising failure the source has; tracking it as an exception put a self-inflicted,+ # self-healing condition at the top of the pipeline-error groups.return {"GitHub API rate limit exceeded",+ "GitHub egress budget exhausted","Github API error (retryable)","UNEXPECTED_EOF_WHILE_READING","EOF occurred in violation of protocol",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.pyindex 4a606d0bfa3c..e3ebcb35d326 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py@@ -5,6 +5,10 @@ from unittest import mockimport requestsfrom prometheus_client import REGISTRY+from tenacity import (+ Future as TenacityFuture,+ RetryCallState,+)from posthog.egress.github.limiter import GitHubRateResourcefrom posthog.egress.limiter.policies import Priority@@ -193,6 +197,53 @@ def test_fetch_page_reraises_chunked_encoding_error_after_exhausting_retries():assert after - before == session.request.call_count+def _failed_retry_state(exc: BaseException) -> RetryCallState:+ state = RetryCallState(retry_object=mock.Mock(), fn=mock.Mock(), args=(), kwargs={})+ outcome: TenacityFuture = TenacityFuture(attempt_number=1)+ outcome.set_exception(exc)+ state.outcome = outcome+ return state+++ "pace,expected_floor,expected_ceiling",+ [+ # The limiter's own answer, which the blind exponential backoff (capped at 30s) cannot reach.+ (120.0, 120.0, 121.0),+ # Clamped to the same ceiling the GitHub-side Retry-After path honors.+ (9999.0, github.GITHUB_MAX_RETRY_AFTER_SECONDS, github.GITHUB_MAX_RETRY_AFTER_SECONDS + 1.0),+ # Budget already refilled: fall through to backoff rather than retrying with no wait at all.+ (0.0, 0.0, 0.0),+ ],+ ids=["waits-the-limiters-pace", "clamped-to-ceiling", "refilled-falls-through"],+)+def test_retry_wait_asks_the_limiter_how_long_our_own_budget_needs(pace, expected_floor, expected_ceiling):+ # Our budget, so the limiter knows when it frees. Leaving this on the 30s-capped exponential+ # meant a shed page burned five attempts in ~2 minutes and failed the activity, letting Temporal+ # restart the whole extraction.+ exc = github.GitHubEgressBudgetExhausted(+ "GitHub egress budget exhausted for installation 42; deferring", scope="42"+ )++ with mock.patch.object(github, "github_installation_pace_seconds", return_value=pace) as paced:+ wait = github._github_retry_wait(_failed_retry_state(exc))++ assert expected_floor <= wait <= expected_ceiling+ assert paced.call_args.args[0] == "42"+ assert paced.call_args.kwargs["priority"] == Priority.BATCH+++def test_retry_wait_falls_through_when_the_budget_error_carries_no_scope():+ # An identity-blind caller has no budget key, so there is nothing to ask the limiter about.+ exc = github.GitHubEgressBudgetExhausted("GitHub egress budget exhausted; deferring")++ with mock.patch.object(github, "github_installation_pace_seconds") as paced:+ wait = github._github_retry_wait(_failed_retry_state(exc))++ assert wait == 0.0+ paced.assert_not_called()++def test_fetch_page_gates_on_egress_budget_when_installation_known():# App path: a denied BATCH gate must defer (raise the retryable error) without ever sending the# request, and the gate must run on every retry attempt before reraising.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 73ca2648d341..d7abbaa7c88a 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@@ -139,6 +139,16 @@ class TestGithubSource:retryable_errors = self.source.get_retryable_errors()assert error_message_matches(observed_error, retryable_errors)+ def test_egress_budget_exhausted_is_retryable_not_non_retryable(self):+ # Our own limiter shedding a deferrable call is the twin of GitHub's rate limit above, and+ # must be classified the same way: tracking it as an exception put a self-inflicted,+ # self-healing condition at the top of the pipeline-error groups.+ observed_error = "GitHub egress budget exhausted for installation 99844466; deferring"+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in observed_error for key in non_retryable_errors)+ retryable_errors = self.source.get_retryable_errors()+ assert error_message_matches(observed_error, retryable_errors)+def test_transient_5xx_error_is_retryable_not_non_retryable(self):# A GithubRetryableError (any transient upstream 5xx) that exhausts _fetch_page's tenacity# retry must stay retryable, so a GitHub-side outage doesn't disable the source.