: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
feat(egress): tier-aware GitHub budgets and real priority lanes (#67713)
Julian Bezabb026003427
diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex aa721d876d4a..9c703a3ecfb9 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -38,15 +38,18 @@ The GitHub helpers wrap the key construction; other domains expose their own thi### Budgets (policies)A budget is a `RatePolicy`: one or more `(count, period_seconds)` limits enforced _together_, so you can cap the hour and smooth per-minute bursts on the same key.-Each domain registers its policy with `register_policy(domain, policy)`, usually as a zero-arg provider so the budget is read from Django settings at acquire time rather than frozen at import.-GitHub's budget is per **installation** (the unit GitHub meters): 13,500 requests/hour plus a 450/minute smoothing cap, deliberately under GitHub's real 15,000/hour ceiling so reactive backoff absorbs drift (clock skew, multi-process races, untracked PAT traffic on the same account).+Each domain registers its policy with `register_policy(domain, policy)`, usually as a provider taking the full limiter key, so the budget is read at acquire time (settings + per-scope state) rather than frozen at import.+GitHub's budget is per **installation** (the unit GitHub meters), scaled to the installation's real tier: `api_request` persists each installation's last-observed core `X-RateLimit-Limit` (only trusted installation-token responses feed this), and the policy budgets 90% of it for the hour with a proportional per-minute smoothing cap (most installations sit on GitHub's 5,000/hour tier, not the 15,000 top tier).+Unobserved installations fall back to the settings defaults (13,500/hour + 750/minute) until their first recorded response.+Budgets stay deliberately under the real ceiling so reactive backoff absorbs drift (clock skew, multi-process races, untracked PAT traffic on the same account).### Priority lanesPriority (`CRITICAL` / `NORMAL` / `BATCH`) controls how sheddable a call is when the budget gets tight.All priorities draw from the _same_ per-key counter — the lane only changes how much headroom must stay free for the call to be admitted (a _reserved floor_), so deferrable bulk traffic (`BATCH`) is denied before critical traffic as the budget fills, without ever splitting the budget into separate buckets.Admission tests `n + reserve` but only consumes `n`, so an empty reserve is bit-identical to pre-priority behavior.-GitHub ships with no active reserves yet: the mechanism is wired end to end (callers already declare their lane), and turning it on is a one-line change once a `CRITICAL` path is actually gated.+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.### Backenddiff --git a/posthog/egress/github/limiter.py b/posthog/egress/github/limiter.pyindex 09ff8fb497e1..75e405b27dae 100644--- a/posthog/egress/github/limiter.py+++ b/posthog/egress/github/limiter.py@@ -1,41 +1,135 @@"""GitHub egress — the first consumer of the outbound rate limiter.-A GitHub App installation gets 15,000 REST requests/hour, shared across every PostHog-consumer of that installation (warehouse sources, Tasks, Code, Conversations, Visual-review). This module registers that budget as a policy keyed per installation and exposes-a thin gate other GitHub call sites can adopt one line at a time.+A GitHub App installation gets 5,000–15,000 REST requests/hour depending on the account's+plan tier, shared across every PostHog consumer of that installation (warehouse sources,+Tasks, Code, Conversations, Visual review). This module budgets each installation to its+observed tier and registers that budget as a policy keyed per installation. The budget is+one shared envelope across GitHub's resources (REST core, GraphQL, …) — deliberately+conservative rather than modeling each resource's separate meter.Importing this module registers the policy as a side effect — import it (directly or via``acquire_github_installation``) before using a ``github:...`` limiter key."""+import time+from typing import TYPE_CHECKING+from django.conf import settings+from django.core.cache import cache++if TYPE_CHECKING:+ import requestsfrom posthog.egress.limiter.outbound import get_outbound_rate_limiterfrom posthog.egress.limiter.policies import Priority, RatePolicy, register_policyGITHUB_DOMAIN = "github"-# No reserves are active yet — a deliberate default, not a limitation. Every GitHub call now gates-# through the limiter: user-facing traffic at CRITICAL (integration, visual review, conversations,-# error tracking), warehouse at BATCH, the job-logs worker at NORMAL. So a BATCH reserve would now-# have a real beneficiary — it would shed deferrable warehouse polling before critical traffic as the-# budget fills. It stays empty until the grant/deny metrics show the shared budget (13.5k under-# GitHub's 15k) actually getting tight; turning it on is a one-line change here — e.g.-# {Priority.BATCH: 0.30} to shed warehouse polling first.-_RESERVE: dict[Priority, float] = {}+# Reserved-floor ladder: BATCH calls are denied once 70% of a window is consumed, NORMAL at 90%,+# CRITICAL can use the full budget. Active now that deferrable callers declare their lane+# (code-workstreams polling and the job-logs worker at BATCH) — shedding them first is what keeps+# headroom for user-facing traffic as an installation's budget fills.+_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}# 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.+# When the installation's real limit has been observed from response headers, the budget scales+# down to that tier instead (see _tier_budgets) — most installations sit on GitHub's 5k tier,+# where this default would never fire._DEFAULT_HOURLY_BUDGET = 13_500-# A per-minute smoothing cap layered on top of the hourly budget. High enough that a normal-# failed run (a handful of jobs) never touches it, low enough that no single consumer can drain-# the shared hourly budget in seconds and that we stay clear of GitHub's secondary (per-minute-# abuse) limits. Under sustained pressure a flood drains at ~this rate, leaving budget for-# co-tenant consumers each minute (~hourly/30 — the hour can't empty faster than ~half an hour).-_DEFAULT_PER_MINUTE_BUDGET = 450+# A per-minute smoothing cap layered on top of the hourly budget, so no single consumer can drain+# the shared hourly budget in seconds and we stay clear of GitHub's documented ~900 requests/min+# secondary limit (750 keeps a comfortable margin under it). Both settings are operator ceilings:+# tier scaling can only lower them, never exceed them.+_DEFAULT_PER_MINUTE_BUDGET = 750++# The installation's core-resource X-RateLimit-Limit, as last observed from a successful+# installation-token response (written by GitHubIntegrationBase.api_request via+# remember_observed_core_limit). Long TTL: the tier changes only when the customer's GitHub plan+# does, and any traffic refreshes it.+OBSERVED_CORE_LIMIT_TTL_SECONDS = 7 * 24 * 3600++# Below GitHub's smallest real app tier (5,000). Rejects junk observations — an unauthenticated+# 60-limit, a bool, a tiny garbage value — that would otherwise clamp or crash the budget math.+_SANE_MIN_OBSERVED_LIMIT = 1_000++# Process-local memos so the hot paths stay off Redis: the gate would otherwise pay one extra+# (event-loop-blocking, on async callers) GET per acquire, and the recorder one SET per response,+# for a value that changes only when a customer's GitHub plan does.+_OBSERVED_MEMO_TTL_SECONDS = 60.0+_observed_memo: dict[str, tuple[int | None, float]] = {}+# Rewrite the shared cache at least hourly even when the value is unchanged: a long-lived process+# skipping every write would otherwise never repair an evicted/flushed cache entry, silently+# reverting every other worker to the default budget until a deploy.+_REWRITE_INTERVAL_SECONDS = 3600.0+_last_written: dict[str, tuple[int, float]] = {}+++def observed_core_limit_cache_key(installation_id: str) -> str:+ return f"github_egress:observed_core_limit:{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]+++def get_observed_core_limit(installation_id: str) -> int | None:+ """The installation's observed core limit, or ``None`` when unobserved or implausible.++ Best-effort by construction: cache failures and junk values fall back to ``None`` (the settings+ defaults) — the limiter must never take a request down with it.+ """+ now = time.monotonic()+ memoized = _observed_memo.get(installation_id)+ if memoized is not None and now - memoized[1] < _OBSERVED_MEMO_TTL_SECONDS:+ return memoized[0]+ try:+ cached = cache.get(observed_core_limit_cache_key(installation_id))+ except Exception:+ cached = None+ observed = (+ cached+ if isinstance(cached, int) and not isinstance(cached, bool) and cached >= _SANE_MIN_OBSERVED_LIMIT+ else None+ )+ _observed_memo[installation_id] = (observed, now)+ return observed+++def remember_observed_core_limit(installation_id: str | None, response: "requests.Response") -> None:+ """Persist the tier from a *successful installation-token* response's headers.++ Called from ``GitHubIntegrationBase.api_request`` — the one place that knows the response was+ metered against the installation. Responses from other principals sharing the installation id+ (App-JWT refreshes on the App's budget, user-to-server calls on the user's 5k budget) and+ error responses (a 401 reports the unauthenticated 60-limit) must never feed the budget, so+ only 2xx ``core`` observations above the sanity floor count.+ """+ if not installation_id or not (200 <= response.status_code < 300):+ return+ headers = response.headers+ # Require the explicit header — a response missing it is no proof the limits are core's.+ if headers.get("x-ratelimit-resource") != "core":+ return+ try:+ limit = int(headers.get("x-ratelimit-limit", ""))+ except (TypeError, ValueError):+ return+ if limit < _SANE_MIN_OBSERVED_LIMIT:+ return+ now = time.monotonic()+ _observed_memo[installation_id] = (limit, now)+ written = _last_written.get(installation_id)+ if written is not None and written[0] == limit and now - written[1] < _REWRITE_INTERVAL_SECONDS:+ return+ try:+ cache.set(observed_core_limit_cache_key(installation_id), limit, OBSERVED_CORE_LIMIT_TTL_SECONDS)+ _last_written[installation_id] = (limit, now)+ except Exception:+ passdef _hourly_budget() -> int:@@ -46,12 +140,30 @@ def _per_minute_budget() -> int:return int(getattr(settings, "GITHUB_EGRESS_PER_MINUTE_BUDGET", _DEFAULT_PER_MINUTE_BUDGET))+def _tier_budgets(observed_limit: int | None) -> tuple[int, int]:+ """``(hourly, per_minute)`` for an installation, scaled to its observed core limit.++ The settings are operator ceilings honored for every installation; the observed tier can only+ lower the hourly budget below them (budgeting *over* the provider's real limit would defeat the+ limiter). 90% of the observed limit leaves room for drift; the minute cap scales as hourly/18+ so the hour can't drain faster than ~18 minutes. The 150 floor cushions only the scaled term+ (small tiers stay usable in bursts) — an explicit per-minute setting below it still wins,+ because operator ceilings are absolute.+ """+ hourly = _hourly_budget()+ if observed_limit is not None and observed_limit > 0:+ hourly = min(hourly, int(observed_limit * 0.9))+ per_minute = min(_per_minute_budget(), max(150, hourly // 18))+ return hourly, per_minute++# Both rates are enforced together — the per-minute rate smooths bursts, the hourly rate caps total-# spend. Registered as a provider so the budgets are read from settings at acquire time, not frozen-# at import (lets deploy-time config and test overrides take effect).-def _github_policy() -> RatePolicy:+# 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)))return RatePolicy(- limits=((_per_minute_budget(), 60.0), (_hourly_budget(), 3600.0)),+ limits=((per_minute, 60.0), (hourly, 3600.0)),in_memory_divider=4,reserve=_RESERVE,)diff --git a/posthog/egress/limiter/policies.py b/posthog/egress/limiter/policies.pyindex e65a22fcc0bb..85595c6cecb2 100644--- a/posthog/egress/limiter/policies.py+++ b/posthog/egress/limiter/policies.py@@ -4,10 +4,11 @@ A *policy* is a budget for calls leaving PostHog to a third-party API. Consumersbudget with a limiter key shaped ``"{domain}:{scope}:{id}"`` (e.g. ``"github:installation:123"``);the facade resolves the key to a policy by its ``domain`` (the first segment).-Policies are registered as *providers* — a zero-arg callable returning a ``RatePolicy`` — so a-budget sourced from Django settings is read at resolve time, not frozen at import. Pass a plain-``RatePolicy`` for a static budget. This module is backend-agnostic (no Redis, no limiter library),-which keeps the limiter backend swappable.+Policies are registered as *providers* — a callable receiving the full limiter key and returning a+``RatePolicy`` — so a budget can be read from Django settings at resolve time (not frozen at import)+and can vary per scope (e.g. per GitHub installation tier). Pass a plain ``RatePolicy`` for a static+budget. This module is backend-agnostic (no Redis, no limiter library), which keeps the limiter+backend swappable."""from collections.abc import Callable, Mapping@@ -72,16 +73,17 @@ class RatePolicy:return floor(self.reserve_fraction(priority) * count)-PolicyProvider = Callable[[], RatePolicy]+PolicyProvider = Callable[[str], RatePolicy]_REGISTRY: dict[str, PolicyProvider] = {}def register_policy(domain: str, policy: RatePolicy | PolicyProvider) -> None:"""Register the budget for a key domain. Pass a ``RatePolicy`` for a static budget, or a- zero-arg callable to resolve it lazily (e.g. from settings) on each acquire."""+ callable taking the full limiter key to resolve it lazily (e.g. from settings, or per scope)+ on each acquire."""if isinstance(policy, RatePolicy):- _REGISTRY[domain] = lambda: policy+ _REGISTRY[domain] = lambda _key: policyelse:_REGISTRY[domain] = policy@@ -96,4 +98,4 @@ def resolve_policy(key: str) -> RatePolicy:f"No outbound rate policy registered for domain '{domain}' (key '{key}'); ""register one with register_policy() before using this key")- return provider()+ return provider(key)diff --git a/posthog/egress/test/test_github_limiter.py b/posthog/egress/test/test_github_limiter.pynew file mode 100644index 000000000000..17c6d733a6e4--- /dev/null+++ b/posthog/egress/test/test_github_limiter.py@@ -0,0 +1,112 @@+import uuid++from django.core.cache import cache+from django.test import SimpleTestCase++import requests+from parameterized import parameterized+from requests.structures import CaseInsensitiveDict++from posthog.egress.github.limiter import (+ _last_written,+ _observed_memo,+ _tier_budgets,+ get_observed_core_limit,+ github_installation_key,+ observed_core_limit_cache_key,+ remember_observed_core_limit,+)+from posthog.egress.limiter.policies import Priority, resolve_policy+++def _response(*, status: int = 200, headers: dict[str, str] | None = None) -> requests.Response:+ response = requests.models.Response()+ response.status_code = status+ response.headers = CaseInsensitiveDict(headers or {})+ return response+++def _core_headers(limit: str) -> dict[str, str]:+ return {"X-RateLimit-Resource": "core", "X-RateLimit-Limit": limit}+++class GitHubLimiterTestCase(SimpleTestCase):+ def setUp(self) -> None:+ super().setUp()+ _observed_memo.clear()+ _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(_observed_memo.clear)+ self.addCleanup(_last_written.clear)+++class TestGitHubTierBudgets(GitHubLimiterTestCase):+ # Guards the tier math: if the 90% derivation, the /18 minute scaling, the clamps, or the+ # settings-as-ceiling contract regress, 5k-tier installations get budgeted above their real+ # GitHub limit (the limiter never fires) or the operator's emergency knob stops reaching traffic.+ @parameterized.expand(+ [+ ("unobserved_uses_defaults", None, 13_500, 750),+ ("five_k_tier", 5_000, 4_500, 250),+ ("top_tier", 15_000, 13_500, 750),+ ("tiny_tier_hits_minute_floor", 1_000, 900, 150),+ ("huge_tier_capped_at_default", 50_000, 13_500, 750),+ ]+ )+ def test_tier_budgets(self, _name: str, observed: int | None, expected_hourly: int, expected_minute: int) -> None:+ assert _tier_budgets(observed) == (expected_hourly, expected_minute)++ def test_per_minute_setting_is_a_ceiling_for_observed_tiers_too(self) -> None:+ with self.settings(GITHUB_EGRESS_PER_MINUTE_BUDGET=100):+ assert _tier_budgets(15_000) == (13_500, 100) # a setting below the burst floor still wins+ 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.+ cache.set(observed_core_limit_cache_key(self.installation_id), 5_000, 60)++ 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.CRITICAL) == 0.0+++class TestObservedCoreLimitStore(GitHubLimiterTestCase):+ # Guards the trusted-observation filter: responses from other principals sharing the+ # installation id (App-JWT refreshes, user-token calls via their error statuses, an+ # unauthenticated 401's 60-limit) must never feed the budget — a poisoned tier either clamps+ # the installation to a fictional budget for days or crashes the limiter's validation.+ def test_successful_core_observation_round_trips(self) -> None:+ remember_observed_core_limit(self.installation_id, _response(headers=_core_headers("5000")))+ assert get_observed_core_limit(self.installation_id) == 5000++ @parameterized.expand(+ [+ ("non_core_resource", 200, {"X-RateLimit-Resource": "graphql", "X-RateLimit-Limit": "5000"}),+ ("missing_resource_header", 200, {"X-RateLimit-Limit": "5000"}),+ ("error_response", 401, _core_headers("60")),+ ("implausibly_small_limit", 200, _core_headers("60")),+ ("missing_limit_header", 200, {"X-RateLimit-Resource": "core"}),+ ]+ )+ def test_untrusted_observations_are_ignored(self, _name: str, status: int, headers: dict[str, str]) -> None:+ remember_observed_core_limit(self.installation_id, _response(status=status, headers=headers))+ assert get_observed_core_limit(self.installation_id) is None++ @parameterized.expand(+ [+ ("bool_is_not_a_limit", True),+ ("garbage_small_int", 60),+ ("wrong_type", "5000"),+ ]+ )+ def test_junk_cached_values_fall_back_to_defaults(self, _name: str, cached: object) -> None:+ # A bad value must degrade to the defaults, never crash admission (a tiny limit would make+ # the policy's window smaller than a single call and raise on every acquire, CRITICAL included).+ cache.set(observed_core_limit_cache_key(self.installation_id), cached, 60)+ assert get_observed_core_limit(self.installation_id) is Nonediff --git a/posthog/egress/test/test_outbound_rate_limiter.py b/posthog/egress/test/test_outbound_rate_limiter.pyindex eb8caaf996dd..89b0bdd22748 100644--- a/posthog/egress/test/test_outbound_rate_limiter.py+++ b/posthog/egress/test/test_outbound_rate_limiter.py@@ -72,6 +72,20 @@ def test_policy_rejects_empty_limits():RatePolicy(limits=())+def test_provider_receives_the_full_limiter_key() -> None:+ # Guards the per-scope budget seam: if resolve_policy stops passing the key through, every+ # key-aware provider (e.g. GitHub's tier-scaled budgets) silently reverts to one shared budget.+ seen: list[str] = []++ def provider(key: str) -> RatePolicy:+ seen.append(key)+ return RatePolicy(limits=((1, 3600.0),))++ register_policy("test-keyed", provider)+ resolve_policy("test-keyed:scope:42")+ assert seen == ["test-keyed:scope:42"]++@pytest.mark.parametrize("bad_key", ["totally-unregistered:scope:1", "nocolon"])def test_resolve_policy_rejects_bad_keys(bad_key):# Fail-closed: an unregistered domain or a malformed (colon-less) key must raise rather thandiff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex d498a04a666e..25bfb707df3b 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -22,7 +22,9 @@ import requestsimport structlogfrom prometheus_client import Counter+from posthog.egress.github.limiter import remember_observed_core_limitfrom posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limited+from posthog.egress.limiter.policies import Priorityfrom posthog.sync import database_sync_to_async_poollogger = structlog.get_logger(__name__)@@ -93,6 +95,11 @@ class GitHubIntegrationBase:# with their own source (e.g. GitHubIntegration(integration, source="visual_review")) so every# request made through this instance — api_request, verbs, GraphQL — is attributed to them.source: str = _OBSERVABILITY_SOURCE+ # How sheddable this instance's calls are when the installation's shared budget runs hot.+ # CRITICAL (the default) is never blocked; deferrable background callers construct with+ # priority=Priority.BATCH so the egress limiter sheds them first — a denied sheddable call+ # raises GitHubEgressBudgetExhausted from api_request before anything is sent.+ priority: Priority = Priority.CRITICAL@propertydef github_installation_id(self) -> str | None:@@ -648,7 +655,9 @@ class GitHubIntegrationBase:``repository`` is ``owner/repo`` (or a bare repo, resolved against the org). Results comefrom the installation token's own API call, so they are inherently trusted — not- user-supplied like ``output.pr_url``. Best-effort: returns [] on a bad repo, non-200, or error.+ user-supplied like ``output.pr_url``. Best-effort: returns [] on a bad repo, non-200, or+ error — except rate limits (``GitHubRateLimitError``) and, on a sheddable instance, budget+ denial (``GitHubEgressBudgetExhausted``), which raise so callers can defer the sweep."""repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"owner = repo_path.split("/", 1)[0]@@ -773,9 +782,10 @@ class GitHubIntegrationBase:def get_pull_request_snapshot(self, pr_url: str) -> dict[str, Any]:"""Fetch the classification-relevant PR signals in one GraphQL call.- On any handled failure returns ``{"success": False, "error": ...}``;- rate-limit and unexpected errors raise ``GitHubIntegrationError`` so the- caller can back off.+ On any handled failure returns ``{"success": False, "error": ...}``; unexpected errors+ raise ``GitHubIntegrationError``. GitHub rate limits raise ``GitHubRateLimitError``, and on+ a sheddable instance (``priority=NORMAL/BATCH``) a denied budget raises+ ``GitHubEgressBudgetExhausted`` — callers own the back-off for both."""parsed = self.parse_pull_request_url(pr_url)if parsed is None:@@ -1294,6 +1304,7 @@ class GitHubIntegrationBase:headers: dict[str, str] | None = None,timeout: int = 10,retry_transient: bool | None = None,+ priority: Priority | None = None,) -> requests.Response:"""Authenticated request against ``https://api.github.com`` returning the raw response.@@ -1305,7 +1316,9 @@ class GitHubIntegrationBase:callers that want dict-or-raise semantics.``endpoint`` is the normalized label for egress telemetry; leave it ``None`` to let the- recorder template the raw URL. Attribution uses ``self.source``.+ recorder template the raw URL. Attribution uses ``self.source``; the limiter lane defaults+ to ``self.priority`` — on a sheddable lane (NORMAL/BATCH) a denied call raises+ ``GitHubEgressBudgetExhausted`` instead of being sent, and the caller owns the deferral."""if not path.startswith("/"):raise ValueError(f"api_request path must start with '/', got {path!r}")@@ -1332,6 +1345,7 @@ class GitHubIntegrationBase:# Token last: a caller-supplied Authorization must not bypass the managed lifecycle.headers={**(headers or {}), "Authorization": f"Bearer {token}"},installation_id=self.github_installation_id,+ priority=priority if priority is not None else self.priority,endpoint=endpoint,params=params,json=json_body,@@ -1346,6 +1360,9 @@ class GitHubIntegrationBase:)continueraise GitHubIntegrationError(f"GitHubIntegration: api_request network error on {path}") from exc+ # Successful installation-token responses are the only trusted source of the tier the+ # limiter budgets to; the store filters non-2xx/non-core itself.+ remember_observed_core_limit(self.github_installation_id, response)# Auth failure → refresh token and retry once (safe for any method: 401 means nothing ran).if response.status_code == 401 and attempt == 0:try:diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 94863d79d32b..6d9909765e7a 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -40,6 +40,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.cache_utils import cache_forfrom posthog.egress.github.transport import github_request+from posthog.egress.limiter.policies import Priorityfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError@@ -2576,12 +2577,16 @@ class GitHubIntegration(GitHubIntegrationBase):return githubreturn None- def __init__(self, integration: Integration, *, source: str | None = None) -> None:+ def __init__(+ self, integration: Integration, *, source: str | None = None, priority: Priority | None = None+ ) -> None:if integration.kind != "github":raise Exception("GitHubIntegration init called with Integration with wrong 'kind'")self.integration = integrationif source is not None:self.source = source+ if priority is not None:+ self.priority = prioritydef _on_token_refresh_failed(self, response: requests.Response) -> None:logger.warning(f"Failed to refresh token for {self}", response=response.text)diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex c731bede2d6f..631bbfb04ae5 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -19,7 +19,12 @@ from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom rest_framework.exceptions import ValidationError-from posthog.egress.github.transport import GitHubRateLimitError, raise_if_github_rate_limited+from posthog.egress.github.transport import (+ GitHubEgressBudgetExhausted,+ GitHubRateLimitError,+ raise_if_github_rate_limited,+)+from posthog.egress.limiter.policies import Priorityfrom posthog.models.github_integration_base import GITHUB_BRANCH_CACHE_TTL_SECONDS, GITHUB_REPOSITORY_CACHE_TTL_SECONDSfrom posthog.models.instance_setting import set_instance_settingfrom posthog.models.integration import (@@ -2034,9 +2039,12 @@ class TestGitHubIntegrationModel(BaseTest):class TestGitHubIntegrationGhApiGet(BaseTest):def _create_integration(self) -> Integration:+ # integration_id mirrors production (set from config on install) — the egress gate and+ # tier store key on it; without it every call is identity-blind and skips both.return Integration.objects.create(team=self.team,kind="github",+ integration_id="INSTALL",config={"installation_id": "INSTALL", "account": {"name": "PostHog"}},sensitive_config={"access_token": "ACCESS_TOKEN"},)@@ -2053,6 +2061,33 @@ class TestGitHubIntegrationGhApiGet(BaseTest):body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")assert body == {"default_branch": "main"}+ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=False)+ @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)+ def test_batch_instance_is_shed_when_budget_denied(self, _mock_expired, _mock_consume, mock_request):+ # Guards the lane plumbing: if the instance priority stops reaching the transport, BATCH+ # callers silently ride the never-shed CRITICAL lane again and denials stop deferring work.+ integration = self._create_integration()+ github = GitHubIntegration(integration, priority=Priority.BATCH)+ with pytest.raises(GitHubEgressBudgetExhausted):+ github.api_request("GET", "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")+ mock_request.assert_not_called()++ @patch("posthog.egress.transport.transport.requests.request")+ @patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=False)+ @patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)+ def test_critical_default_proceeds_when_budget_denied(self, _mock_expired, _mock_consume, mock_request):+ ok = MagicMock()+ ok.status_code = 200+ mock_request.return_value = ok++ integration = self._create_integration()+ response = GitHubIntegration(integration).api_request(+ "GET", "/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}"+ )+ assert response.status_code == 200+ mock_request.assert_called_once()+@patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_retries_once_on_transient_5xx(self, _mock_expired, mock_get):diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex f34e1b0bb5eb..5aed60bcad26 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -8,6 +8,7 @@ from django.db import modelsimport requestsimport structlog+from posthog.egress.limiter.policies import Priorityfrom posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import invalidate_github_repository_caches_for_installation@@ -132,12 +133,16 @@ class UserGitHubIntegration(GitHubIntegrationBase):integration: UserIntegration- def __init__(self, integration: UserIntegration, *, source: str | None = None) -> None:+ def __init__(+ self, integration: UserIntegration, *, source: str | None = None, priority: Priority | None = None+ ) -> None:if integration.kind != "github":raise Exception("UserGitHubIntegration initialized with non-github integration")self.integration = integrationif source is not None:self.source = source+ if priority is not None:+ self.priority = priority# --- Token refresh hooks ---diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.pyindex 2aaf80d60d7e..90977cc65620 100644--- a/products/engineering_analytics/backend/logic/job_logs/activity.py+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py@@ -18,6 +18,7 @@ from temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationErrorfrom posthog.egress.github.limiter import acquire_github_installation+from posthog.egress.limiter.policies import Priorityfrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflow@@ -67,7 +68,9 @@ async def fetch_and_emit_job_log_activity(inputs: FetchJobLogInputs) -> dict[strgithub_token, installation_id, log_ingest_token = await database_sync_to_async(_resolve_credentials, thread_sensitive=False)(inputs.team_id, inputs.integration_id)- if not await acquire_github_installation(installation_id, source="job_logs"):+ # Deferrable bulk: BATCH is shed first as the installation's budget fills, and the raise below+ # hands the retry to Temporal.+ if not await acquire_github_installation(installation_id, priority=Priority.BATCH, source="job_logs"):# Over budget — raise so Temporal retries with backoff instead of blocking a worker.raise ApplicationError("GitHub egress budget exhausted", type="GithubEgressBudgetExhausted")archive = await asyncio.to_thread(fetch_job_log, inputs.repo, inputs.job_id, github_token)@@ -120,9 +123,12 @@ class FetchGithubJobLogWorkflow(PostHogWorkflow):fetch_and_emit_job_log_activity,inputs,start_to_close_timeout=timedelta(minutes=5),+ # The BATCH lane can stay shed for the remainder of an hourly budget window, so the+ # retry horizon must outlive a worst-case shed — otherwise the job's logs are dropped+ # forever (the workflow_job webhook never refires).retry_policy=RetryPolicy(- maximum_attempts=5,+ maximum_attempts=10,initial_interval=timedelta(seconds=30),- maximum_interval=timedelta(minutes=5),+ maximum_interval=timedelta(minutes=15),),)diff --git a/products/tasks/backend/management/commands/evaluate_code_workstreams.py b/products/tasks/backend/management/commands/evaluate_code_workstreams.pyindex 87de13ff81ce..278c6ac8a594 100644--- a/products/tasks/backend/management/commands/evaluate_code_workstreams.py+++ b/products/tasks/backend/management/commands/evaluate_code_workstreams.py@@ -2,18 +2,17 @@ import jsonfrom django.core.management.base import BaseCommand, CommandError+from posthog.egress.limiter.policies import Priorityfrom posthog.models.scoping import team_scopefrom products.tasks.backend.models import CodePrSnapshot, CodeWorkstream+from products.tasks.backend.temporal.code_workstreams.activities.github_resolution import resolve_github_integrationfrom products.tasks.backend.temporal.code_workstreams.activities.list_active_teams import list_active_code_teamsfrom products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import (LoadTeamPrUrlsInput,load_team_pr_urls,)-from products.tasks.backend.temporal.code_workstreams.activities.poll_pull_requests import (- _resolve_integration,- poll_pull_requests_for_team,-)+from products.tasks.backend.temporal.code_workstreams.activities.poll_pull_requests import poll_pull_requests_for_teamfrom products.tasks.backend.temporal.code_workstreams.activities.rebuild_workstreams import (RebuildTeamWorkstreamsInput,rebuild_team_workstreams,@@ -111,7 +110,11 @@ class Command(BaseCommand):self.stdout.write(f"Resolved PrRef: team_integration={ref.github_integration_id}, user_integration={ref.github_user_integration_id}")- integration = _resolve_integration(ref)+ # One interactive diagnostic call is not deferrable bulk — don't let the BATCH lane shed+ # the very probe that's investigating degraded polling.+ integration = resolve_github_integration(+ ref.github_integration_id, ref.github_user_integration_id, priority=Priority.CRITICAL+ )if integration is None:raise CommandError("No GitHub integration resolved for this PR: the task isn't linked to one, the team has no GitHub "diff --git a/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py b/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.pyindex e916ba9ce9db..25c478d07336 100644--- a/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py+++ b/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py@@ -1,3 +1,4 @@+import randomfrom collections.abc import Callablefrom dataclasses import dataclassfrom typing import Optional@@ -8,7 +9,7 @@ from django.utils import timezoneimport requestsfrom temporalio import activity-from posthog.egress.github.transport import GitHubRateLimitError+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitErrorfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationErrorfrom posthog.temporal.common.utils import close_db_connections@@ -106,6 +107,9 @@ def discover_branch_prs_for_team(return DiscoverBranchPrsOutput(prs=[])candidates = _collect_branch_candidates(team_id)+ # A shed sweep breaks mid-list; shuffling gives the tail equal coverage across cycles instead+ # of the same recency-ordered prefix consuming the budget every run.+ random.shuffle(candidates)integrations: dict[str, GitHubIntegrationBase | None] = {}found: dict[str, PrRef] = {}@@ -142,6 +146,10 @@ def discover_branch_prs_for_team(try:urls = integration.find_pull_request_urls_for_branch(candidate.repository, candidate.branch)+ except GitHubEgressBudgetExhausted:+ # Our own limiter shed the sweep — stop for this cycle; the next scheduled run resumes.+ activity.logger.warning("code_workstreams_discover_budget_exhausted", repository=candidate.repository)+ breakexcept Exception as e:activity.logger.warning("code_workstreams_discover_branch_failed",diff --git a/products/tasks/backend/temporal/code_workstreams/activities/github_resolution.py b/products/tasks/backend/temporal/code_workstreams/activities/github_resolution.pyindex 8a732e9dc48c..c000c28f3398 100644--- a/products/tasks/backend/temporal/code_workstreams/activities/github_resolution.py+++ b/products/tasks/backend/temporal/code_workstreams/activities/github_resolution.py@@ -1,5 +1,6 @@from typing import Optional+from posthog.egress.limiter.policies import Priorityfrom posthog.models import Integrationfrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration@@ -40,20 +41,34 @@ class TeamIntegrationResolver:def resolve_github_integration(- github_integration_id: Optional[int], github_user_integration_id: Optional[str]+ github_integration_id: Optional[int],+ github_user_integration_id: Optional[str],+ *,+ priority: Priority = Priority.BATCH,) -> GitHubIntegrationBase | None:"""Instantiate the GitHub integration for the given ids, refreshing an expired token.+ Defaults to the sheddable BATCH lane: code-workstreams sweeps are deferrable bulk, so the+ egress limiter sheds them before user-facing traffic when an installation's budget runs hot.+ Interactive callers (the diagnostic management command) override to CRITICAL.+Raises ``ObjectDoesNotExist`` if the id no longer resolves; may also raise on token-refresh failure."""+ integration: GitHubIntegrationBaseif github_integration_id is not None:- integration = GitHubIntegration(Integration.objects.get(id=github_integration_id))- if integration.access_token_expired():- integration.refresh_access_token()- return integration- if github_user_integration_id is not None:- user_integration = UserGitHubIntegration(UserIntegration.objects.get(id=github_user_integration_id))- if user_integration.access_token_expired():- user_integration.refresh_access_token()- return user_integration- return None+ integration = GitHubIntegration(+ Integration.objects.get(id=github_integration_id),+ source="code_workstreams",+ priority=priority,+ )+ elif github_user_integration_id is not None:+ integration = UserGitHubIntegration(+ UserIntegration.objects.get(id=github_user_integration_id),+ source="code_workstreams",+ priority=priority,+ )+ else:+ return None+ if integration.access_token_expired():+ integration.refresh_access_token()+ return integrationdiff --git a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.pyindex 4174c0cc7e4f..013b3eeb261e 100644--- a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py+++ b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py@@ -1,5 +1,6 @@from __future__ import annotations+import randomimport hashlibfrom collections.abc import Callablefrom dataclasses import dataclass@@ -11,7 +12,7 @@ from django.utils.dateparse import parse_datetimeimport requestsfrom temporalio import activity-from posthog.egress.github.transport import GitHubRateLimitError+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitErrorfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationErrorfrom posthog.models.scoping import team_scopefrom posthog.temporal.common.utils import close_db_connections@@ -59,6 +60,11 @@ def poll_pull_requests_for_team(updated = 0rate_limited = False+ # A shed sweep breaks mid-list; shuffling gives the tail equal coverage across cycles instead+ # of permanently starving whatever sits past the shed point of a large team's list.+ prs = list(prs)+ random.shuffle(prs)+for index, ref in enumerate(prs):if heartbeat is not None:heartbeat(index)@@ -85,6 +91,11 @@ def poll_pull_requests_for_team(try:snap = integration.get_pull_request_snapshot(ref.pr_url)+ except GitHubEgressBudgetExhausted:+ # Our own limiter shed the sweep — stop for this cycle; the next scheduled run resumes.+ activity.logger.warning("code_workstreams_pr_budget_exhausted", team_id=team_id, polled=polled)+ rate_limited = True+ breakexcept GitHubRateLimitError:activity.logger.warning("code_workstreams_pr_rate_limited", team_id=team_id, polled=polled)rate_limited = Truediff --git a/products/tasks/backend/temporal/code_workstreams/test_discover_branch_prs.py b/products/tasks/backend/temporal/code_workstreams/test_discover_branch_prs.pyindex e86aa48f1c72..811b4dc235a3 100644--- a/products/tasks/backend/temporal/code_workstreams/test_discover_branch_prs.py+++ b/products/tasks/backend/temporal/code_workstreams/test_discover_branch_prs.py@@ -3,6 +3,7 @@ import randomimport pytestfrom unittest.mock import MagicMock, patch+from posthog.egress.github.transport import GitHubEgressBudgetExhaustedfrom posthog.models import Integration, Organization, Teamfrom products.tasks.backend.models import Task, TaskRun@@ -146,3 +147,24 @@ def test_collect_candidates_requires_an_integration():_run_on_branch(team, "acme/widgets", "posthog-code/feature-x")assert _collect_branch_candidates(team.id) == []++[email protected]_db(transaction=True)+def test_discover_stops_the_cycle_when_budget_shed(activity_environment):+ # Guards the break-on-shed seam: if GitHubEgressBudgetExhausted stops being caught here it+ # falls into the outer except-and-continue, and a shed sweep keeps grinding through denied+ # gate checks instead of yielding the cycle.+ team = _make_team()+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-x")+ _run_on_branch(team, "acme/widgets", "posthog-code/feature-y")++ fake = MagicMock()+ fake.find_pull_request_urls_for_branch.side_effect = GitHubEgressBudgetExhausted("shed")+ with patch(_RESOLVE, return_value=fake):+ result = activity_environment.run(+ discover_branch_prs,+ DiscoverBranchPrsInput(team_id=team.id, known_pr_urls=[], budget=50),+ )++ assert result.prs == []+ fake.find_pull_request_urls_for_branch.assert_called_once()diff --git a/products/tasks/backend/temporal/code_workstreams/test_poll_pull_requests.py b/products/tasks/backend/temporal/code_workstreams/test_poll_pull_requests.pynew file mode 100644index 000000000000..3fcfbad96d14--- /dev/null+++ b/products/tasks/backend/temporal/code_workstreams/test_poll_pull_requests.py@@ -0,0 +1,41 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError++from products.tasks.backend.temporal.code_workstreams.activities.load_pr_urls import PrRef+from products.tasks.backend.temporal.code_workstreams.activities.poll_pull_requests import poll_pull_requests_for_team++_RESOLVE = "products.tasks.backend.temporal.code_workstreams.activities.poll_pull_requests._resolve_integration"+++def _refs(count: int) -> list[PrRef]:+ return [+ PrRef(+ pr_url=f"https://github.com/acme/widgets/pull/{n}", github_integration_id=1, github_user_integration_id=None+ )+ for n in range(1, count + 1)+ ]+++# Guards the shed/backoff seam: if either exception stops being caught here, the whole team sweep+# activity fails and Temporal re-runs it immediately — hammering the budget it was just shed from —+# instead of yielding until the next scheduled cycle.+ [+ ("egress_budget_shed", GitHubEgressBudgetExhausted("shed")),+ ("github_rate_limited", GitHubRateLimitError("429", retry_after=60)),+ ]+)+def test_poll_stops_the_cycle_when_shed_or_rate_limited(_name: str, exc: Exception) -> None:+ integration = MagicMock()+ integration.get_pull_request_snapshot.side_effect = exc++ with patch(_RESOLVE, return_value=integration):+ result = poll_pull_requests_for_team(1, _refs(3))++ assert result.rate_limited is True+ assert result.polled == 0+ # break, not continue: one attempt, then yield the remaining PRs to the next cycle+ integration.get_pull_request_snapshot.assert_called_once()