: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): route GitHub callers through a single gated transport (#67371)
Julian Bez428c22625535
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex f00d309d980c..8196542184c8 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -3327,48 +3327,48 @@ class TestGitHubBranches:)self.github = GitHubIntegration(self.integration)- @patch("posthog.models.integration.requests.get")- def test_list_branches_returns_first_page(self, mock_get):+ @patch("posthog.egress.transport.transport.requests.request")+ def test_list_branches_returns_first_page(self, mock_request):names = [f"branch-{i}" for i in range(100)]- mock_get.return_value = _make_github_branches_response(names, has_next=True)+ mock_request.return_value = _make_github_branches_response(names, has_next=True)branches, has_more = self.github.list_branches("org/repo", limit=100, offset=0)assert branches == namesassert has_more is True- mock_get.assert_called_once()- assert "page=1" in mock_get.call_args[0][0]+ mock_request.assert_called_once()+ assert "page=1" in mock_request.call_args[0][1]- @patch("posthog.models.integration.requests.get")- def test_list_branches_offset_skips_pages(self, mock_get):+ @patch("posthog.egress.transport.transport.requests.request")+ def test_list_branches_offset_skips_pages(self, mock_request):"""Requesting offset=200 should start fetching from GitHub page 3."""page3_names = [f"branch-{i}" for i in range(200, 300)]- mock_get.return_value = _make_github_branches_response(page3_names, has_next=True)+ mock_request.return_value = _make_github_branches_response(page3_names, has_next=True)branches, has_more = self.github.list_branches("org/repo", limit=100, offset=200)assert branches == page3_namesassert has_more is True- assert mock_get.call_count == 1- assert "page=3" in mock_get.call_args[0][0]+ assert mock_request.call_count == 1+ assert "page=3" in mock_request.call_args[0][1]- @patch("posthog.models.integration.requests.get")- def test_list_branches_last_page_no_more(self, mock_get):+ @patch("posthog.egress.transport.transport.requests.request")+ def test_list_branches_last_page_no_more(self, mock_request):names = [f"branch-{i}" for i in range(50)]- mock_get.return_value = _make_github_branches_response(names, has_next=False)+ mock_request.return_value = _make_github_branches_response(names, has_next=False)branches, has_more = self.github.list_branches("org/repo", limit=100, offset=0)assert branches == namesassert has_more is False- @patch("posthog.models.integration.requests.get")- def test_list_branches_spans_two_github_pages(self, mock_get):+ @patch("posthog.egress.transport.transport.requests.request")+ def test_list_branches_spans_two_github_pages(self, mock_request):"""An offset that doesn't align with per_page=100 requires fetching two GitHub pages."""page1_names = [f"branch-{i}" for i in range(100)]page2_names = [f"branch-{i}" for i in range(100, 200)]- mock_get.side_effect = [+ mock_request.side_effect = [_make_github_branches_response(page1_names, has_next=True),_make_github_branches_response(page2_names, has_next=False),]@@ -3379,32 +3379,32 @@ class TestGitHubBranches:assert branches == [f"branch-{i}" for i in range(50, 150)]# There are still branches 150-199 beyond this windowassert has_more is True- assert mock_get.call_count == 2+ assert mock_request.call_count == 2- @patch("posthog.models.integration.requests.get")- def test_list_branches_empty_repo(self, mock_get):- mock_get.return_value = _make_github_branches_response([], has_next=False)+ @patch("posthog.egress.transport.transport.requests.request")+ def test_list_branches_empty_repo(self, mock_request):+ mock_request.return_value = _make_github_branches_response([], has_next=False)branches, has_more = self.github.list_branches("org/repo")assert branches == []assert has_more is False- @patch("posthog.models.integration.requests.get")- def test_list_branches_401_triggers_refresh_and_retry(self, mock_get):+ @patch("posthog.egress.transport.transport.requests.request")+ def test_list_branches_401_triggers_refresh_and_retry(self, mock_request):unauthorized = MagicMock()unauthorized.status_code = 401names = ["main", "develop"]success = _make_github_branches_response(names, has_next=False)- mock_get.side_effect = [unauthorized, success]+ mock_request.side_effect = [unauthorized, success]with patch.object(self.github, "refresh_access_token"):branches, has_more = self.github.list_branches("org/repo")assert branches == names- assert mock_get.call_count == 2+ assert mock_request.call_count == 2@patch("posthog.models.integration.GitHubIntegration.list_cached_branches")def test_api_endpoint_passes_search_limit_offset(self, mock_list_cached, client: HttpClient):@@ -3481,8 +3481,8 @@ class TestGitHubBranches:assert response.status_code == 400- @patch("posthog.models.integration.requests.get")- def test_get_default_branch_is_cached(self, mock_get):+ @patch("posthog.egress.transport.transport.requests.request")+ def test_get_default_branch_is_cached(self, mock_request):from django.core.cache import cachecache.clear()@@ -3490,14 +3490,14 @@ class TestGitHubBranches:response = MagicMock()response.status_code = 200response.json.return_value = {"default_branch": "develop"}- mock_get.return_value = response+ mock_request.return_value = responsefirst = self.github.get_default_branch("org/repo-cache-test")second = self.github.get_default_branch("org/repo-cache-test")assert first == "develop"assert second == "develop"- assert mock_get.call_count == 1+ assert mock_request.call_count == 1class TestAnthropicIntegration:diff --git a/posthog/rate_limiting/AGENTS.md b/posthog/egress/AGENTS.mdsimilarity index 100%rename from posthog/rate_limiting/AGENTS.mdrename to posthog/egress/AGENTS.mddiff --git a/posthog/rate_limiting/CLAUDE.md b/posthog/egress/CLAUDE.mdsimilarity index 100%rename from posthog/rate_limiting/CLAUDE.mdrename to posthog/egress/CLAUDE.mddiff --git a/posthog/rate_limiting/README.md b/posthog/egress/README.mdsimilarity index 65%rename from posthog/rate_limiting/README.mdrename to posthog/egress/README.mdindex 51ace0335491..0915e56b2845 100644--- a/posthog/rate_limiting/README.md+++ b/posthog/egress/README.md@@ -1,17 +1,18 @@-# Outbound rate limiting & egress observability+# Outbound egress: rate limiting, observability, transportGeneral-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:+Three lanes, one per subpackage:-- **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.+- **`limiter/`** — 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.+- **`observability/`** — the metrics analog: request volume plus the API's own rate-limit headers, on one Prometheus metric set.+- **`transport/`** — the HTTP client that composes the other two: one request that is gated _and_ recorded by construction, so no caller can bypass either.-This is _outbound_ limiting — what PostHog sends.+This is _outbound_ egress — 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.+All three lanes are **domain-generic** and domain-free; each third-party API is an incarnation under its own subpackage (`github/`), supplying a budget policy, a metric set + parser, and a transport subclass.+Adding a new outbound API is another `<domain>/` folder, not a change to the mechanisms.## Rate limiting@@ -21,8 +22,8 @@ A consumer identifies a budget with a limiter key shaped `{domain}:{scope}:{id}`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+from posthog.egress.limiter.policies import Priority+from posthog.egress.github.limiter import consume_github_installation_syncif 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.@@ -63,6 +64,29 @@ Record every response through the domain's recorder (e.g. `record_github_api_resThe `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.+## Transport++`github_request` is the one way to call GitHub from anywhere — it gates on the shared per-installation budget and records telemetry by construction, so a caller physically can't forget either:++```python+from posthog.egress.github.transport import github_request+from posthog.egress.limiter.policies import Priority++resp = github_request(+ "GET",+ url,+ source="visual_review",+ headers={"Authorization": f"Bearer {token}"}, # caller owns auth; the client adds Accept + API version+ installation_id=installation_id, # budget owner; None = identity-blind (records volume only)+ priority=Priority.CRITICAL, # CRITICAL never blocks; sheddable lanes raise on denial+)+```++It's **token-agnostic** (installation token, user token, PAT, or PostHog's shared token) and stateless.+The generic `EgressClient` base owns the gate → request → record algorithm and the priority-based denial semantics (CRITICAL proceeds even when the budget is spent — GitHub's own 429 is the backstop; sheddable lanes raise `EgressBudgetExhausted`); `GitHubClient` fills the domain hooks.+Response handling — what to do on a 403/429 — stays with the caller: `raise_if_github_rate_limited` / `GitHubRateLimitError` (GitHub's own 429, the reactive twin of our `EgressBudgetExhausted`) live in `github/transport.py` for callers that want to raise-and-retry.+The model-coupled `GitHubIntegrationBase` is a _consumer_ of this, not the general path.+## The one identity ruleEverything 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.@@ -90,7 +114,10 @@ The headers are already on the response, so it needs no request restructuring## 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.+Add a `<domain>/` subpackage with three small adapters (see `github/`):++- `limiter.py` — register a budget with `register_policy("<domain>", provider)` and a thin gate that builds the `{domain}:{scope}:{id}` key.+- `observability.py` — an observability adapter (metric set, response parser, endpoint normalizer) and the recorders.+- `transport.py` — an `EgressClient` subclass filling the domain hooks (headers, gate, recorders, normalizer, budget-exhausted error), exposed as a `<domain>_request` helper.++Keep the identity in the external API's id space, keep the subpackage free of `posthog.models` imports, and remember the limiter is non-blocking — the caller owns the back-off.diff --git a/posthog/egress/__init__.py b/posthog/egress/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/egress/github/__init__.py b/posthog/egress/github/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/rate_limiting/github.py b/posthog/egress/github/limiter.pysimilarity index 76%rename from posthog/rate_limiting/github.pyrename to posthog/egress/github/limiter.pyindex 8bf84501d847..09ff8fb497e1 100644--- a/posthog/rate_limiting/github.py+++ b/posthog/egress/github/limiter.py@@ -11,23 +11,22 @@ Importing this module registers the policy as a side effect — import it (direcfrom django.conf import settings-from posthog.rate_limiting.outbound import get_outbound_rate_limiter-from posthog.rate_limiting.policies import Priority, RatePolicy, register_policy+from posthog.egress.limiter.outbound import get_outbound_rate_limiter+from posthog.egress.limiter.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.+# 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] = {}# 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+# 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._DEFAULT_HOURLY_BUDGET = 13_500diff --git a/posthog/rate_limiting/github_observability.py b/posthog/egress/github/observability.pysimilarity index 99%rename from posthog/rate_limiting/github_observability.pyrename to posthog/egress/github/observability.pyindex 9e577769c3be..07ec5506a52c 100644--- a/posthog/rate_limiting/github_observability.py+++ b/posthog/egress/github/observability.py@@ -17,7 +17,7 @@ from urllib.parse import urlparseimport requestsfrom prometheus_client import Counter, Gauge-from posthog.rate_limiting.observability import (+from posthog.egress.observability.observability import (EgressMetrics,EgressObservability,RateLimitSnapshot,diff --git a/posthog/egress/github/transport.py b/posthog/egress/github/transport.pynew file mode 100644index 000000000000..a83cab3704af--- /dev/null+++ b/posthog/egress/github/transport.py@@ -0,0 +1,141 @@+"""GitHub incarnation of the egress transport.++``github_request`` is the one way to call GitHub from anywhere in the codebase: it gates on the shared+per-installation budget and records telemetry by construction, so a caller physically can't forget+either. It is *token-agnostic* — pass whatever ``Authorization`` header the caller holds (installation+token, user token, PAT, or PostHog's shared token) and the ``installation_id`` as ``scope`` when known.++This module lives in ``egress`` (not the model layer) and imports nothing from ``posthog.models`` — the+model-coupled ``GitHubIntegrationBase`` is a *consumer* of this, not the other way round. ``GITHUB_API_VERSION``+is defined here for the same reason: the transport needs it, and it can't reach back into ``integration.py``.+"""++import time+from typing import Any++import requests++from posthog.egress.github.limiter import consume_github_installation_sync+from posthog.egress.github.observability import record_github_api_exception, record_github_api_response+from posthog.egress.limiter.policies import Priority+from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient++# The GitHub REST API version we pin every request to. Lives here (not integration.py) so the egress+# layer stays free of any posthog.models import; integration.py imports it back from here.+GITHUB_API_VERSION = "2022-11-28"+++class GitHubEgressBudgetExhausted(EgressBudgetExhausted):+ """A deferrable (BATCH/NORMAL) GitHub call was shed by our egress limiter before it was sent —+ the proactive, our-side twin of :class:`GitHubRateLimitError`. This is our own budget, so a caller+ that can defer (e.g. the warehouse sync) catches it and backs off."""+++class GitHubRateLimitError(Exception):+ """GitHub itself rate-limited an outbound call (a 429, or a 403 with a rate-limit body) — the+ reactive, GitHub-side twin of :class:`GitHubEgressBudgetExhausted`. A GitHub egress condition, so it+ lives here (not the model layer); it deliberately does not subclass ``GitHubIntegrationError`` — a+ transient rate limit isn't a fatal integration failure. Exposes ``is_rate_limit`` /+ ``retry_after_seconds`` so backoff filters can key off it."""++ def __init__(self, message: str, reset_at: int | None = None, retry_after: int | None = None):+ super().__init__(message)+ self.is_rate_limit = True+ self.retry_after_seconds = float(retry_after) if retry_after is not None else None+ self.reset_at = reset_at+ self.retry_after = retry_after+++def raise_if_github_rate_limited(response: requests.Response) -> None:+ """Raise :class:`GitHubRateLimitError` when the response signals a GitHub rate limit (primary+ 403 + body, or secondary 429). Safe to call unconditionally after any GitHub API response."""+ if response.status_code == 429:+ is_rate_limited = True+ elif response.status_code == 403:+ try:+ body = response.text+ except Exception:+ body = ""+ is_rate_limited = "rate limit" in body.lower()+ else:+ return++ if not is_rate_limited:+ return++ def _int_header(name: str) -> int | None:+ val = response.headers.get(name)+ if not val:+ return None+ try:+ return int(val)+ except (ValueError, TypeError):+ return None++ reset_at = _int_header("x-ratelimit-reset")+ retry_after = _int_header("retry-after")+ if retry_after is None and reset_at is not None:+ retry_after = max(1, reset_at - int(time.time()))++ raise GitHubRateLimitError(+ f"GitHub API rate limit exceeded (resets at {reset_at})",+ reset_at=reset_at,+ retry_after=retry_after,+ )+++class GitHubClient(EgressClient):+ """The GitHub incarnation of :class:`EgressClient`. Stateless and token-agnostic, so one shared+ instance serves every caller; wire it through :func:`github_request`."""++ def _standard_headers(self) -> dict[str, str]:+ return {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": GITHUB_API_VERSION}++ def _consume(self, scope: str, priority: Priority, source: str) -> bool:+ return consume_github_installation_sync(scope, priority=priority, source=source)++ def _record_response(+ self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None+ ) -> None:+ record_github_api_response(response, source=source, installation_id=scope, method=method, endpoint=endpoint)++ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:+ record_github_api_exception(source=source, installation_id=scope, method=method, url=url, endpoint=endpoint)++ def _budget_exhausted_error(self, scope: str) -> GitHubEgressBudgetExhausted:+ return GitHubEgressBudgetExhausted(f"GitHub egress budget exhausted for installation {scope}; deferring")+++# Stateless — one shared instance for the whole process.+_github_client = GitHubClient()+++def github_request(+ method: str,+ url: str,+ *,+ source: str,+ headers: dict[str, str] | None = None,+ installation_id: str | None = None,+ priority: Priority = Priority.CRITICAL,+ endpoint: str | None = None,+ timeout: float | tuple[float, float] | None = None,+ session: requests.Session | None = None,+ **kwargs: Any,+) -> requests.Response:+ """Make a gated, recorded GitHub API request. ``installation_id`` is the shared budget owner — pass+ it when known so the call is gated (at ``priority``) and the rate-limit gauges are set; leave it+ ``None`` for identity-blind callers (raw PATs, PostHog's public token), which record volume only.+ ``source`` attributes the call to a subsystem. ``headers`` must carry the caller's ``Authorization``."""+ return _github_client.request(+ method,+ url,+ source=source,+ headers=headers,+ scope=installation_id,+ priority=priority,+ endpoint=endpoint,+ timeout=timeout,+ session=session,+ **kwargs,+ )diff --git a/posthog/egress/limiter/__init__.py b/posthog/egress/limiter/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/rate_limiting/backends.py b/posthog/egress/limiter/backends.pysimilarity index 98%rename from posthog/rate_limiting/backends.pyrename to posthog/egress/limiter/backends.pyindex 92873710bf3c..01b1e2c00aca 100644--- a/posthog/rate_limiting/backends.py+++ b/posthog/egress/limiter/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 Priority, RateLimit, RatePolicy+from posthog.egress.limiter.policies import Priority, RateLimit, RatePolicyfrom posthog.redis import get_clientlogger = structlog.get_logger(__name__)diff --git a/posthog/rate_limiting/outbound.py b/posthog/egress/limiter/outbound.pysimilarity index 93%rename from posthog/rate_limiting/outbound.pyrename to posthog/egress/limiter/outbound.pyindex 3e61c89c1afc..dc8aad1e1c9d 100644--- a/posthog/rate_limiting/outbound.py+++ b/posthog/egress/limiter/outbound.py@@ -9,9 +9,9 @@ backing library, so the algorithm/backend stays swappable.import threading-from posthog.rate_limiting.backends import LimitsBackend-from posthog.rate_limiting.observability import record_outbound_decision-from posthog.rate_limiting.policies import Priority, RatePolicy, resolve_policy+from posthog.egress.limiter.backends import LimitsBackend+from posthog.egress.limiter.policies import Priority, RatePolicy, resolve_policy+from posthog.egress.observability.observability import record_outbound_decisiondef _domain_of(key: str) -> str:diff --git a/posthog/rate_limiting/policies.py b/posthog/egress/limiter/policies.pysimilarity index 100%rename from posthog/rate_limiting/policies.pyrename to posthog/egress/limiter/policies.pydiff --git a/posthog/egress/observability/__init__.py b/posthog/egress/observability/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/rate_limiting/observability.py b/posthog/egress/observability/observability.pysimilarity index 98%rename from posthog/rate_limiting/observability.pyrename to posthog/egress/observability/observability.pyindex f79e519662ff..b45091e5991d 100644--- a/posthog/rate_limiting/observability.py+++ b/posthog/egress/observability/observability.py@@ -1,6 +1,6 @@"""Generic outbound API egress observability — the metrics analog of the egress limiter.-Mirrors the limiter's shape (:mod:`posthog.rate_limiting.outbound`): a domain-agnostic mechanism,+Mirrors the limiter's shape (:mod:`posthog.egress.limiter.outbound`): a domain-agnostic mechanism,with each third-party API registered as a *domain* that supplies its own metric set and a parser forthat API's rate-limit response headers. A consumer records a response against a domain; the registered:class:`EgressObservability` does the rest.diff --git a/posthog/egress/test/__init__.py b/posthog/egress/test/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/rate_limiting/test/test_github_observability.py b/posthog/egress/test/test_github_observability.pysimilarity index 98%rename from posthog/rate_limiting/test/test_github_observability.pyrename to posthog/egress/test/test_github_observability.pyindex d4c4714e9350..c896c4f74f84 100644--- a/posthog/rate_limiting/test/test_github_observability.py+++ b/posthog/egress/test/test_github_observability.py@@ -7,12 +7,12 @@ from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom requests.structures import CaseInsensitiveDict-from posthog.rate_limiting.github_observability import (+from posthog.egress.github.observability import (_normalize_github_endpoint,record_github_api_exception,record_github_api_response,)-from posthog.rate_limiting.observability import (+from posthog.egress.observability.observability import (default_normalize_endpoint,record_outbound_api_response,resolve_egress_observability,diff --git a/posthog/rate_limiting/test/test_outbound_rate_limiter.py b/posthog/egress/test/test_outbound_rate_limiter.pysimilarity index 94%rename from posthog/rate_limiting/test/test_outbound_rate_limiter.pyrename to posthog/egress/test/test_outbound_rate_limiter.pyindex 6f74f7104c45..eb8caaf996dd 100644--- a/posthog/rate_limiting/test/test_outbound_rate_limiter.py+++ b/posthog/egress/test/test_outbound_rate_limiter.py@@ -1,12 +1,12 @@import pytest-import posthog.rate_limiting.backends as backends_module-import posthog.rate_limiting.outbound as outbound_module-import posthog.rate_limiting.policies as policies_module-from posthog.rate_limiting import OutboundRateLimiter, Priority, RatePolicy, register_policy-from posthog.rate_limiting.backends import LimitsBackend-from posthog.rate_limiting.github import acquire_github_installation, github_installation_key-from posthog.rate_limiting.policies import resolve_policy+import posthog.egress.limiter.backends as backends_module+import posthog.egress.limiter.outbound as outbound_module+import posthog.egress.limiter.policies as policies_module+from posthog.egress.github.limiter import acquire_github_installation, github_installation_key+from posthog.egress.limiter.backends import LimitsBackend+from posthog.egress.limiter.outbound import OutboundRateLimiter+from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy, resolve_policy@pytest.fixture(autouse=True)diff --git a/posthog/egress/transport/__init__.py b/posthog/egress/transport/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/egress/transport/transport.py b/posthog/egress/transport/transport.pynew file mode 100644index 000000000000..bb4f0ae4e733--- /dev/null+++ b/posthog/egress/transport/transport.py@@ -0,0 +1,98 @@+"""Generic outbound egress transport — the third egress lane, composing the limiter and observability.++An :class:`EgressClient` makes an outbound HTTP request that is *gated* (against the shared per-owner+budget) and *recorded* (request volume + the API's rate-limit headers) by construction, so no caller+can make a request that bypasses either. The gate→request→record algorithm and the priority-based+denial semantics are domain-agnostic and live here; each third-party API subclasses and fills the+domain hooks (standard headers, the limiter gate, the recorders, the endpoint normaliser, the+budget-exhausted exception). GitHub is the first incarnation — see :mod:`posthog.egress.github.transport`.+"""++from abc import ABC, abstractmethod+from typing import Any++import requests++from posthog.egress.limiter.policies import Priority+++class EgressBudgetExhausted(Exception):+ """A *sheddable* (non-CRITICAL) outbound call was denied by the egress limiter before it was sent.+ Callers that can defer should catch this and back off/retry — it means our own shared budget is+ spent, not that the third-party API returned an error. CRITICAL calls are never raised on; they+ proceed and let the API's own rate limiting be the backstop."""+++class EgressClient(ABC):+ """One outbound API's transport: gate → request → record, with priority-based denial semantics.++ The algorithm is fixed here; subclasses supply the domain hooks. ``scope`` is the shared budget+ owner's id in the API's own namespace (e.g. a GitHub App installation id); ``None`` means the+ caller is identity-blind (a raw token with no shared budget), which skips the gate and records+ request volume only.+ """++ def request(+ self,+ method: str,+ url: str,+ *,+ source: str,+ headers: dict[str, str] | None = None,+ scope: str | None = None,+ priority: Priority = Priority.CRITICAL,+ endpoint: str | None = None,+ timeout: float | tuple[float, float] | None = None,+ session: requests.Session | None = None,+ **kwargs: Any,+ ) -> requests.Response:+ self._gate(scope, source, priority)++ request_headers = {**self._standard_headers(), **(headers or {})}+ sender = session or requests+ try:+ response = sender.request(method, url, headers=request_headers, timeout=timeout, **kwargs)+ except requests.RequestException:+ # Best-effort telemetry must never mask the real transport error — record and re-raise it.+ self._record_exception(source=source, scope=scope, method=method, url=url, endpoint=endpoint)+ raise++ self._record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)+ return response++ def _gate(self, scope: str | None, source: str, priority: Priority) -> None:+ # Identity-blind callers have no shared budget to draw on — record volume only, never gate.+ # An empty scope is no identity either: gating on it would key a phantom budget/metric series.+ if not scope:+ return+ granted = self._consume(scope, priority, source)+ # CRITICAL never blocks: it records the decision (and consumes if there's room) but proceeds+ # regardless, so a user-facing call is never shed by us — the API's own 429 is the backstop.+ # Sheddable lanes back off so their headroom is left for higher-priority traffic.+ if not granted and priority is not Priority.CRITICAL:+ raise self._budget_exhausted_error(scope)++ # --- domain hooks -------------------------------------------------------------------------------++ @abstractmethod+ def _standard_headers(self) -> dict[str, str]:+ """Default headers merged under the caller's (the caller's win) — e.g. Accept, API version."""++ @abstractmethod+ def _consume(self, scope: str, priority: Priority, source: str) -> bool:+ """Draw ``1`` from the domain's shared budget for ``scope`` at ``priority``; True if granted."""++ @abstractmethod+ def _record_response(+ self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None+ ) -> None:+ """Record a returned response (volume + the API's rate-limit headers) via the domain's recorder."""++ @abstractmethod+ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:+ """Record a request that raised before returning a response (timeout, connection error)."""++ @abstractmethod+ def _budget_exhausted_error(self, scope: str) -> EgressBudgetExhausted:+ """The domain-specific exception raised when a sheddable call is denied (a subclass of+ :class:`EgressBudgetExhausted`)."""diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex d94816c7539c..1108fc538737 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -22,7 +22,8 @@ import requestsimport structlogfrom prometheus_client import Counter-from posthog.rate_limiting.github_observability import record_github_api_exception, record_github_api_response+from posthog.egress.github.observability import record_github_api_exception, record_github_api_response+from posthog.egress.github.transport import GITHUB_API_VERSION, github_requestfrom posthog.sync import database_sync_to_async_poollogger = structlog.get_logger(__name__)@@ -121,7 +122,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {jwt_token}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},timeout=timeout,)@@ -234,7 +235,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {user_access_token}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},params={"per_page": 1},timeout=10,@@ -281,13 +282,16 @@ class GitHubIntegrationBase:params: dict[str, str | int] | None = None,timeout: int | None = None,) -> requests.Response:- try:- response = requests.get(url, headers=headers, params=params, timeout=timeout)- except requests.RequestException:- self._record_github_api_exception("GET", endpoint)- raise- self._record_github_api_response(response, "GET", endpoint)- return response+ return github_request(+ "GET",+ url,+ source=_OBSERVABILITY_SOURCE,+ headers=headers,+ installation_id=self.github_installation_id,+ endpoint=endpoint,+ params=params,+ timeout=timeout,+ )def _github_api_post(self,@@ -297,13 +301,15 @@ class GitHubIntegrationBase:headers: dict[str, str],json_body: Mapping[str, object] | None = None,) -> requests.Response:- try:- response = requests.post(url, json=json_body, headers=headers)- except requests.RequestException:- self._record_github_api_exception("POST", endpoint)- raise- self._record_github_api_response(response, "POST", endpoint)- return response+ return github_request(+ "POST",+ url,+ source=_OBSERVABILITY_SOURCE,+ headers=headers,+ installation_id=self.github_installation_id,+ endpoint=endpoint,+ json=json_body,+ )def _github_api_put(self,@@ -313,13 +319,15 @@ class GitHubIntegrationBase:headers: dict[str, str],json_body: Mapping[str, object],) -> requests.Response:- try:- response = requests.put(url, json=json_body, headers=headers)- except requests.RequestException:- self._record_github_api_exception("PUT", endpoint)- raise- self._record_github_api_response(response, "PUT", endpoint)- return response+ return github_request(+ "PUT",+ url,+ source=_OBSERVABILITY_SOURCE,+ headers=headers,+ installation_id=self.github_installation_id,+ endpoint=endpoint,+ json=json_body,+ )# --- Installation access token ---@@ -438,7 +446,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},params=params,timeout=timeout,@@ -764,7 +772,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {self.get_access_token()}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},json_body={"query": query, "variables": variables},)@@ -914,7 +922,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},)@@ -1053,7 +1061,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},timeout=10,)@@ -1178,7 +1186,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},)@@ -1234,7 +1242,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},timeout=10,)@@ -1519,7 +1527,7 @@ class GitHubIntegrationBase:headers={"Accept": "application/vnd.github+json","Authorization": f"Bearer {self.get_access_token()}",- "X-GitHub-Api-Version": "2022-11-28",+ "X-GitHub-Api-Version": GITHUB_API_VERSION,},timeout=timeout,)diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 272a0f8e1516..ff911a90505e 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -39,6 +39,7 @@ from slack_sdk import WebClientfrom slack_sdk.errors import SlackApiErrorfrom posthog.cache_utils import cache_for+from posthog.egress.github.transport import GITHUB_API_VERSIONfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError@@ -83,8 +84,6 @@ oauth_refresh_counter = Counter("integration_oauth_refresh", "Number of times an oauth refresh has been attempted", labelnames=["kind", "result"])-GITHUB_API_VERSION = "2022-11-28"-# `owner/repo`, single slash, no traversal. Used to keep repo/ref/sha values out of GitHub API URL# paths where a crafted value (e.g. `../../other-repo/contents/x?ref=y`) could redirect the# authenticated request to a different endpoint.@@ -2385,62 +2384,6 @@ class GitHubUserAuthorization:refresh_token_expires_in: int | None-class GitHubRateLimitError(GitHubIntegrationError):- """GitHub API rate limit exhausted for this installation."""-- def __init__(self, message: str, reset_at: int | None = None, retry_after: int | None = None):- # Forward to the base error so backoff filters using `exc.is_rate_limit` /- # `exc.retry_after_seconds` continue to work for instances of this subclass.- super().__init__(- message,- is_rate_limit=True,- retry_after_seconds=float(retry_after) if retry_after is not None else None,- )- self.reset_at = reset_at- self.retry_after = retry_after---def raise_if_github_rate_limited(response: requests.Response) -> None:- """Raise GitHubRateLimitError when the response signals a GitHub rate limit.-- Handles both primary (403 + body) and secondary (429) rate limit formats.- Safe to call unconditionally after every GitHub API response.- """- if response.status_code == 429:- is_rate_limited = True- elif response.status_code == 403:- try:- body = response.text- except Exception:- body = ""- is_rate_limited = "rate limit" in body.lower()- else:- return-- if not is_rate_limited:- return-- def _int_header(name: str) -> int | None:- val = response.headers.get(name)- if not val:- return None- try:- return int(val)- except (ValueError, TypeError):- return None-- reset_at = _int_header("x-ratelimit-reset")- retry_after = _int_header("retry-after")- if retry_after is None and reset_at is not None:- retry_after = max(1, reset_at - int(time.time()))-- raise GitHubRateLimitError(- f"GitHub API rate limit exceeded (resets at {reset_at})",- reset_at=reset_at,- retry_after=retry_after,- )--@dataclass(frozen=True)class GitHubInstallationAccess:"""Installation-level access token response for a GitHub App installation."""diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex ebc4f2954152..4f2f675bd105 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -19,6 +19,7 @@ from parameterized import parameterizedfrom prometheus_client import REGISTRYfrom rest_framework.exceptions import ValidationError+from posthog.egress.github.transport import GitHubRateLimitError, raise_if_github_rate_limitedfrom 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 (@@ -32,7 +33,6 @@ from posthog.models.integration import (EmailIntegration,GitHubIntegration,GitHubIntegrationError,- GitHubRateLimitError,GoogleCloudIntegration,GoogleCloudServiceAccountIntegration,Integration,@@ -43,7 +43,6 @@ from posthog.models.integration import (S3CredentialIntegrationError,SlackIntegration,invalidate_github_repository_caches_for_installation,- raise_if_github_rate_limited,)from posthog.models.organization import Organizationfrom posthog.models.team.team import Team@@ -1123,7 +1122,7 @@ class TestGitHubIntegrationModel(BaseTest):),])- @patch("posthog.models.github_integration_base.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_github_api_request_metrics_include_integration_and_rate_limit_headers(self,_name: str,@@ -1184,7 +1183,7 @@ class TestGitHubIntegrationModel(BaseTest):== expected_reset)- @patch("posthog.models.github_integration_base.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_github_api_request_metrics_include_request_exceptions(self, mock_get):integration = self.create_integration({"installation_id": "INSTALL", "account": {"name": "PostHog"}},@@ -1303,7 +1302,7 @@ class TestGitHubIntegrationModel(BaseTest):integration.refresh_from_db()assert integration.errors == ""- @patch("posthog.models.github_integration_base.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_list_repositories_retries_transient_non_json_response(self, _mock_expired, mock_get):integration = self.create_integration(@@ -1335,7 +1334,7 @@ class TestGitHubIntegrationModel(BaseTest):assert has_more is Falseassert mock_get.call_count == 2- @patch("posthog.models.github_integration_base.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_list_repositories_raises_after_repeated_transient_non_json(self, _mock_expired, mock_get):integration = self.create_integration(@@ -1358,7 +1357,7 @@ class TestGitHubIntegrationModel(BaseTest):assert mock_get.call_count == 2- @patch("posthog.models.github_integration_base.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_list_all_repositories_raises_when_later_page_fails(self, _mock_expired, mock_get):integration = self.create_integration(@@ -1922,8 +1921,13 @@ class TestGitHubIntegrationModel(BaseTest):# --- exception hierarchy ---- def test_github_rate_limit_error_is_integration_error(self):- assert isinstance(GitHubRateLimitError("test"), GitHubIntegrationError)+ def test_github_rate_limit_error_is_egress_error_not_fatal_integration_error(self):+ # Deliberately NOT a GitHubIntegrationError: a transient rate limit is retryable, not a fatal+ # integration failure, and it lives in the egress layer. Backoff filters key off these fields.+ err = GitHubRateLimitError("test", retry_after=45)+ assert not isinstance(err, GitHubIntegrationError)+ assert err.is_rate_limit is True+ assert err.retry_after_seconds == 45.0# --- get_access_token ---@@ -1977,7 +1981,7 @@ class TestGitHubIntegrationGhApiGet(BaseTest):sensitive_config={"access_token": "ACCESS_TOKEN"},)- @patch("posthog.models.integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_returns_parsed_json_body(self, _mock_expired, mock_get):ok = MagicMock()@@ -1989,7 +1993,7 @@ class TestGitHubIntegrationGhApiGet(BaseTest):body = GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")assert body == {"default_branch": "main"}- @patch("posthog.models.integration.requests.get")+ @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):transient = MagicMock()@@ -2005,7 +2009,7 @@ class TestGitHubIntegrationGhApiGet(BaseTest):assert body == {"ok": True}assert mock_get.call_count == 2- @patch("posthog.models.integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_raises_rate_limit_error_on_secondary_limit(self, _mock_expired, mock_get):resp = MagicMock()@@ -2020,7 +2024,7 @@ class TestGitHubIntegrationGhApiGet(BaseTest):assert excinfo.value.is_rate_limit is Trueassert excinfo.value.retry_after_seconds == 5.0- @patch("posthog.models.integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_detects_secondary_limit_from_body_when_headers_missing(self, _mock_expired, mock_get):resp = MagicMock()@@ -2036,7 +2040,7 @@ class TestGitHubIntegrationGhApiGet(BaseTest):assert excinfo.value.is_rate_limit is Trueassert excinfo.value.retry_after_seconds == 60.0- @patch("posthog.models.integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.refresh_access_token")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)def test_refreshes_token_on_401(self, _mock_expired, mock_refresh, mock_get):diff --git a/posthog/rate_limiting/__init__.py b/posthog/rate_limiting/__init__.pydeleted file mode 100644index f10d28db1687..000000000000--- a/posthog/rate_limiting/__init__.py+++ /dev/null@@ -1,21 +0,0 @@-"""General-purpose outbound API egress rate limiting.--Shared, Redis-backed budgets for calls leaving PostHog to third-party APIs, so every worker-process draws from one limit. Consumers go through ``OutboundRateLimiter`` with a key like-``"github:installation:123"``; per-target budgets are declared as ``RatePolicy`` objects and-registered by each consumer's adapter (see ``posthog.rate_limiting.github``).--Distinct from ``posthog.rate_limit`` (inbound DRF request throttling) — this limits what we-send out, not what clients send us.-"""--from posthog.rate_limiting.outbound import OutboundRateLimiter, get_outbound_rate_limiter-from posthog.rate_limiting.policies import Priority, RatePolicy, register_policy--__all__ = [- "OutboundRateLimiter",- "get_outbound_rate_limiter",- "Priority",- "RatePolicy",- "register_policy",-]diff --git a/posthog/temporal/tests/data_imports/github/test_github_source.py b/posthog/temporal/tests/data_imports/github/test_github_source.pyindex 97ce732fa854..2c4d79335a45 100644--- a/posthog/temporal/tests/data_imports/github/test_github_source.py+++ b/posthog/temporal/tests/data_imports/github/test_github_source.py@@ -11,7 +11,7 @@ import requestsfrom parameterized import parameterizedfrom tenacity import Future, RetryCallState-from posthog.models.integration import GitHubRateLimitError+from posthog.egress.github.transport import GitHubRateLimitErrorfrom products.warehouse_sources.backend.facade.types import ExternalDataSourceTypefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import (@@ -625,7 +625,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = responses+ mock_get.return_value.request.side_effect = responseslist(get_rows(personal_access_token="tok",@@ -637,7 +637,7 @@ class TestGetRowsResume:))- first_url = mock_get.return_value.get.call_args_list[0].args[0]+ first_url = mock_get.return_value.request.call_args_list[0].args[1]assert first_url.startswith("https://api.github.com/repos/owner/repo/releases")manager.load_state.assert_not_called()@@ -659,7 +659,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = responses+ mock_get.return_value.request.side_effect = responseslist(get_rows(personal_access_token="tok",@@ -671,7 +671,7 @@ class TestGetRowsResume:))- assert mock_get.return_value.get.call_args_list[0].args[0] == saved_url+ assert mock_get.return_value.request.call_args_list[0].args[1] == saved_urlmanager.load_state.assert_called_once()def test_empty_first_page_ends_loop(self) -> None:@@ -682,7 +682,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = [_make_response(body=[], link="")]+ mock_get.return_value.request.side_effect = [_make_response(body=[], link="")]rows = list(get_rows(personal_access_token="tok",@@ -707,7 +707,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = [_make_response(body=[{"id": 1}], link="")]+ mock_get.return_value.request.side_effect = [_make_response(body=[{"id": 1}], link="")]list(get_rows(personal_access_token="tok",@@ -721,7 +721,7 @@ class TestGetRowsResume:assert manager.save_state.call_count == 1saved = manager.save_state.call_args.args[0]- assert saved.next_url == mock_get.return_value.get.call_args_list[0].args[0]+ assert saved.next_url == mock_get.return_value.request.call_args_list[0].args[1]def test_empty_repository_409_syncs_zero_rows(self) -> None:"""An empty repo returns 409 "Git Repository is empty." on the commits@@ -736,7 +736,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = [empty_repo_409]+ mock_get.return_value.request.side_effect = [empty_repo_409]rows = list(get_rows(personal_access_token="tok",@@ -767,7 +767,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = [other_409]+ mock_get.return_value.request.side_effect = [other_409]with pytest.raises(requests.HTTPError):list(get_rows(@@ -790,7 +790,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = [_make_response(body=envelope, link="")]+ mock_get.return_value.request.side_effect = [_make_response(body=envelope, link="")]rows = list(get_rows(personal_access_token="tok",@@ -815,7 +815,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = [_make_response(body=envelope, link="")]+ mock_get.return_value.request.side_effect = [_make_response(body=envelope, link="")]rows = list(get_rows(personal_access_token="tok",@@ -861,7 +861,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = responses+ mock_get.return_value.request.side_effect = responsesrows = list(get_rows(personal_access_token="tok",@@ -876,8 +876,8 @@ class TestGetRowsResume:)assert [row["id"] for row in rows] == [3, 2, 1]- assert mock_get.return_value.get.call_count == 2- first_url = mock_get.return_value.get.call_args_list[0].args[0]+ assert mock_get.return_value.request.call_count == 2+ first_url = mock_get.return_value.request.call_args_list[0].args[1]assert "created=" not in first_urlassert "since=" not in first_urlassert "/actions/runs" in first_url@@ -911,7 +911,7 @@ class TestGetRowsResume:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get,):- mock_get.return_value.get.side_effect = responses+ mock_get.return_value.request.side_effect = responseslist(get_rows(personal_access_token="tok",@@ -927,7 +927,7 @@ class TestGetRowsResume:# the next-page URL — otherwise item 3 (batched but not yet yielded)# would be skipped on resume.first_save = manager.save_state.call_args_list[0].args[0]- assert first_save.next_url == mock_get.return_value.get.call_args_list[0].args[0]+ assert first_save.next_url == mock_get.return_value.request.call_args_list[0].args[1]assert first_save.next_url != "https://api.github.com/repos/owner/repo/releases?page=2"@@ -1057,7 +1057,7 @@ class _RoutingSession:self._jobs_by_run = jobs_by_runself.calls: list[str] = []- def get(self, url: str, headers: Any = None, timeout: Any = None) -> Any:+ def request(self, method: str, url: str, headers: Any = None, timeout: Any = None, **kwargs: Any) -> Any:self.calls.append(url)if "/jobs" in url:run_id = int(urlparse(url).path.split("/")[-2])@@ -1318,7 +1318,7 @@ class TestIterPages:with mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get:- mock_get.return_value.get.side_effect = responses+ mock_get.return_value.request.side_effect = responsespages = list(_iter_pages("https://api.github.com/x", {}, "jobs", mock.Mock()))assert [items for items, _url in pages] == [[{"id": 1}], [{"id": 2}]]@@ -1334,7 +1334,7 @@ class TestIterPages:with mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get:- mock_get.return_value.get.side_effect = [_make_response(body=body, link="")]+ mock_get.return_value.request.side_effect = [_make_response(body=body, link="")]pages = list(_iter_pages("https://api.github.com/x", {}, "jobs", mock.Mock()))assert pages == []@@ -1349,7 +1349,7 @@ class TestIterPages:with mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get:- mock_get.return_value.get.side_effect = responses+ mock_get.return_value.request.side_effect = responsespages = list(_iter_pages("https://api.github.com/x",@@ -1378,11 +1378,11 @@ class TestIterPages:with mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session",) as mock_get:- mock_get.return_value.get.side_effect = responses+ mock_get.return_value.request.side_effect = responsesjobs = list(_iter_jobs_for_run("owner/repo", 1001, {}, logger, config))assert [job["id"] for job in jobs] == [1]- url = mock_get.return_value.get.call_args_list[0].args[0]+ url = mock_get.return_value.request.call_args_list[0].args[1]assert "/repos/owner/repo/actions/runs/1001/jobs" in urlassert "filter=all" in url# Cap of 1 page reached (a next link exists) → warning emitted.@@ -1635,12 +1635,12 @@ class TestFetchPageRateLimit:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get,):- mock_get.return_value.get.return_value = resp+ mock_get.return_value.request.return_value = respwith pytest.raises(GitHubRateLimitError):_fetch_page("https://api.github.com/x", {}, mock.Mock())# stop_after_attempt(5): the rate limit is retried, not treated as fatal on first hit.- assert mock_get.return_value.get.call_count == 5+ assert mock_get.return_value.request.call_count == 5def test_recovers_when_rate_limit_clears(self) -> None:rate_limited = _rate_limited_response(429, "Too Many Requests", {"retry-after": "1"})@@ -1652,11 +1652,11 @@ class TestFetchPageRateLimit:"products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get,):- mock_get.return_value.get.side_effect = [rate_limited, ok]+ mock_get.return_value.request.side_effect = [rate_limited, ok]response = _fetch_page("https://api.github.com/x", {}, mock.Mock())assert response is ok- assert mock_get.return_value.get.call_count == 2+ assert mock_get.return_value.request.call_count == 2def test_permission_403_is_fatal_not_retried(self) -> None:# A 403 with no rate-limit body is a real permission error: surface it@@ -1668,11 +1668,11 @@ class TestFetchPageRateLimit:with mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get:- mock_get.return_value.get.return_value = resp+ mock_get.return_value.request.return_value = respwith pytest.raises(requests.HTTPError):_fetch_page("https://api.github.com/x", {}, mock.Mock())- assert mock_get.return_value.get.call_count == 1+ assert mock_get.return_value.request.call_count == 1def test_disables_adapter_retries_so_cap_is_authoritative(self) -> None:# The tracked session's default adapter retries 429/5xx and honors Retry-After@@ -1683,7 +1683,7 @@ class TestFetchPageRateLimit:with mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.github.github.make_tracked_session") as mock_get:- mock_get.return_value.get.return_value = ok+ mock_get.return_value.request.return_value = ok_fetch_page("https://api.github.com/x", {}, mock.Mock())retry = mock_get.call_args.kwargs["retry"]diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex dbf04632df62..9c3ea8fcaf6e 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -19,11 +19,11 @@ import requestsimport structlogfrom celery import shared_task+from posthog.egress.github.transport import github_requestfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.comment import Comment as CommentModelfrom posthog.models.team import Teamfrom posthog.models.uploaded_media import UploadedMedia-from posthog.rate_limiting.github_observability import record_github_api_responsefrom posthog.scoping_audit import skip_team_scope_auditfrom posthog.storage import object_storage@@ -92,7 +92,6 @@ SUPPORTHOG_EVENT_IDEMPOTENCY_TTL_SECONDS = 6 * 60SUPPORTHOG_EVENT_IDEMPOTENCY_KEY_PREFIX = "supporthog:slack:event:"SUPPORTHOG_TEAMS_EVENT_IDEMPOTENCY_KEY_PREFIX = "supporthog:teams:event:"SUPPORTHOG_GITHUB_EVENT_IDEMPOTENCY_KEY_PREFIX = "supporthog:github:event:"-GITHUB_API_VERSION = "2022-11-28"def _is_duplicate_supporthog_event(event_id: str) -> bool:@@ -1782,17 +1781,15 @@ def post_reply_to_github(url = f"https://api.github.com/repos/{ticket.github_repo}/issues/{ticket.github_issue_number}/comments"try:- resp = requests.post(+ resp = github_request(+ "POST",url,+ source="conversations",+ headers={"Authorization": f"Bearer {access_token}"},+ installation_id=github.github_installation_id,json={"body": reply_text},- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },timeout=15,)- record_github_api_response(resp, source="conversations", installation_id=github.github_installation_id)if resp.status_code not in (200, 201):logger.warning("github_reply_post_failed",@@ -1854,17 +1851,15 @@ def create_github_issue(url = f"https://api.github.com/repos/{repo}/issues"try:- resp = requests.post(+ resp = github_request(+ "POST",url,+ source="conversations",+ headers={"Authorization": f"Bearer {access_token}"},+ installation_id=github.github_installation_id,json=json_body,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },timeout=15,)- record_github_api_response(resp, source="conversations", installation_id=github.github_installation_id)resp.raise_for_status()except requests.RequestException as e:logger.exception("github_create_issue_failed", repo=repo, error=str(e))diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.pyindex 48063538a035..c452d8cdf05b 100644--- a/products/engineering_analytics/backend/logic/job_logs/activity.py+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py@@ -17,8 +17,8 @@ from temporalio import activity, workflowfrom temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationError+from posthog.egress.github.limiter import acquire_github_installationfrom posthog.models.integration import GitHubIntegration, Integration-from posthog.rate_limiting.github import acquire_github_installationfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowdiff --git a/products/engineering_analytics/backend/logic/job_logs/fetcher.py b/products/engineering_analytics/backend/logic/job_logs/fetcher.pyindex 0511630ba61d..3984485fae86 100644--- a/products/engineering_analytics/backend/logic/job_logs/fetcher.py+++ b/products/engineering_analytics/backend/logic/job_logs/fetcher.py@@ -8,7 +8,8 @@ the Temporal retry honors the reset.import requests-from posthog.models.integration import GITHUB_API_VERSION, _is_safe_github_repo_path, raise_if_github_rate_limited+from posthog.egress.github.transport import GITHUB_API_VERSION, raise_if_github_rate_limited+from posthog.models.integration import _is_safe_github_repo_path_GITHUB_API = "https://api.github.com"_BASE_HEADERS = {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": GITHUB_API_VERSION}diff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py b/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.pyindex 595bb49e954a..ccafefa533cc 100644--- a/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_fetcher.py@@ -2,7 +2,7 @@ import pytestimport requests-from posthog.models.integration import GitHubRateLimitError+from posthog.egress.github.transport import GitHubRateLimitErrorfrom products.engineering_analytics.backend.logic.job_logs.fetcher import fetch_job_logdiff --git a/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py b/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.pyindex b4d34f9a8b0b..677c9288e7ed 100644--- a/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py+++ b/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py@@ -11,8 +11,8 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action+from posthog.egress.github.transport import github_requestfrom posthog.models.integration import GitHubIntegration, GitLabIntegration, Integration-from posthog.rate_limiting.github_observability import record_github_api_responselogger = structlog.get_logger(__name__)@@ -89,12 +89,12 @@ def get_github_file_url(headers = {"Authorization": f"token {token}","Accept": "application/vnd.github.text-match+json",- "X-GitHub-Api-Version": "2022-11-28",}try:- response = requests.get(url, headers=headers, timeout=10)- record_github_api_response(response, source="error_tracking", installation_id=installation_id)+ response = github_request(+ "GET", url, source="error_tracking", headers=headers, installation_id=installation_id, timeout=10+ )if response.status_code == 200:data = response.json()diff --git a/products/visual_review/backend/github.py b/products/visual_review/backend/github.pyindex c8307adc6dd9..2e337ff65e11 100644--- a/products/visual_review/backend/github.py+++ b/products/visual_review/backend/github.py@@ -10,8 +10,11 @@ from __future__ import annotationsimport requestsimport structlog-from posthog.models.integration import GITHUB_API_VERSION, GitHubRateLimitError, raise_if_github_rate_limited-from posthog.rate_limiting.github_observability import record_github_api_response+from posthog.egress.github.transport import (+ GitHubRateLimitError,+ github_request as _egress_github_request,+ raise_if_github_rate_limited,+)logger = structlog.get_logger(__name__)@@ -31,17 +34,16 @@ def github_request(Raises GitHubRateLimitError on 403/429 when the rate limit is exhausted."""- headers = {- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- **(kwargs.pop("headers", {})),- }-- response = requests.request(method, url, headers=headers, **kwargs)-- # source="visual_review"; the existing structlog lines below stay for low-remaining alerts.- record_github_api_response(response, source="visual_review", installation_id=installation_id)+ # Gated + recorded by the shared egress client; visual review keeps only its own rate-limit+ # response handling (the structlog low-remaining alerts + raising GitHubRateLimitError on 403/429).+ response = _egress_github_request(+ method,+ url,+ source="visual_review",+ headers={"Authorization": f"Bearer {access_token}", **(kwargs.pop("headers", {}))},+ installation_id=installation_id,+ **kwargs,+ )_log_rate_limit_headers(response, method, url)_check_rate_limit_response(response, method, url)diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex 67249a75eff1..25881141be60 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -30,8 +30,8 @@ import structlogif TYPE_CHECKING:from posthog.models.integration import GitHubIntegration+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.helpers.trigram_search import TrigramSearchField, apply_trigram_search, normalize_search_term-from posthog.models.integration import GitHubRateLimitErrorfrom .classifier import SnapshotClassifierfrom .db import READER_DB, WRITER_DBdiff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.pyindex 43d8dd25f289..7d6052a4c56c 100644--- a/products/visual_review/backend/tasks/tasks.py+++ b/products/visual_review/backend/tasks/tasks.py@@ -37,7 +37,7 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:Verifies hash integrity of new uploads before creating Artifactrecords and computing diffs."""- from posthog.models.integration import GitHubRateLimitError+ from posthog.egress.github.transport import GitHubRateLimitErrorfrom .. import logicfrom ..diffing import process_diffs@@ -87,7 +87,7 @@ def post_approval_comment(self, team_id: int, run_id: str, add_images: bool = Farate-limit errors only. ``add_images`` embeds the before/after snapshotimages when the reviewer opted in at finalize time."""- from posthog.models.integration import GitHubRateLimitError+ from posthog.egress.github.transport import GitHubRateLimitErrorfrom .. import logicdiff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.pyindex fc42d01b2b72..ed469aea0989 100644--- a/products/visual_review/backend/tests/test_tasks.py+++ b/products/visual_review/backend/tests/test_tasks.py@@ -186,7 +186,7 @@ class TestPostApprovalCommentTask:post_approval_comment(repo.team_id, "00000000-0000-0000-0000-000000000002")def test_retries_on_rate_limit(self, repo):- from posthog.models.integration import GitHubRateLimitError+ from posthog.egress.github.transport import GitHubRateLimitErrorwith (patch(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 0e230b8e0f32..c6c3b591cefb 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@@ -14,10 +14,13 @@ from structlog.types import FilteringBoundLoggerfrom tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitterfrom urllib3.util.retry import Retry-from posthog.models.integration import GitHubRateLimitError, raise_if_github_rate_limited-from posthog.rate_limiting.github import consume_github_installation_sync-from posthog.rate_limiting.github_observability import record_github_api_exception, record_github_api_response-from posthog.rate_limiting.policies import Priority+from posthog.egress.github.transport import (+ GitHubEgressBudgetExhausted,+ GitHubRateLimitError,+ github_request,+ raise_if_github_rate_limited,+)+from posthog.egress.limiter.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@@ -369,6 +372,8 @@ def _github_retry_wait(state: RetryCallState) -> float:retry=retry_if_exception_type((GithubRetryableError,+ # Our egress limiter shed this deferrable page (BATCH); back off and re-acquire next attempt.+ GitHubEgressBudgetExhausted,GitHubRateLimitError,requests.ReadTimeout,requests.ConnectionError,@@ -388,28 +393,22 @@ def _fetch_page(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.+ # One gated + recorded GET through the shared egress client. The App path bills the shared+ # per-installation budget at BATCH (deferrable bulk); the PAT path (installation_id None) skips the+ # gate and records volume only. On a BATCH denial the client raises GitHubEgressBudgetExhausted, which+ # this function's @retry backs off on; transport failures are recorded and re-raised for the same+ # retry. We keep our own tracked session and the GitHub response→exception mapping below.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, installation_id=installation_id)- raise-- # 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)+ response = github_request(+ "GET",+ page_url,+ source="warehouse",+ headers=headers,+ installation_id=installation_id,+ priority=Priority.BATCH,+ timeout=60,+ session=make_tracked_session(retry=_NO_ADAPTER_RETRY),+ )# Transient server errors: retry with plain exponential backoff.if response.status_code >= 500: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 53f881053213..92d45495ac9c 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,7 +4,7 @@ from unittest import mockimport requestsfrom prometheus_client import REGISTRY-from posthog.rate_limiting.policies import Priority+from posthog.egress.limiter.policies import Priorityfrom products.warehouse_sources.backend.temporal.data_imports.sources.github import github@@ -30,18 +30,18 @@ def _instant_backoff():def test_fetch_page_retries_chunked_encoding_error():session = mock.Mock()- session.get.side_effect = [requests.exceptions.ChunkedEncodingError("Connection broken"), _ok_response()]+ session.request.side_effect = [requests.exceptions.ChunkedEncodingError("Connection broken"), _ok_response()]with mock.patch.object(github, "make_tracked_session", return_value=session):response = github._fetch_page("https://api.github.com/repos/o/r/issues", {}, mock.Mock())assert response.status_code == 200- assert session.get.call_count == 2+ assert session.request.call_count == 2def test_fetch_page_reraises_chunked_encoding_error_after_exhausting_retries():session = mock.Mock()- session.get.side_effect = [requests.exceptions.ChunkedEncodingError("Connection broken")] * 5+ session.request.side_effect = [requests.exceptions.ChunkedEncodingError("Connection broken")] * 5exception_labels = {"installation_id": "",@@ -56,27 +56,27 @@ def test_fetch_page_reraises_chunked_encoding_error_after_exhausting_retries():with pytest.raises(requests.exceptions.ChunkedEncodingError):github._fetch_page("https://api.github.com/repos/o/r/issues", {}, mock.Mock())- assert session.get.call_count == 5+ assert session.request.call_count == 5# 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 0- assert after - before == session.get.call_count+ assert after - before == session.request.call_countdef 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()+ session.request.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("posthog.egress.github.transport.consume_github_installation_sync", return_value=False) as gate,mock.patch.object(github, "make_tracked_session", return_value=session),):- with pytest.raises(github.GithubRetryableError):+ with pytest.raises(github.GitHubEgressBudgetExhausted):github._fetch_page("https://api.github.com/repos/o/r/issues", {}, mock.Mock(), identity)- assert session.get.call_count == 0+ assert session.request.call_count == 0assert gate.call_count == 5assert gate.call_args.args[0] == "123"assert gate.call_args.kwargs == {"priority": Priority.BATCH, "source": "warehouse"}@@ -85,10 +85,10 @@ def test_fetch_page_gates_on_egress_budget_when_installation_known():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()+ session.request.return_value = _ok_response()with (- mock.patch.object(github, "consume_github_installation_sync") as gate,+ mock.patch("posthog.egress.github.transport.consume_github_installation_sync") as gate,mock.patch.object(github, "make_tracked_session", return_value=session),):response = github._fetch_page(@@ -97,4 +97,4 @@ def test_fetch_page_skips_gate_on_pat_path():assert response.status_code == 200assert gate.call_count == 0- assert session.get.call_count == 1+ assert session.request.call_count == 1