: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(devex): add egress limiter priority lane + adopt in warehouse github source (#67029)
Julian Beza52deb3cb476
diff --git a/posthog/rate_limiting/AGENTS.md b/posthog/rate_limiting/AGENTS.mdnew file mode 100644index 000000000000..1b1e7e33049f--- /dev/null+++ b/posthog/rate_limiting/AGENTS.md@@ -0,0 +1,6 @@+# Outbound rate limiting & egress observability++Read the README before changing metrics, limiter keys, or adding an egress domain here.+Two things are easy to re-derive wrong: the identity model (key on the external budget owner — e.g. the GitHub App installation id — **never** a PostHog DB row id) and the deliberate PAT scope decision.+diff --git a/posthog/rate_limiting/CLAUDE.md b/posthog/rate_limiting/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/posthog/rate_limiting/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/posthog/rate_limiting/README.md b/posthog/rate_limiting/README.mdnew file mode 100644index 000000000000..51ace0335491--- /dev/null+++ b/posthog/rate_limiting/README.md@@ -0,0 +1,96 @@+# Outbound rate limiting & egress observability++General-purpose controls for the calls PostHog makes _out_ to third-party APIs.+GitHub is the first consumer, but the package is built for more.+There are two independent halves:++- **Rate limiting** — shared, Redis-backed budgets so every worker process draws from one limit and PostHog stays inside an external API's rate limit, with priority lanes so bulk traffic can't starve critical traffic.+- **Egress observability** — the metrics analog: request volume plus the API's own rate-limit headers, on one Prometheus metric set.++This is _outbound_ limiting — what PostHog sends.+It is unrelated to `posthog.rate_limit`, which throttles _inbound_ DRF requests from clients.++Both halves are **domain-generic**: a mechanism plus a small per-domain adapter (a budget policy for the limiter, a metric set and response parser for observability).+Adding a new outbound API is another adapter, not a change to the mechanism.++## Rate limiting++### Using it++A consumer identifies a budget with a limiter key shaped `{domain}:{scope}:{id}` — e.g. `github:installation:123`.+Go through the facade, never the backing library:++```python+from posthog.rate_limiting import Priority+from posthog.rate_limiting.github import consume_github_installation_sync++if not consume_github_installation_sync(installation_id, priority=Priority.BATCH, source="warehouse"):+ # Budget exhausted — back off and retry, defer, or drop. The limiter never blocks or sleeps.+ raise SomeRetryableError(...)+```++`acquire` (async) and `consume_sync` (sync, for callers outside an event loop) both return `True` if the call fits the shared budget and `False` if it would exceed it.+They are **non-blocking** — the caller decides what to do on `False`.+The GitHub helpers wrap the key construction; other domains expose their own thin gate the same way.++### 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).++### Priority lanes++Priority (`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.++### Backend++A sliding-window counter over Redis holds the shared budget across worker processes — O(1) memory per key, self-expiring, no background grooming.+When Redis is unavailable it degrades to a per-process in-memory counter, shrunk by `in_memory_divider` so N processes don't together allow N× the shared limit.+That fallback is best-effort: **the consumer's reactive backoff (e.g. honoring a 429) is the real backstop**, and the limiter is a proactive smoother on top.+All library and Redis specifics live in the backend module, so the facade and consumers stay backend-agnostic and the algorithm stays swappable.++## Egress observability++Record every response through the domain's recorder (e.g. `record_github_api_response`) so request volume and the API's rate-limit headers land on one metric set, whichever subsystem made the call.++- **Counter** (`github_integration_api_requests_total`) — request volume, always recorded, including errors, rate-limited responses, and transport exceptions that raise before a response. Labeled `installation_id, method, endpoint, status_code, source`.+- **Gauges** (`github_integration_api_rate_limit_{remaining,limit,reset_timestamp_seconds}`) — last-observed budget headroom parsed from the API's response headers (GitHub: `X-RateLimit-*`). Labeled `installation_id, resource`, with no `source`, because the budget is shared across sources.++The `source` label (e.g. `integration`, `visual_review`, `warehouse`) carries per-subsystem attribution.+Endpoint labels are normalized to bound cardinality: owner/repo, numeric ids, commit SHAs, and free-form tails (file paths, compare refs) are templated out (`/repos/{owner}/{repo}/statuses/{sha}`), so raw-URL callers don't mint one label per commit.++## The one identity rule++Everything keys on the **budget owner in the external API's own id space** — for GitHub the App **installation id**, because that is what GitHub meters.+It is **never** a PostHog DB row id (`Integration.id`).+Several PostHog integration rows can point at the same installation (multiple projects, one org), and GitHub gives that installation one shared budget: key a gauge by the row and one real budget splits into N flip-flopping series; key by the installation and you get one true series.+Per-caller attribution is the `source` label's job, not the identity's.++> The cache-hit counter in `github_integration_base` is a separate concern (cache efficiency per connection) and legitimately keys by the integration row — it is not egress-budget telemetry.++## Identity-blind callers and the PAT scope decision++Some callers have no installation in scope.+The important one is a warehouse source authenticated with a **personal access token (PAT)**: a customer's own token on the customer's own budget, disconnected from any PostHog installation (error tracking's public-repo path is the other).+These record the counter only, under an empty `installation_id`, and skip both the limiter and the gauges.+The counter still sums correctly, but identity-blind callers are **not distinguishable from one another** — every PAT lands on the same empty series, and writing headroom to a shared empty gauge would let unrelated tokens clobber each other.++Scope line, as of the telemetry unification:++- PAT request-**volume** telemetry is in scope and shipped (aggregate only).+- PAT rate-limit **headroom** and PAT **limiting** are deferred — revisit.++Both need the same missing piece: a per-token identity (a hash of the token) to key on.+The headers are already on the response, so it needs no request restructuring — but a token-hash label is higher-cardinality than an installation, so it's a deliberate choice, not a default.+`GithubEgressIdentity` is the seam where such a key would thread through.++## Adding a new egress domain++- Register a budget with `register_policy("<domain>", provider)` returning a `RatePolicy`.+- Expose a thin per-domain gate that builds the `{domain}:{scope}:{id}` key (see `github.py`).+- For telemetry, register an observability adapter (metric set, response parser, endpoint normalizer) and record responses through it.+- Keep the identity in the external API's id space, and remember the limiter is non-blocking — the caller owns the back-off.diff --git a/posthog/rate_limiting/__init__.py b/posthog/rate_limiting/__init__.pyindex e31df3a0822d..f10d28db1687 100644--- a/posthog/rate_limiting/__init__.py+++ b/posthog/rate_limiting/__init__.py@@ -10,11 +10,12 @@ send out, not what clients send us."""from posthog.rate_limiting.outbound import OutboundRateLimiter, get_outbound_rate_limiter-from posthog.rate_limiting.policies import RatePolicy, register_policy+from posthog.rate_limiting.policies import Priority, RatePolicy, register_policy__all__ = ["OutboundRateLimiter","get_outbound_rate_limiter",+ "Priority","RatePolicy","register_policy",]diff --git a/posthog/rate_limiting/backends.py b/posthog/rate_limiting/backends.pyindex 03de6e5c198e..92873710bf3c 100644--- a/posthog/rate_limiting/backends.py+++ b/posthog/rate_limiting/backends.py@@ -19,7 +19,7 @@ from limits import RateLimitItemPerSecondfrom limits.storage import MemoryStorage, RedisStoragefrom limits.strategies import SlidingWindowCounterRateLimiter-from posthog.rate_limiting.policies import RateLimit, RatePolicy+from posthog.rate_limiting.policies import Priority, RateLimit, RatePolicyfrom posthog.redis import get_clientlogger = structlog.get_logger(__name__)@@ -41,14 +41,32 @@ def _items(limits: tuple[RateLimit, ...]) -> list[RateLimitItemPerSecond]:return [RateLimitItemPerSecond(count, int(period_seconds)) for count, period_seconds in limits]-def _check(limiter: SlidingWindowCounterRateLimiter, items: list[RateLimitItemPerSecond], key: str, n: int) -> bool:- # Allowed only if every window has room; consume from all. Best-effort, not atomic across windows:- # testing all first avoids the deterministic partial-consume (hit window A, then deny window B), but- # a concurrent caller landing between test and hit can still leave one window consumed on a denied- # call. The drift is deny-biased (we err toward denying, never over-allowing the shared budget) and- # bounded by headroom plus the consumer's reactive backoff — fine for egress; cross-window atomicity- # (a custom multi-window Lua) isn't worth it at v1.- if not all(limiter.test(item, key, cost=n) for item in items):+def _reserves(policy: RatePolicy, priority: Priority, limits: tuple[RateLimit, ...]) -> list[int]:+ # Per-window headroom (in units) this priority must leave free, parallel to _items. Goes through+ # RatePolicy.reserve_amount so admission and the facade's _validate share one floor formula.+ return [policy.reserve_amount(priority, count) for count, _ in limits]+++def _check(+ limiter: SlidingWindowCounterRateLimiter,+ items: list[RateLimitItemPerSecond],+ key: str,+ n: int,+ reserves: list[int],+) -> bool:+ # Allowed only if every window has room for n PLUS the priority's reserved floor; if so, consume+ # only the real n. test inflates the cost by the reserve so lower-priority calls are denied while+ # that headroom is still owed to higher-priority traffic — but hit never charges the reserve, so+ # the budget stays shared (no per-priority buckets). CRITICAL/no-reserve => reserve 0 => test and+ # hit both cost n, the original behavior exactly.+ #+ # Best-effort, not atomic across windows: testing all first avoids the deterministic+ # partial-consume (hit window A, then deny window B), but a concurrent caller landing between test+ # and hit can still leave one window consumed on a denied call. The drift is deny-biased (we err+ # toward denying, never over-allowing the shared budget) and bounded by headroom plus the+ # consumer's reactive backoff — fine for egress; cross-window atomicity (a custom multi-window Lua)+ # isn't worth it at v1.+ if not all(limiter.test(item, key, cost=n + reserve) for item, reserve in zip(items, reserves)):return Falsereturn all(limiter.hit(item, key, cost=n) for item in items)@@ -65,16 +83,20 @@ class LimitsBackend:self._memory: SlidingWindowCounterRateLimiter | None = Noneself._lock = threading.Lock()- async def acquire(self, key: str, policy: RatePolicy, n: int) -> bool:+ async def acquire(self, key: str, policy: RatePolicy, n: int, priority: Priority) -> bool:# Offload the blocking Redis call so the event loop isn't held.- return await asyncio.to_thread(self.consume_sync, key, policy, n)+ return await asyncio.to_thread(self.consume_sync, key, policy, n, priority)- def consume_sync(self, key: str, policy: RatePolicy, n: int) -> bool:+ def consume_sync(self, key: str, policy: RatePolicy, n: int, priority: Priority) -> bool:try:- return _check(self._redis_limiter(), _items(policy.limits), key, n)+ limits = policy.limits+ return _check(self._redis_limiter(), _items(limits), key, n, _reserves(policy, priority, limits))except _REDIS_ERRORS:logger.warning("outbound_rate_limit_redis_unavailable", key=key, fallback="in_memory")- return _check(self._memory_limiter(), _items(self._shrunk(policy)), key, n)+ # Reserve off the shrunk fallback budget so the floor scales with the smaller per-process+ # limit rather than the full one.+ shrunk = self._shrunk(policy)+ return _check(self._memory_limiter(), _items(shrunk), key, n, _reserves(policy, priority, shrunk))@staticmethoddef _shrunk(policy: RatePolicy) -> tuple[RateLimit, ...]:diff --git a/posthog/rate_limiting/github.py b/posthog/rate_limiting/github.pyindex 892633cf3385..8bf84501d847 100644--- a/posthog/rate_limiting/github.py+++ b/posthog/rate_limiting/github.py@@ -12,10 +12,20 @@ Importing this module registers the policy as a side effect — import it (direcfrom django.conf import settingsfrom posthog.rate_limiting.outbound import get_outbound_rate_limiter-from posthog.rate_limiting.policies import RatePolicy, register_policy+from posthog.rate_limiting.policies import Priority, RatePolicy, register_policyGITHUB_DOMAIN = "github"+# No reserves are active yet. A reserve only helps once a higher-priority lane actually gates through+# the limiter — and today the only callers are warehouse (BATCH) and the job-logs worker (NORMAL),+# both deferrable background jobs. The CRITICAL lane (auth, token refresh, webhook CRUD) still calls+# GitHub without acquiring, so reserving headroom for it would just hard-cap the two real callers+# below GitHub's actual budget with no beneficiary (and silently drop the job-logs ceiling). The+# priority *mechanism* is wired end to end (callers already declare BATCH/NORMAL), so activating+# reserves when CRITICAL is gated is a one-line change here — e.g. {Priority.BATCH: 0.30} to shed+# warehouse polling first. Until then the shared budget alone (13.5k under GitHub's 15k) is the guard.+_RESERVE: dict[Priority, float] = {}+# Default under GitHub's real 15k/hr ceiling so the reactive backoff (GitHubRateLimitError in# posthog/models/integration.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.@@ -44,6 +54,7 @@ def _github_policy() -> RatePolicy:return RatePolicy(limits=((_per_minute_budget(), 60.0), (_hourly_budget(), 3600.0)),in_memory_divider=4,+ reserve=_RESERVE,)@@ -55,7 +66,22 @@ def github_installation_key(installation_id: str | int) -> str:return f"{GITHUB_DOMAIN}:installation:{installation_id}"-async def acquire_github_installation(installation_id: str | int, n: int = 1) -> bool:- """Reserve ``n`` requests against an installation's hourly GitHub budget. Returns False when- the budget is exhausted — back off and retry rather than calling GitHub."""- return await get_outbound_rate_limiter().acquire(github_installation_key(installation_id), n)+async def acquire_github_installation(+ installation_id: str | int, n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown"+) -> bool:+ """Reserve ``n`` requests against an installation's hourly GitHub budget. Returns False when the+ budget (or this ``priority``'s reserved floor) is exhausted — back off and retry rather than+ calling GitHub."""+ return await get_outbound_rate_limiter().acquire(+ github_installation_key(installation_id), n, priority=priority, source=source+ )+++def consume_github_installation_sync(+ installation_id: str | int, n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown"+) -> bool:+ """Sync variant of :func:`acquire_github_installation` for callers outside an event loop (e.g. the+ warehouse source iterator, which runs in a thread pool)."""+ return get_outbound_rate_limiter().consume_sync(+ github_installation_key(installation_id), n, priority=priority, source=source+ )diff --git a/posthog/rate_limiting/observability.py b/posthog/rate_limiting/observability.pyindex 0aa47f4530e8..f79e519662ff 100644--- a/posthog/rate_limiting/observability.py+++ b/posthog/rate_limiting/observability.py@@ -146,6 +146,25 @@ class EgressObservability:self._metrics.request_counter.labels(scope or "", method.upper(), endpoint_label, "exception", source).inc()+# Limiter admission decisions, domain-labeled like everything else here. Counter (not gauge) so the+# grant/deny rate per domain+source+priority is visible — that's how you see deferrable BATCH traffic+# being shed before CRITICAL as a shared budget fills. ``granted`` is "true"/"false"; prometheus_client+# appends ``_total`` to the exposed series name.+outbound_rate_limit_decisions = Counter(+ "outbound_rate_limit_decisions",+ "Outbound egress rate limiter admission decisions. Recorded per attempt, so a shed call that retries "+ "(e.g. warehouse _fetch_page under tenacity) inflates granted=false by the retry count — alert on the "+ "grant/deny ratio or rate, not raw denied totals.",+ labelnames=["domain", "source", "priority", "granted"],+)+++def record_outbound_decision(*, domain: str, source: str, priority: str, granted: bool) -> None:+ """Record one limiter decision. ``priority`` is the lane string (e.g. ``"batch"``); the caller+ derives ``domain`` from the limiter key's first segment so this stays limiter-library-agnostic."""+ outbound_rate_limit_decisions.labels(domain, source, priority, "true" if granted else "false").inc()++_REGISTRY: dict[str, EgressObservability] = {}diff --git a/posthog/rate_limiting/outbound.py b/posthog/rate_limiting/outbound.pyindex 0f6b78e945ce..3e61c89c1afc 100644--- a/posthog/rate_limiting/outbound.py+++ b/posthog/rate_limiting/outbound.py@@ -10,34 +10,54 @@ backing library, so the algorithm/backend stays swappable.import threadingfrom posthog.rate_limiting.backends import LimitsBackend-from posthog.rate_limiting.policies import RatePolicy, resolve_policy+from posthog.rate_limiting.observability import record_outbound_decision+from posthog.rate_limiting.policies import Priority, RatePolicy, resolve_policy-def _validate(n: int, policy: RatePolicy) -> None:+def _domain_of(key: str) -> str:+ # resolve_policy already validated the key shape, so the first segment is the domain.+ return key.partition(":")[0]+++def _validate(n: int, policy: RatePolicy, priority: Priority) -> None:if n < 1:raise ValueError(f"rate limiter weight must be >= 1, got {n}")- smallest = min(count for count, _ in policy.limits)- if n > smallest:- # limits treats a weight larger than the limit as permanently unsatisfiable, so the caller- # would back off forever rather than ever be granted. Fail loudly instead of silently.- raise ValueError(f"weight {n} exceeds the tightest configured limit ({smallest}); it can never be granted")+ for count, _ in policy.limits:+ reserve = policy.reserve_amount(priority, count)+ if n + reserve > count:+ # limits treats a weight larger than the limit as permanently unsatisfiable, so the+ # caller would back off forever rather than ever be granted. The priority's reserved floor+ # eats into that headroom, so check the inflated weight, not just n. Fail loudly.+ raise ValueError(+ f"weight {n} plus reserved floor {reserve} for priority {priority.name} exceeds the "+ f"limit {count}; it can never be granted"+ )class OutboundRateLimiter:def __init__(self, backend: LimitsBackend | None = None) -> None:self._backend = backend or LimitsBackend()- async def acquire(self, key: str, n: int = 1) -> bool:- """Reserve ``n`` units against ``key``'s budget. Returns False if it would exceed it."""+ async def acquire(+ self, key: str, n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown"+ ) -> bool:+ """Reserve ``n`` units against ``key``'s budget. Returns False if it would exceed it (or, for a+ lower ``priority``, would dip into the reserve owed to higher-priority traffic)."""policy = resolve_policy(key)- _validate(n, policy)- return await self._backend.acquire(key, policy, n)+ _validate(n, policy, priority)+ granted = await self._backend.acquire(key, policy, n, priority)+ record_outbound_decision(domain=_domain_of(key), source=source, priority=priority.value, granted=granted)+ return granted- def consume_sync(self, key: str, n: int = 1) -> bool:+ def consume_sync(+ self, key: str, n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown"+ ) -> bool:"""Non-blocking sync variant for callers outside an event loop."""policy = resolve_policy(key)- _validate(n, policy)- return self._backend.consume_sync(key, policy, n)+ _validate(n, policy, priority)+ granted = self._backend.consume_sync(key, policy, n, priority)+ record_outbound_decision(domain=_domain_of(key), source=source, priority=priority.value, granted=granted)+ return granted_limiter: OutboundRateLimiter | None = Nonediff --git a/posthog/rate_limiting/policies.py b/posthog/rate_limiting/policies.pyindex 9a212b633883..e65a22fcc0bb 100644--- a/posthog/rate_limiting/policies.py+++ b/posthog/rate_limiting/policies.py@@ -10,14 +10,27 @@ budget sourced from Django settings is read at resolve time, not frozen at imporwhich keeps the limiter backend swappable."""-from collections.abc import Callable-from dataclasses import dataclass+from collections.abc import Callable, Mapping+from dataclasses import dataclass, field+from enum import Enum+from math import floor# (count, period_seconds) — one rate constraint. A policy may carry several; they are all enforced# together, so you can cap the hour AND smooth per-minute bursts on the same key.RateLimit = tuple[int, float]+class Priority(Enum):+ """How sheddable a call is when the shared 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, so deferrable bulk traffic (``BATCH``) is denied before critical traffic as the budget+ fills, without ever splitting the budget into separate buckets."""++ CRITICAL = "critical" # may use the whole budget — never shed+ NORMAL = "normal" # default — yields a small reserve to CRITICAL+ BATCH = "batch" # deferrable bulk — yields the largest reserve, shed first++@dataclass(frozen=True)class RatePolicy:"""A budget: one or more ``(count, period_seconds)`` limits enforced together.@@ -26,16 +39,37 @@ class RatePolicy:each process would otherwise get the full budget, so N processes together would allow N× theshared limit. The fallback is best-effort only — the consumer's reactive backoff (e.g. honoringa 429) is the real backstop.++ ``reserve`` maps a :class:`Priority` to the fraction of each window's budget that must remain+ free for a call of that priority to be admitted. A priority absent from the map reserves nothing+ (0.0), so an empty ``reserve`` keeps every call critical-equivalent — exactly the pre-priority+ behavior. Fractions are validated to ``[0, 1)`` (1.0 would reserve the whole window and deny the+ priority forever)."""limits: tuple[RateLimit, ...]in_memory_divider: int = 1+ reserve: Mapping[Priority, float] = field(default_factory=dict)def __post_init__(self) -> None:# A policy with no limits would let every call through, defeating the point. Reject it at# definition time rather than surfacing an opaque "min() arg is empty" deep in the facade.if not self.limits:raise ValueError("RatePolicy.limits must declare at least one (count, period_seconds) limit")+ for priority, fraction in self.reserve.items():+ if not (0.0 <= fraction < 1.0):+ raise ValueError(f"RatePolicy.reserve[{priority.name}] must be in [0, 1), got {fraction}")++ def reserve_fraction(self, priority: Priority) -> float:+ """Reserved-headroom fraction for ``priority`` — 0.0 when the priority isn't configured."""+ return self.reserve.get(priority, 0.0)++ def reserve_amount(self, priority: Priority, count: int) -> int:+ """Units of a window of size ``count`` this priority must leave free: ``floor(fraction * count)``.+ floor (not round/ceil) so a 0 fraction reserves exactly 0, keeping the no-reserve path+ bit-identical to pre-priority behavior. Single source for both admission (backend) and+ validation (facade), so the two can't drift."""+ return floor(self.reserve_fraction(priority) * count)PolicyProvider = Callable[[], RatePolicy]diff --git a/posthog/rate_limiting/test/test_outbound_rate_limiter.py b/posthog/rate_limiting/test/test_outbound_rate_limiter.pyindex c09a8bfc15f6..6f74f7104c45 100644--- a/posthog/rate_limiting/test/test_outbound_rate_limiter.py+++ b/posthog/rate_limiting/test/test_outbound_rate_limiter.py@@ -3,7 +3,7 @@ import pytestimport posthog.rate_limiting.backends as backends_moduleimport posthog.rate_limiting.outbound as outbound_moduleimport posthog.rate_limiting.policies as policies_module-from posthog.rate_limiting import OutboundRateLimiter, RatePolicy, register_policy+from posthog.rate_limiting import OutboundRateLimiter, Priority, RatePolicy, register_policyfrom posthog.rate_limiting.backends import LimitsBackendfrom posthog.rate_limiting.github import acquire_github_installation, github_installation_keyfrom posthog.rate_limiting.policies import resolve_policy@@ -111,3 +111,66 @@ async def test_github_adapter_registers_policy_and_keys_per_installation():# installation so distinct installations draw on independent budgets.assert github_installation_key(1) != github_installation_key(2)assert await acquire_github_installation(987654321, 1) is True+++_RESERVE = {Priority.NORMAL: 0.1, Priority.BATCH: 0.3}+++ "priority,grantable",+ [+ # reserve floor = floor(fraction * 10): CRITICAL 0, NORMAL 1, BATCH 3 -> each priority may+ # consume up to limit - floor before its reserved headroom denies the next call.+ (Priority.CRITICAL, 10),+ (Priority.NORMAL, 9),+ (Priority.BATCH, 7),+ ],+)+async def test_reserved_floor_caps_each_priority(priority, grantable):+ # The whole point of the lane: a lower priority is denied while headroom is still owed to higher+ # ones, even though all three draw from the same counter.+ register_policy("test-reserve", RatePolicy(limits=((10, 3600.0),), reserve=_RESERVE))+ limiter = _fresh_limiter()+ # Distinct scope per case — parametrize cases share one Redis-backed counter otherwise.+ key = f"test-reserve:scope:{priority.value}"+ grants = [await limiter.acquire(key, priority=priority) for _ in range(11)]+ assert grants[:grantable] == [True] * grantable+ assert grants[grantable] is False+++async def test_batch_shed_before_critical_on_shared_counter():+ # Fill the non-reserved share with BATCH, then prove BATCH is denied while CRITICAL still draws+ # from the SAME counter (the reserved floor protected exactly that headroom).+ register_policy("test-shared", RatePolicy(limits=((10, 3600.0),), reserve={Priority.BATCH: 0.3}))+ limiter = _fresh_limiter()+ key = "test-shared:scope:1"+ assert all([await limiter.acquire(key, priority=Priority.BATCH) for _ in range(7)])+ assert await limiter.acquire(key, priority=Priority.BATCH) is False+ assert await limiter.acquire(key, priority=Priority.CRITICAL) is True++[email protected]("priority", [Priority.CRITICAL, Priority.NORMAL, Priority.BATCH])+async def test_no_reserve_policy_is_priority_blind(priority):+ # An empty reserve must reproduce the pre-priority behavior for every lane — no headroom held back.+ register_policy("test-noreserve", RatePolicy(limits=((2, 3600.0),)))+ limiter = _fresh_limiter()+ key = f"test-noreserve:scope:{priority.value}"+ assert [await limiter.acquire(key, priority=priority) for _ in range(3)] == [True, True, False]+++def test_reserve_inflated_weight_validation():+ # n plus the reserved floor must fit the limit or it can never be granted — fail loudly, and only+ # for the priority whose reserve makes it unsatisfiable.+ register_policy("test-reserve-weight", RatePolicy(limits=((10, 3600.0),), reserve={Priority.BATCH: 0.3}))+ limiter = _fresh_limiter()+ key = "test-reserve-weight:scope:1"+ with pytest.raises(ValueError):+ limiter.consume_sync(key, 8, priority=Priority.BATCH) # 8 + floor(0.3*10)=3 -> 11 > 10+ assert limiter.consume_sync(key, 8, priority=Priority.CRITICAL) is True # 8 + 0 <= 10++[email protected]("bad_fraction", [-0.1, 1.0, 1.5])+def test_policy_rejects_out_of_range_reserve(bad_fraction):+ # A fraction outside [0, 1) is a config error: 1.0 reserves the whole window and denies forever.+ with pytest.raises(ValueError):+ RatePolicy(limits=((10, 3600.0),), reserve={Priority.BATCH: bad_fraction})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 99c0f949ee09..0e230b8e0f32 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@@ -15,7 +15,9 @@ from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_from urllib3.util.retry import Retryfrom posthog.models.integration import GitHubRateLimitError, raise_if_github_rate_limited+from posthog.rate_limiting.github import consume_github_installation_syncfrom posthog.rate_limiting.github_observability import record_github_api_exception, record_github_api_response+from posthog.rate_limiting.policies import Priorityfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcherfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse@@ -60,6 +62,19 @@ class GithubResumeConfig:next_url: str[email protected](frozen=True)+class GithubEgressIdentity:+ """Identity threaded to the HTTP chokepoint (``_fetch_page``) so it can gate on the shared+ per-installation egress budget and label telemetry.++ ``installation_id`` is the GitHub App installation id — the limiter's budget owner and the+ telemetry key, matching every other consumer of the same installation so the shared budget is+ genuinely shared. ``None`` on the PAT path (no installation, token-blind), which skips the gate and+ records request volume only — the pre-limiter behavior."""++ installation_id: str | None = None++def _format_incremental_value(value: Any) -> str:"""Format incremental field value as ISO string for GitHub API filters."""if isinstance(value, datetime):@@ -367,21 +382,34 @@ def _github_retry_wait(state: RetryCallState) -> float:wait=_github_retry_wait,reraise=True,)-def _fetch_page(page_url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> requests.Response:+def _fetch_page(+ page_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ egress_identity: GithubEgressIdentity | None = None,+) -> requests.Response:+ # Gate deferrable warehouse polling on the shared per-installation budget BEFORE spending it.+ # Only the App path has an installation to bill (PAT path has no shared budget). On denial raise+ # the retryable error so tenacity backs off instead of blocking a worker — bulk traffic defers,+ # critical traffic keeps the headroom the BATCH reserve protects. Skipped entirely on the PAT path.+ installation_id = egress_identity.installation_id if egress_identity is not None else None+ if installation_id is not None:+ if not consume_github_installation_sync(installation_id, priority=Priority.BATCH, source="warehouse"):+ raise GithubRetryableError(f"GitHub egress budget exhausted for installation {installation_id}; deferring")+# Record transport failures (ReadTimeout/ConnectionError from the retry tuple) too, so a GitHub# connectivity incident doesn't silently zero out warehouse telemetry exactly when it matters. Best# effort — the recorder never raises, and we re-raise the original error untouched.try:response = make_tracked_session(retry=_NO_ADAPTER_RETRY).get(page_url, headers=headers, timeout=60)except requests.RequestException:- record_github_api_exception(source="warehouse", method="GET", url=page_url)+ record_github_api_exception(source="warehouse", method="GET", url=page_url, installation_id=installation_id)raise- # Record before the branching below so rate-limited (403/429) and error responses count too.- # This source authenticates with a raw token and has no installation id in scope, so it records- # request volume only (source="warehouse"); the per-installation gauges stay with callers that- # know their installation.- record_github_api_response(response, source="warehouse")+ # Record before the branching below so rate-limited (403/429) and error responses count too. Pass the+ # installation id when known (App path) so the shared rate-limit gauges are set; the PAT path stays+ # counter-only (no installation, token-blind).+ record_github_api_response(response, source="warehouse", installation_id=installation_id)# Transient server errors: retry with plain exponential backoff.if response.status_code >= 500:@@ -412,6 +440,7 @@ def _iter_pages(logger: FilteringBoundLogger,max_pages: int | None = None,page_cap_context: dict[str, Any] | None = None,+ egress_identity: GithubEgressIdentity | None = None,) -> Iterator[tuple[list[dict[str, Any]], str]]:"""Yield (items, page_url) for each page of a paginated GitHub list,unwrapping the envelope and following the Link header. Stops at ``max_pages``,@@ -419,7 +448,7 @@ def _iter_pages(envelope body simply ends iteration — there is nothing to truncate."""page_count = 0while True:- response = _fetch_page(url, headers, logger)+ response = _fetch_page(url, headers, logger, egress_identity)data = response.json()if response_data_path and isinstance(data, dict):data = data.get(response_data_path) or []@@ -446,6 +475,7 @@ def _iter_jobs_for_run(headers: dict[str, str],logger: FilteringBoundLogger,config: GithubEndpointConfig,+ egress_identity: GithubEgressIdentity | None = None,) -> Iterator[dict[str, Any]]:path = config.path.format(repository=repository, run_id=run_id)params: dict[str, Any] = {"per_page": config.page_size, **(config.extra_params or {})}@@ -457,6 +487,7 @@ def _iter_jobs_for_run(logger,max_pages=config.max_pages_per_parent,page_cap_context={"repository": repository, "run_id": run_id},+ egress_identity=egress_identity,):yield from jobs@@ -470,6 +501,7 @@ def _fan_out_get_rows(should_use_incremental_field: bool,db_incremental_field_last_value: Any,incremental_field: str | None,+ egress_identity: GithubEgressIdentity | None = None,) -> Iterator[Any]:"""Single-hop parent->child fan-out: walk the parent endpoint newest-first andemit every child row for each parent. Incremental bounding happens on the@@ -512,7 +544,9 @@ def _fan_out_get_rows(else:parent_url = _build_initial_url(parent_config, repository, {"per_page": parent_config.page_size})- for runs, page_url in _iter_pages(parent_url, headers, parent_config.response_data_path, logger):+ for runs, page_url in _iter_pages(+ parent_url, headers, parent_config.response_data_path, logger, egress_identity=egress_identity+ ):stop_after_this_page = _should_stop_desc(runs, "desc", parent_field, parent_cutoff)for run in runs:@@ -522,7 +556,7 @@ def _fan_out_get_rows(# Only fan out parents at/above the watermark; older ones were synced before.if parent_cutoff is not None and _is_older_than_cutoff(run.get(parent_field), parent_cutoff):continue- for job in _iter_jobs_for_run(repository, run_id, headers, logger, child_config):+ for job in _iter_jobs_for_run(repository, run_id, headers, logger, child_config, egress_identity):batcher.batch(job)if batcher.should_yield():yield batcher.get_table()@@ -546,6 +580,7 @@ def get_rows(should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,incremental_field: str | None = None,+ egress_identity: GithubEgressIdentity | None = None,) -> Iterator[Any]:config = GITHUB_ENDPOINTS[endpoint]if config.fan_out_parent is not None:@@ -558,6 +593,7 @@ def get_rows(should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,incremental_field=incremental_field,+ egress_identity=egress_identity,)return@@ -590,7 +626,7 @@ def get_rows(while True:try:- response = _fetch_page(url, headers, logger)+ response = _fetch_page(url, headers, logger, egress_identity)except GithubEmptyRepositoryError:logger.debug(f"Github: repository has no commits (empty repository), syncing zero rows: url={url}")break@@ -689,6 +725,7 @@ def github_source(db_incremental_field_last_value: Optional[Any] = None,incremental_field: str | None = None,webhook_source_manager: Optional[WebhookSourceManager] = None,+ egress_identity: GithubEgressIdentity | None = None,) -> SourceResponse:endpoint_config = GITHUB_ENDPOINTS[endpoint]@@ -741,6 +778,7 @@ def github_source(should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,incremental_field=incremental_field,+ egress_identity=egress_identity,)return SourceResponse(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 aa9b0343c41d..d4422f428673 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@@ -40,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.schfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GithubSourceConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.github.github import (+ GithubEgressIdentity,GithubResumeConfig,create_repo_webhook,delete_repo_webhook,@@ -230,6 +231,17 @@ If automatic creation failed, your token needs webhook permissions — the **admraise ValueError("GitHub access token not found")return integration.access_token+ def _egress_identity(self, config: GithubSourceConfig, team_id: int) -> GithubEgressIdentity:+ """Resolve the installation id used to gate egress and label telemetry. Empty on the PAT path+ (no installation budget, token-blind), which makes the source record counter-only and skip the+ limiter — the pre-limiter behavior. The integration is a cheap PK lookup; resolving it separately+ from the token keeps ``_get_access_token`` a token-only method (and its tests untouched), at the+ cost of one extra indexed query per pipeline build (negligible)."""+ if config.auth_method.selection == "pat" or not config.auth_method.github_integration_id:+ return GithubEgressIdentity()+ integration = self.get_oauth_integration(config.auth_method.github_integration_id, team_id)+ return GithubEgressIdentity(installation_id=GitHubIntegration(integration).github_installation_id)+@staticmethoddef _schema_for_endpoint(endpoint: str) -> SourceSchema:webhook_capable = endpoint in GITHUB_WEBHOOK_RESOURCE_MAP@@ -322,6 +334,7 @@ If automatic creation failed, your token needs webhook permissions — the **adminputs: SourceInputs,) -> SourceResponse:access_token = self._get_access_token(config, inputs.team_id)+ egress_identity = self._egress_identity(config, inputs.team_id)# Only the workflow schemas can be webhook-fed, so skip building the manager — and its# webhook_enabled() DB lookup — for the poll-only endpoints (issues, commits, etc.).webhook_source_manager = (@@ -340,4 +353,5 @@ If automatic creation failed, your token needs webhook permissions — the **admelse None,incremental_field=inputs.incremental_field,webhook_source_manager=webhook_source_manager,+ egress_identity=egress_identity,)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 8c3cf8f80072..53f881053213 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@@ -4,6 +4,8 @@ from unittest import mockimport requestsfrom prometheus_client import REGISTRY+from posthog.rate_limiting.policies import Priority+from products.warehouse_sources.backend.temporal.data_imports.sources.github import github@@ -12,6 +14,9 @@ def _ok_response() -> mock.Mock:response.status_code = 200response.ok = Trueresponse.text = ""+ # The egress recorder reads response.request.{method,url}; a spec'd mock doesn't expose the+ # instance attribute, so set it explicitly (None falls back to defaults in the recorder).+ response.request = Nonereturn response@@ -55,3 +60,41 @@ def test_fetch_page_reraises_chunked_encoding_error_after_exhausting_retries():# Every transport failure is recorded, so a GitHub outage doesn't silently zero warehouse telemetry.after = REGISTRY.get_sample_value("github_integration_api_requests_total", exception_labels) or 0assert after - before == session.get.call_count+++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.+ session = mock.Mock()+ session.get.return_value = _ok_response()+ identity = github.GithubEgressIdentity(installation_id="123")++ with (+ mock.patch.object(github, "consume_github_installation_sync", return_value=False) as gate,+ mock.patch.object(github, "make_tracked_session", return_value=session),+ ):+ with pytest.raises(github.GithubRetryableError):+ github._fetch_page("https://api.github.com/repos/o/r/issues", {}, mock.Mock(), identity)++ assert session.get.call_count == 0+ assert gate.call_count == 5+ assert gate.call_args.args[0] == "123"+ assert gate.call_args.kwargs == {"priority": Priority.BATCH, "source": "warehouse"}+++def test_fetch_page_skips_gate_on_pat_path():+ # PAT path has no installation budget, so the gate must never run and the request proceeds.+ session = mock.Mock()+ session.get.return_value = _ok_response()++ with (+ mock.patch.object(github, "consume_github_installation_sync") as gate,+ mock.patch.object(github, "make_tracked_session", return_value=session),+ ):+ response = github._fetch_page(+ "https://api.github.com/repos/o/r/issues", {}, mock.Mock(), github.GithubEgressIdentity()+ )++ assert response.status_code == 200+ assert gate.call_count == 0+ assert session.get.call_count == 1