: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(egress): release the GitHub batch reserve on quiet installations (#88224)
Tom Owers8422154d32e3
diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex ae7dcb576594..12d12b399905 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -69,6 +69,12 @@ Admission tests `n + reserve` but only consumes `n`, so an empty reserve is bit-GitHub's reserve ladder is active: `BATCH` calls are denied once 70% of a window is consumed and `NORMAL` at 90%, while `CRITICAL` may use the full budget.Deferrable background callers construct their client on the `BATCH` lane (`GitHubIntegration(integration, source=..., priority=Priority.BATCH)`; `api_request` also takes a per-call override) — a shed sweep stops for the cycle and resumes on the next scheduled run.+The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.+An installation whose only consumer is a bulk one — a warehouse backfill of a repository nothing else touches — would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.+So a non-`BATCH` `core` call writes a short-lived per-installation marker (`note_interactive_demand`), and the policy holds the full 70% floor only while that marker is present; without it `BATCH` falls back to a 10% floor — the same floor `NORMAL` keeps.+Three details make that safe: the marker is written on the attempt rather than the outcome, so a _denied_ interactive call still counts; the floor matches `NORMAL`'s rather than dropping toward zero, so an unopposed backfill can never saturate the window past the point where the first interactive call would itself be denied, regardless of the marker it just wrote; and an unreachable cache reports demand as present, so a cache outage cannot hand the whole budget to bulk traffic.+The two search resources keep the flat ladder — they are metered on their own counters, so core demand says nothing about them.+### BackendA sliding-window counter over Redis holds the shared budget across worker processes — O(1) memory per key, self-expiring, no background grooming.diff --git a/posthog/egress/github/limiter.py b/posthog/egress/github/limiter.pyindex 73db66da0617..dfccb9c03e5a 100644--- a/posthog/egress/github/limiter.py+++ b/posthog/egress/github/limiter.py@@ -74,6 +74,26 @@ _RESOURCE_DOMAINS: dict[GitHubRateResource, str] = {# headroom for user-facing traffic as an installation's budget fills._RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}+# Applied instead when an installation has served no recent interactive traffic. The BATCH floor+# above keeps headroom for user-facing calls; on an installation whose only consumer is a bulk one+# — a warehouse backfill of a repository nothing else touches — it holds that headroom against+# contention which never arrives, and forfeits a third of the budget for the whole run. The hourly+# budget is what decides whether a large backfill finishes, so that third is the difference between+# one run and several.+#+# BATCH keeps a floor rather than the entire budget, and that floor is never smaller than NORMAL's+# own (0.10): a zero floor denies the first interactive call before its own marker can apply, and+# anything smaller than NORMAL's floor lets an unopposed backfill saturate the window past the+# point where that first interactive call would be admitted at all, regardless of the marker it+# just wrote. NORMAL's floor itself stays unchanged, because CRITICAL traffic arrives with no+# warning.+_IDLE_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.10, Priority.NORMAL: 0.10}++# How long one interactive call holds the full reserve in place. Longer than a quiet gap in genuine+# interactive use, so the budget does not flap part-way through a backfill, and far shorter than a+# backfill, so a single configuration action does not reserve headroom for hours.+INTERACTIVE_DEMAND_TTL_SECONDS = 15 * 60+# Default under GitHub's real 15k/hr ceiling so the reactive backoff (GitHubRateLimitError in# posthog/egress/github/transport.py) absorbs drift between our local count and GitHub's actual# counter — clock skew, multi-process races, and untracked PAT traffic on the same account.@@ -109,11 +129,24 @@ _observed_memo: dict[str, tuple[int | None, float]] = {}_REWRITE_INTERVAL_SECONDS = 3600.0_last_written: dict[str, tuple[int, float]] = {}+# Same reasoning for the interactive-demand marker, with a shorter memo: this value flips within a+# session rather than with a customer's GitHub plan, and a stale True only delays a budget the+# backfill was not using a moment ago. The rewrite interval stays well inside the marker's TTL so a+# steady stream of interactive calls keeps it alive.+_INTERACTIVE_MEMO_TTL_SECONDS = 10.0+_interactive_memo: dict[str, tuple[bool, float]] = {}+_INTERACTIVE_REWRITE_INTERVAL_SECONDS = 60.0+_interactive_last_written: dict[str, float] = {}+def observed_core_limit_cache_key(installation_id: str) -> str:return f"github_egress:observed_core_limit:{installation_id}"+def interactive_demand_cache_key(installation_id: str) -> str:+ return f"github_egress:interactive_demand:{installation_id}"++def installation_id_from_key(key: str) -> str:"""Inverse of :func:`github_installation_key` — the key shape lives in this pair only."""return key.rpartition(":")[2]@@ -175,6 +208,45 @@ def remember_observed_core_limit(installation_id: str | None, response: "requestpass+def note_interactive_demand(installation_id: str | int) -> None:+ """Record that interactive traffic is using this installation's ``core`` budget.++ Called on the attempt, not on the outcome: a denied interactive call is the strongest evidence+ that the reserve is needed, so it has to count. Best-effort — a cache failure leaves the budget+ unreserved, which is what an installation with no interactive traffic gets anyway.+ """+ key = str(installation_id)+ now = time.monotonic()+ _interactive_memo[key] = (True, now)+ last_written = _interactive_last_written.get(key)+ if last_written is not None and now - last_written < _INTERACTIVE_REWRITE_INTERVAL_SECONDS:+ return+ try:+ cache.set(interactive_demand_cache_key(key), True, INTERACTIVE_DEMAND_TTL_SECONDS)+ _interactive_last_written[key] = now+ except Exception:+ pass+++def has_interactive_demand(installation_id: str) -> bool:+ """Whether interactive traffic used this installation's ``core`` budget recently.++ An unreachable cache answers ``True``. Every other best-effort read here degrades toward the+ safer default, and the safer default for a reserve that protects user-facing traffic is to keep+ it — the cost is a slower backfill, against starving an interactive call.+ """+ now = time.monotonic()+ memoized = _interactive_memo.get(installation_id)+ if memoized is not None and now - memoized[1] < _INTERACTIVE_MEMO_TTL_SECONDS:+ return memoized[0]+ try:+ present = bool(cache.get(interactive_demand_cache_key(installation_id)))+ except Exception:+ return True+ _interactive_memo[installation_id] = (present, now)+ return present++def _hourly_budget() -> int:return int(getattr(settings, "GITHUB_EGRESS_HOURLY_BUDGET", _DEFAULT_HOURLY_BUDGET))@@ -204,11 +276,12 @@ def _tier_budgets(observed_limit: int | None) -> tuple[int, int]:# spend. Registered as a provider so budgets are read at acquire time (settings + the observed tier# for the key's installation), not frozen at import.def _github_policy(key: str) -> RatePolicy:- hourly, per_minute = _tier_budgets(get_observed_core_limit(installation_id_from_key(key)))+ installation_id = installation_id_from_key(key)+ hourly, per_minute = _tier_budgets(get_observed_core_limit(installation_id))return RatePolicy(limits=((per_minute, 60.0), (hourly, 3600.0)),in_memory_divider=4,- reserve=_RESERVE,+ reserve=_RESERVE if has_interactive_demand(installation_id) else _IDLE_RESERVE,)@@ -237,6 +310,16 @@ def github_installation_key(return f"{_RESOURCE_DOMAINS[resource]}:installation:{installation_id}"+def _note_demand_if_interactive(installation_id: str | int, priority: Priority, resource: GitHubRateResource) -> None:+ """Stamp the demand marker for a non-BATCH ``core`` call.++ Scoped to ``core`` because only the core policy consults the marker; the two search budgets are+ static and metered on their own counters, so search demand says nothing about core headroom.+ """+ if resource is GitHubRateResource.CORE and priority is not Priority.BATCH:+ note_interactive_demand(installation_id)++async def acquire_github_installation(installation_id: str | int,n: int = 1,@@ -248,6 +331,7 @@ async def acquire_github_installation("""Reserve ``n`` requests against an installation's budget for ``resource``. Returns False when thebudget (or this ``priority``'s reserved floor) is exhausted — back off and retry rather thancalling GitHub."""+ _note_demand_if_interactive(installation_id, priority, resource)return await get_outbound_rate_limiter().acquire(github_installation_key(installation_id, resource=resource), n, priority=priority, source=source)@@ -263,6 +347,7 @@ def consume_github_installation_sync() -> bool:"""Sync variant of :func:`acquire_github_installation` for callers outside an event loop (e.g. thewarehouse source iterator, which runs in a thread pool)."""+ _note_demand_if_interactive(installation_id, priority, resource)return get_outbound_rate_limiter().consume_sync(github_installation_key(installation_id, resource=resource), n, priority=priority, source=source)diff --git a/posthog/egress/test/test_github_limiter.py b/posthog/egress/test/test_github_limiter.pyindex 4484c01a277b..3a053d540f31 100644--- a/posthog/egress/test/test_github_limiter.py+++ b/posthog/egress/test/test_github_limiter.py@@ -1,5 +1,7 @@import uuid+from unittest.mock import patch+from django.core.cache import cachefrom django.test import SimpleTestCase@@ -8,14 +10,22 @@ from parameterized import parameterizedfrom requests.structures import CaseInsensitiveDictfrom posthog.egress.github.limiter import (+ _IDLE_RESERVE,+ _RESERVE,GitHubRateResource,+ _interactive_last_written,+ _interactive_memo,_last_written,_observed_memo,_tier_budgets,classify_github_resource,+ consume_github_installation_sync,get_observed_core_limit,github_installation_key,+ has_interactive_demand,installation_id_from_key,+ interactive_demand_cache_key,+ note_interactive_demand,observed_core_limit_cache_key,remember_observed_core_limit,)@@ -38,10 +48,15 @@ class GitHubLimiterTestCase(SimpleTestCase):super().setUp()_observed_memo.clear()_last_written.clear()+ _interactive_memo.clear()+ _interactive_last_written.clear()self.installation_id = f"test-{uuid.uuid4().hex[:8]}"self.addCleanup(cache.delete, observed_core_limit_cache_key(self.installation_id))+ self.addCleanup(cache.delete, interactive_demand_cache_key(self.installation_id))self.addCleanup(_observed_memo.clear)self.addCleanup(_last_written.clear)+ self.addCleanup(_interactive_memo.clear)+ self.addCleanup(_interactive_last_written.clear)class TestGitHubTierBudgets(GitHubLimiterTestCase):@@ -66,16 +81,32 @@ class TestGitHubTierBudgets(GitHubLimiterTestCase):with self.settings(GITHUB_EGRESS_PER_MINUTE_BUDGET=200):assert _tier_budgets(15_000) == (13_500, 200)- def test_policy_reads_observed_tier_for_the_keys_installation(self) -> None:- # Guards the wiring: key parsing + tier read + reserve attach. If resolve_policy stops- # passing the key, or the store's key drifts from the writer's, every installation silently- # falls back to the flat default budget and the reserve ladder detaches.+ @parameterized.expand(+ [+ ("interactive_demand_holds_the_full_reserve", True, _RESERVE),+ ("idle_installation_releases_it_to_batch", False, _IDLE_RESERVE),+ ]+ )+ def test_policy_reads_observed_tier_and_reserve_for_the_keys_installation(+ self, _name: str, interactive: bool, expected_reserve: dict[Priority, float]+ ) -> None:+ # Guards the wiring: key parsing + tier read + reserve selection. If resolve_policy stops+ # passing the key, or either store's key drifts from its writer's, every installation+ # silently falls back to the flat default budget and the reserve ladder detaches.+ #+ # The reserve branch decides how much of an installation's hourly budget a backfill may+ # use, and neither way of breaking it raises: stuck on the full reserve costs a bulk sync a+ # third of every hour, and stuck on the idle one lets it starve interactive traffic.+ # Asserted against the constants, so retuning either ladder is not a test change.cache.set(observed_core_limit_cache_key(self.installation_id), 5_000, 60)+ if interactive:+ note_interactive_demand(self.installation_id)policy = resolve_policy(github_installation_key(self.installation_id))assert policy.limits == ((250, 60.0), (4_500, 3600.0))- assert policy.reserve_fraction(Priority.BATCH) > policy.reserve_fraction(Priority.NORMAL) > 0.0+ assert policy.reserve_fraction(Priority.BATCH) == expected_reserve[Priority.BATCH]+ assert policy.reserve_fraction(Priority.NORMAL) == expected_reserve[Priority.NORMAL]assert policy.reserve_fraction(Priority.CRITICAL) == 0.0@@ -115,6 +146,45 @@ class TestObservedCoreLimitStore(GitHubLimiterTestCase):assert get_observed_core_limit(self.installation_id) is None+class TestInteractiveDemandMarker(GitHubLimiterTestCase):+ # The marker is what lets a bulk sync use an idle installation's whole budget, so both ways of+ # mis-scoping it are silent. Stamping for BATCH makes a warehouse sync record its own demand and+ # reserve headroom against itself, which returns the backfill to 70% and looks like no change at+ # all. Stamping for a search call reserves core headroom on the strength of a different counter.+ @parameterized.expand(+ [+ ("critical_core_counts", Priority.CRITICAL, GitHubRateResource.CORE, True),+ ("normal_core_counts", Priority.NORMAL, GitHubRateResource.CORE, True),+ ("batch_core_does_not", Priority.BATCH, GitHubRateResource.CORE, False),+ ("normal_search_does_not", Priority.NORMAL, GitHubRateResource.SEARCH, False),+ ]+ )+ def test_only_interactive_core_calls_mark_demand(+ self, _name: str, priority: Priority, resource: GitHubRateResource, expected: bool+ ) -> None:+ consume_github_installation_sync(self.installation_id, priority=priority, resource=resource)++ # Read through the shared cache, the way another worker process would.+ _interactive_memo.clear()+ assert has_interactive_demand(self.installation_id) is expected++ def test_demand_is_marked_even_when_the_call_is_denied(self) -> None:+ # A denied interactive call is the moment the reserve matters most, so gating the stamp on+ # the admission result would drop the signal exactly when it is needed.+ with patch("posthog.egress.github.limiter.get_outbound_rate_limiter") as limiter:+ limiter.return_value.consume_sync.return_value = False+ assert consume_github_installation_sync(self.installation_id, priority=Priority.NORMAL) is False++ _interactive_memo.clear()+ assert has_interactive_demand(self.installation_id) is True++ def test_unreachable_cache_keeps_the_reserve(self) -> None:+ # Failing open here would hand every installation's full budget to bulk traffic during a+ # cache outage, so the unknown answer has to be the protective one.+ with patch("posthog.egress.github.limiter.cache.get", side_effect=Exception("cache unavailable")):+ assert has_interactive_demand(self.installation_id) is True++class TestClassifyGithubResource(SimpleTestCase):# The routing that this whole fix hinges on: a /search/code call charged to core would sail# through the 5k/hour budget while GitHub 403/429s it at 10/min. Guards that each URL lands on