: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): consolidate GitHub product callers onto the integration client (#67662)
Julian Bezce51aec3e8bd
diff --git a/.github/workflows/ci-dagster.yml b/.github/workflows/ci-dagster.ymlindex e4251ba7ae62..acb0f715198e 100644--- a/.github/workflows/ci-dagster.yml+++ b/.github/workflows/ci-dagster.yml@@ -102,6 +102,7 @@ jobs:# --- posthog submodules that DAGs actually import ---# (verified by tracing imports of all 148 dagster Python files)- 'posthog/clickhouse/**'+ - 'posthog/egress/**'- 'posthog/models/**'- 'posthog/hogql/**'- 'posthog/hogql_queries/**'diff --git a/.semgrep/devex-rules/github-api-calls-go-through-egress.py b/.semgrep/devex-rules/github-api-calls-go-through-egress.pynew file mode 100644index 000000000000..74af9f8d9bba--- /dev/null+++ b/.semgrep/devex-rules/github-api-calls-go-through-egress.py@@ -0,0 +1,30 @@+# Test cases for github-api-calls-go-through-egress rule.+# ruff: noqa: F841, E501+import requests++from posthog.egress.github.transport import github_request+++def flagged_literal_url(token: str):+ # ruleid: github-api-calls-go-through-egress+ return requests.get("https://api.github.com/user", headers={"Authorization": f"Bearer {token}"})+++def flagged_fstring_url(repo: str):+ # ruleid: github-api-calls-go-through-egress+ return requests.post(f"https://api.github.com/repos/{repo}/issues", json={"title": "x"})+++def flagged_generic_request(method: str):+ # ruleid: github-api-calls-go-through-egress+ return requests.request(method, "https://uploads.github.com/repos/o/r/releases/1/assets")+++def ok_through_transport(token: str):+ # ok: github-api-calls-go-through-egress+ return github_request("GET", "https://api.github.com/user", source="integration", headers={})+++def ok_other_host():+ # ok: github-api-calls-go-through-egress+ return requests.get("https://example.com/api")diff --git a/.semgrep/devex-rules/github-api-calls-go-through-egress.yaml b/.semgrep/devex-rules/github-api-calls-go-through-egress.yamlnew file mode 100644index 000000000000..0567e2221dc1--- /dev/null+++ b/.semgrep/devex-rules/github-api-calls-go-through-egress.yaml@@ -0,0 +1,44 @@+rules:+ - id: github-api-calls-go-through-egress+ message: |+ Outbound GitHub API calls must go through the gated, recorded egress transport —+ never raw `requests`.++ Use one of:+ - `GitHubIntegrationBase.api_request(...)` when you hold a `GitHubIntegration` /+ `UserGitHubIntegration` — it owns token refresh, the 401 refresh-retry,+ rate-limit raising (`GitHubRateLimitError`), and telemetry attribution via the+ instance's `source`.+ - `posthog.egress.github.transport.github_request(...)` for token-agnostic calls+ (user OAuth tokens, PATs, App JWTs). Pass `installation_id` only when the call+ is metered against that installation's budget — user-token and App-JWT calls+ are identity-blind (`installation_id=None`).++ Why: a raw call bypasses the shared per-installation rate-limit budget and the+ egress telemetry (request volume + `X-RateLimit-*` gauges), so it can burn a+ customer's GitHub budget invisibly. See `posthog/egress/README.md`.++ This rule only catches literal/f-string URLs; keep URLs inline at the call site.+ Suppress a legitimate exception with+ `# nosemgrep: github-api-calls-go-through-egress -- <reason>`.+ languages: [python]+ severity: ERROR+ patterns:+ - pattern-either:+ - patterns:+ - pattern: requests.$METHOD($URL, ...)+ - metavariable-regex:+ metavariable: $METHOD+ regex: ^(get|post|put|patch|delete|head)$+ - pattern: requests.request($METHOD, $URL, ...)+ - metavariable-regex:+ metavariable: $URL+ regex: .*(api|uploads)\.github\.com.*+ paths:+ include:+ - common/**/*.py+ - ee/**/*.py+ - posthog/**/*.py+ - products/**/*.py+ exclude:+ - posthog/egress/**diff --git a/posthog/api/github_callback/personal_finish.py b/posthog/api/github_callback/personal_finish.pyindex cb6be03cb87d..55049bac3cfd 100644--- a/posthog/api/github_callback/personal_finish.py+++ b/posthog/api/github_callback/personal_finish.py@@ -18,6 +18,7 @@ from posthog.api.github_callback.types import (github_oauth_redirect_uri,is_valid_github_installation_id,)+from posthog.egress.github.transport import github_requestfrom posthog.models import Userfrom posthog.models.integration import GitHubInstallationAccessFetchError, GitHubIntegration, Integrationfrom posthog.models.user_integration import (@@ -114,13 +115,12 @@ def finish_personal(request: HttpRequest) -> FinishResult:if flow.discovers_installations:try:- response = requests.get(+ # Identity-blind: user OAuth token, metered against the user's budget, not an installation's.+ response = github_request(+ "GET","https://api.github.com/user/installations",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {authorization.access_token}",- "X-GitHub-Api-Version": "2022-11-28",- },+ source="integration",+ headers={"Authorization": f"Bearer {authorization.access_token}"},params={"per_page": 100},timeout=10,)diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex cacdfd03b22f..123254569b41 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -14,7 +14,7 @@ import requestsimport structlogfrom django_filters.rest_framework import DjangoFilterBackendfrom drf_spectacular.utils import extend_schema, extend_schema_serializer-from rest_framework import mixins, serializers, viewsets+from rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.exceptions import PermissionDenied, ValidationErrorfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Request@@ -37,6 +37,7 @@ from posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import actionfrom posthog.auth import SessionAuthenticationfrom posthog.domain_connect import discover_domain_connect, extract_root_domain_and_host, get_available_providers+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.fuzzy_search import fuzzy_filter@@ -802,6 +803,21 @@ class GitHubOAuthAuthorizeResponseSerializer(serializers.Serializer):oauth_url = serializers.CharField(help_text="GitHub User OAuth URL the client should redirect to.")+def github_rate_limited_response(exc: GitHubRateLimitError) -> Response:+ """The 429 + Retry-After response for a GitHub rate limit.++ Shared by every GitHub-backed endpoint (integration and user-integration viewsets, signals)+ so the egress ``GitHubRateLimitError`` maps the same way everywhere instead of surfacing a 500.+ """+ response = Response(+ {"detail": "GitHub API rate limit exceeded. Please retry later.", "code": "rate_limited"},+ status=status.HTTP_429_TOO_MANY_REQUESTS,+ )+ if exc.retry_after:+ response["Retry-After"] = str(exc.retry_after)+ return response++@extend_schema(extensions={"x-product": "integrations"})class IntegrationViewSet(TeamAndOrgViewSetMixin,@@ -847,6 +863,13 @@ class IntegrationViewSet(filter_backends = [DjangoFilterBackend]filterset_fields = ["kind"]+ def handle_exception(self, exc: Exception) -> Response:+ # GitHub rate limits surface from any GitHub-backed action (teams, repos, branches, refresh);+ # map them to 429 + Retry-After once here instead of per action.+ if isinstance(exc, GitHubRateLimitError):+ return github_rate_limited_response(exc)+ return super().handle_exception(exc)+def dangerously_get_permissions(self):if self.action == "refresh_github_repos":return [diff --git a/posthog/api/test/test_user_integration.py b/posthog/api/test/test_user_integration.pyindex c152f5c9a104..69c81050c3c8 100644--- a/posthog/api/test/test_user_integration.py+++ b/posthog/api/test/test_user_integration.py@@ -325,7 +325,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):GITHUB_APP_CLIENT_SECRET="client_secret",SITE_URL="https://us.posthog.com",)- @patch("posthog.api.user_integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.client_request")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")def test_github_link_oauth_callback_creates_user_integration_without_installation_in_query(@@ -385,7 +385,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):GITHUB_APP_CLIENT_SECRET="client_secret",SITE_URL="https://us.posthog.com",)- @patch("posthog.api.user_integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.client_request")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")def test_github_link_oauth_callback_ignores_query_installation_id_when_state_binds_one(@@ -435,7 +435,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertTrue(UserIntegration.objects.filter(user=self.user, integration_id="12345").exists())self.assertFalse(UserIntegration.objects.filter(integration_id="999").exists())# The installation-access check went against the cached id, not the query one.- verify_url = mock_verify_get.call_args[0][0]+ verify_url = mock_verify_get.call_args[0][1]self.assertIn("/installations/12345/repositories", verify_url)self.assertNotIn("/installations/999/repositories", verify_url)@@ -444,7 +444,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):GITHUB_APP_CLIENT_SECRET="client_secret",SITE_URL="https://us.posthog.com",)- @patch("posthog.api.user_integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.client_request")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")def test_github_link_oauth_discover_creates_user_integration_from_visible_installation(@@ -500,7 +500,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):"posthog.api.github_callback.types.get_instance_settings",return_value={"GITHUB_APP_SLUG": "posthog-dev"},)- @patch("posthog.api.user_integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")def test_github_link_oauth_discover_redirects_to_app_install_when_no_installations(self, mock_user_from_code, mock_requests_get, _mock_settings@@ -530,7 +530,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):self.assertIn("github.com/apps/posthog-dev/installations/new", response["Location"])@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")- @patch("posthog.api.user_integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.client_request")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")def test_github_link_callback_creates_user_integration(@@ -576,7 +576,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):])@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")- @patch("posthog.api.user_integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.client_request")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")def test_github_link_redirects_to_client_destination_on_success(@@ -694,7 +694,7 @@ class TestUserIntegrationEndpoints(APIBaseTest):@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")@patch("posthog.models.integration.GitHubIntegration.integration_from_installation_id")- @patch("posthog.api.user_integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.client_request")@patch("posthog.models.integration.GitHubIntegration.github_user_from_code")def test_github_link_callback_team_oauth_authorize_creates_team_integration(@@ -1033,7 +1033,7 @@ class TestUserGitHubIntegrationFromInstallation(APIBaseTest):class TestGithubUserFromCode(APIBaseTest):- @patch("posthog.models.integration.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.requests.post")@override_settings(GITHUB_APP_CLIENT_ID="client_id", GITHUB_APP_CLIENT_SECRET="client_secret")def test_returns_full_authorization_including_tokens(self, mock_post, mock_get):diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.pyindex 04b781b842e0..a03de51b34fd 100644--- a/posthog/api/user_integration.py+++ b/posthog/api/user_integration.py@@ -40,9 +40,11 @@ from posthog.api.integration import (GitHubReposQuerySerializer,GitHubReposRefreshResponseSerializer,GitHubReposResponseSerializer,+ github_rate_limited_response,validate_github_repository_name,)from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.egress.github.transport import GitHubRateLimitError, github_requestfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, Integrationfrom posthog.models.user import User@@ -228,6 +230,13 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):http_method_names = ["get", "post", "delete"]serializer_class = UserGitHubIntegrationItemSerializer+ def handle_exception(self, exc: Exception) -> Response:+ # Personal-GitHub actions (repos, branches, refresh) raise the same egress+ # GitHubRateLimitError as the team integration endpoints — same 429 mapping.+ if isinstance(exc, GitHubRateLimitError):+ return github_rate_limited_response(exc)+ return super().handle_exception(exc)+def _get_user(self) -> User:"""Resolve the target user from the nested ``parent_lookup_uuid`` (same rules as ``UserViewSet``)."""request_user = cast(User, self.request.user)@@ -705,13 +714,12 @@ def _has_unlinked_github_installations(user: User) -> bool | None:return Nonetry:- response = requests.get(+ # Identity-blind: user OAuth token, metered against the user's budget, not an installation's.+ response = github_request(+ "GET","https://api.github.com/user/installations",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {token}",- "X-GitHub-Api-Version": "2022-11-28",- },+ source="integration",+ headers={"Authorization": f"Bearer {token}"},params={"per_page": 100},timeout=10,)diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex 0e2026e801e9..aa721d876d4a 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -86,7 +86,8 @@ resp = github_request(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 model-coupled `GitHubIntegrationBase.api_request` layers the installation-token lifecycle (proactive refresh, 401 refresh-retry, rate-limit raising, per-instance `source` attribution) on top — hold an integration, call that; hold a bare token, call `github_request`.+Raw `requests` calls against `api.github.com` are blocked by the `github-api-calls-go-through-egress` semgrep rule (`.semgrep/devex-rules/`), so new callers land on one of these two paths by construction.## The one identity rulediff --git a/posthog/egress/github/transport.py b/posthog/egress/github/transport.pyindex a83cab3704af..738ad7164cff 100644--- a/posthog/egress/github/transport.py+++ b/posthog/egress/github/transport.py@@ -35,28 +35,32 @@ class GitHubRateLimitError(Exception):"""GitHub itself rate-limited an outbound call (a 429, or a 403 with a rate-limit body) — thereactive, GitHub-side twin of :class:`GitHubEgressBudgetExhausted`. A GitHub egress condition, so itlives 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."""+ transient rate limit isn't a fatal integration failure. ``retry_after`` (seconds) is the backoff+ hint; :func:`raise_if_github_rate_limited` always sets it, hand-built instances may not."""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 Noneself.reset_at = reset_atself.retry_after = retry_afterdef 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."""+ """Raise :class:`GitHubRateLimitError` when the response signals a GitHub rate limit. Safe to call+ unconditionally after any GitHub API response. Covers every documented signal: secondary 429,+ primary 403 with an exhausted window (``X-RateLimit-Remaining: 0``) or a ``Retry-After`` hint,+ and 403s that only mark the limit in the body (rate limit / abuse detection)."""if response.status_code == 429:is_rate_limited = Trueelif response.status_code == 403:- try:- body = response.text- except Exception:- body = ""- is_rate_limited = "rate limit" in body.lower()+ if response.headers.get("retry-after") or response.headers.get("x-ratelimit-remaining") == "0":+ is_rate_limited = True+ else:+ try:+ body = response.text+ except Exception:+ body = ""+ body = body.lower()+ is_rate_limited = "rate limit" in body or "abuse detection" in bodyelse:return@@ -76,6 +80,9 @@ def raise_if_github_rate_limited(response: requests.Response) -> None: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()))+ if retry_after is None:+ # No timing headers at all (body-only signal) — GitHub's documented guidance is to wait ≥1 minute.+ retry_after = 60raise GitHubRateLimitError(f"GitHub API rate limit exceeded (resets at {reset_at})",diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 1108fc538737..047fed414901 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -22,8 +22,7 @@ import requestsimport structlogfrom prometheus_client import Counter-from posthog.egress.github.observability import record_github_api_exception, record_github_api_response-from posthog.egress.github.transport import GITHUB_API_VERSION, github_request+from posthog.egress.github.transport import github_request, raise_if_github_rate_limitedfrom posthog.sync import database_sync_to_async_poollogger = structlog.get_logger(__name__)@@ -53,25 +52,24 @@ class GitHubCommitAuthor:class GitHubIntegrationError(Exception):- def __init__(- self,- message: str,- *,- status_code: int | None = None,- is_rate_limit: bool = False,- retry_after_seconds: float | None = None,- ) -> None:+ """A GitHub API call failed for a non-rate-limit reason (bad response, auth failure, network+ error after retry). Rate limits raise ``GitHubRateLimitError`` from ``posthog.egress.github``+ instead — a transient limit isn't an integration failure."""++ def __init__(self, message: str, *, status_code: int | None = None) -> None:super().__init__(message)# Needed, so retry wrappers can make decisions without reparsing the response.self.status_code = status_code- self.is_rate_limit = is_rate_limit- self.retry_after_seconds = retry_after_secondsclass GitHubIntegrationBase:"""Installation-token operations shared between team and user GitHub integrations."""integration: Any # Integration | UserIntegration -- subclasses narrow the type+ # Per-subsystem attribution on the shared egress metrics. Product callers construct their client+ # with their own source (e.g. GitHubIntegration(integration, source="visual_review")) so every+ # request made through this instance — api_request, verbs, GraphQL — is attributed to them.+ source: str = _OBSERVABILITY_SOURCE@propertydef github_installation_id(self) -> str | None:@@ -116,14 +114,13 @@ class GitHubIntegrationBase:"Failed to create GitHub App JWT token. Please check your GITHUB_APP_PRIVATE_KEY format.")- return requests.request(+ # Identity-blind on purpose: App-JWT calls are metered per App, not per installation, so+ # gating them under an installation budget would be wrong — but volume telemetry still counts.+ return github_request(method,f"https://api.github.com/app/{endpoint}",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {jwt_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },+ source=_OBSERVABILITY_SOURCE,+ headers={"Authorization": f"Bearer {jwt_token}"},timeout=timeout,)@@ -230,13 +227,15 @@ class GitHubIntegrationBase:when GitHub returns 404 (no access). Raises on network errors orunexpected status codes so callers can surface an appropriate error."""- response = requests.get( # nosemgrep: python.django.security.injection.ssrf.ssrf-injection-requests.ssrf-injection-requests -- installation_id is validated as digits-only by callers+ # installation_id stays None: this call is authenticated with the *user's* OAuth token, so+ # GitHub meters it against the user's budget, not the installation's — gating or writing+ # gauges under the installation would consume/clobber a budget the call never draws from.+ response = github_request(+ "GET",f"https://api.github.com/user/installations/{installation_id}/repositories",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {user_access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },+ source=_OBSERVABILITY_SOURCE,+ headers={"Authorization": f"Bearer {user_access_token}"},+ endpoint="/user/installations/{installation_id}/repositories",params={"per_page": 1},timeout=10,)@@ -251,84 +250,11 @@ class GitHubIntegrationBase:)raise requests.RequestException(f"Unexpected status {response.status_code} verifying installation access")- def _record_github_api_response(self, response: requests.Response, method: str, endpoint: str) -> None:- record_github_api_response(- response,- source=_OBSERVABILITY_SOURCE,- installation_id=self.github_installation_id,- method=method,- endpoint=endpoint,- )-- def _record_github_api_exception(self, method: str, endpoint: str) -> None:- record_github_api_exception(- source=_OBSERVABILITY_SOURCE,- installation_id=self.github_installation_id,- method=method,- endpoint=endpoint,- )-def _record_github_cache_access(self, cache_type: Literal["repositories", "branches"], result: Literal["hit", "miss"], repository: str) -> None:github_cache_access_counter.labels(str(self.integration.id), cache_type, repository.casefold(), result).inc()- def _github_api_get(- self,- url: str,- *,- endpoint: str,- headers: dict[str, str],- params: dict[str, str | int] | None = None,- timeout: int | None = None,- ) -> requests.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,- url: str,- *,- endpoint: str,- headers: dict[str, str],- json_body: Mapping[str, object] | None = None,- ) -> requests.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,- url: str,- *,- endpoint: str,- headers: dict[str, str],- json_body: Mapping[str, object],- ) -> requests.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 ---@property@@ -356,13 +282,9 @@ class GitHubIntegrationBase:hook is called *before* ``save()`` so it can mutate extra fields thatwill be included in a single write."""- endpoint = "/app/installations/{installation_id}/access_tokens"- try:- response = self.client_request(f"installations/{self.github_installation_id}/access_tokens", method="POST")- except requests.RequestException:- self._record_github_api_exception("POST", endpoint)- raise- self._record_github_api_response(response, "POST", endpoint)+ # client_request records the call via the egress transport — no manual recording here,+ # or every refresh would count twice.+ response = self.client_request(f"installations/{self.github_installation_id}/access_tokens", method="POST")try:data = response.json()except ValueError:@@ -431,42 +353,12 @@ class GitHubIntegrationBase:params: dict[str, str | int] | None = None,timeout: int = 10,) -> requests.Response | None:- """GET with installation token; refreshes on expiry or 401."""+ """GET with installation token via :meth:`api_request`; ``None`` instead of raising, for the+ success/error-dict verbs built on top."""+ path = url.removeprefix("https://api.github.com")try:- if self.access_token_expired():- self.refresh_access_token()- except Exception:- logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)-- def fetch() -> requests.Response:- access_token = (self.integration.sensitive_config or {}).get("access_token")- return self._github_api_get(- url,- endpoint=endpoint,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },- params=params,- timeout=timeout,- )-- try:- response = fetch()- if response.status_code == 401:- try:- self.refresh_access_token()- except Exception as exc:- logger.exception(- "GitHubIntegration: token refresh after 401 failed",- integration_id=self.integration.id,- status_code=getattr(exc, "status_code", None),- )- return None- response = fetch()- return response- except Exception:+ return self.api_request("GET", path, endpoint=endpoint, params=params, timeout=timeout)+ except GitHubIntegrationError:logger.warning("GitHubIntegration: installation GET failed", url=url, exc_info=True)return None@@ -754,65 +646,31 @@ class GitHubIntegrationBase:def _gh_graphql(self, query: str, variables: dict[str, Any], *, endpoint: str, timeout: int = 10) -> dict:"""Authenticated POST to the GitHub GraphQL API. Returns the ``data`` object.- Mirrors ``_gh_api_get``'s auth lifecycle: proactive token refresh, one- retry on 401 (refresh) or transient network error, and secondary- rate-limit detection bubbled up as a retryable ``GitHubIntegrationError``.+ GraphQL queries are read-only, so a POST retry on transient failures is safe —+ hence ``retry_transient=True`` on the shared :meth:`api_request` lifecycle."""- url = "https://api.github.com/graphql"- try:- if self.access_token_expired():- self.refresh_access_token()- except Exception:- logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)-- def post() -> requests.Response:- return self._github_api_post(- url,- endpoint=endpoint,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {self.get_access_token()}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },- json_body={"query": query, "variables": variables},+ response = self.api_request(+ "POST",+ "/graphql",+ endpoint=endpoint,+ json_body={"query": query, "variables": variables},+ timeout=timeout,+ retry_transient=True,+ )+ if response.status_code != 200:+ raise GitHubIntegrationError(+ f"GitHubIntegration: _gh_graphql {response.status_code} on {endpoint}: {response.text[:300]}",+ status_code=response.status_code,)-- for attempt in range(2):- try:- response = post()- except requests.RequestException as exc:- if attempt == 0:- logger.info("GitHubIntegration: _gh_graphql retrying network error", exc_info=True)- continue- raise GitHubIntegrationError(f"GitHubIntegration: _gh_graphql network error on {endpoint}") from exc-- if response.status_code == 401 and attempt == 0:- self.refresh_access_token()- continue- if self._is_secondary_rate_limit(response):- retry_after = self._parse_retry_after_seconds(response) or 60.0- raise GitHubIntegrationError(- f"GitHubIntegration: secondary rate limit on {endpoint}",- status_code=response.status_code,- is_rate_limit=True,- retry_after_seconds=retry_after,- )- if response.status_code != 200:- raise GitHubIntegrationError(- f"GitHubIntegration: _gh_graphql {response.status_code} on {endpoint}: {response.text[:300]}",- status_code=response.status_code,- )- body = response.json()- data = body.get("data")- errors = body.get("errors")- if errors:- # GitHub can return useful partial data with field-level permission errors.- logger.warning("GitHubIntegration: GraphQL partial errors", endpoint=endpoint, errors=errors)- if not data:- raise GitHubIntegrationError(f"GitHubIntegration: GraphQL errors on {endpoint}: {errors}")- return data or {}-- raise GitHubIntegrationError(f"GitHubIntegration: _gh_graphql exhausted retries on {endpoint}")+ body = response.json()+ data = body.get("data")+ errors = body.get("errors")+ if errors:+ # GitHub can return useful partial data with field-level permission errors.+ logger.warning("GitHubIntegration: GraphQL partial errors", endpoint=endpoint, errors=errors)+ if not data:+ raise GitHubIntegrationError(f"GitHubIntegration: GraphQL errors on {endpoint}: {errors}")+ return data or {}@staticmethoddef _map_pr_state(gql_state: str | None, is_draft: bool) -> str:@@ -908,24 +766,6 @@ class GitHubIntegrationBase:page = max(1, page)per_page = max(1, min(100, per_page))- try:- if self.access_token_expired():- self.refresh_access_token()- except Exception:- logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)-- def fetch() -> requests.Response:- access_token = (self.integration.sensitive_config or {}).get("access_token")- return self._github_api_get(- f"https://api.github.com/installation/repositories?page={page}&per_page={per_page}",- endpoint="/installation/repositories",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },- )-def extract_repos(body: dict) -> list[dict]:repositories = body.get("repositories")if not isinstance(repositories, list):@@ -948,79 +788,31 @@ class GitHubIntegrationBase:and isinstance(repo.get("full_name"), str)]- def raise_repository_error(message: str, *, status_code: int | None = None, exc_info: bool = False) -> None:- logger.warning(- message,- integration_id=self.integration.id,- status_code=status_code,- exc_info=exc_info,- )- raise GitHubIntegrationError(message)-- transient_status_codes = {502, 503, 504}-- for attempt in range(2):- try:- response = fetch()- except requests.RequestException:- raise_repository_error("GitHubIntegration: list_repositories network error", exc_info=True)-- if response.status_code == 401:- try:- self.refresh_access_token()- except Exception as exc:- refresh_status = getattr(exc, "status_code", None)- logger.exception(- "GitHubIntegration: token refresh after 401 failed",- integration_id=self.integration.id,- status_code=refresh_status,- )- raise GitHubIntegrationError(- "GitHubIntegration: token refresh after 401 failed",- status_code=refresh_status,- ) from exc- try:- response = fetch()- except requests.RequestException:- raise_repository_error("GitHubIntegration: list_repositories network error on retry", exc_info=True)-- try:- body = response.json()- except Exception:- if response.status_code in transient_status_codes and attempt == 0:- logger.info(- "GitHubIntegration: list_repositories retrying transient non-JSON response",- status_code=response.status_code,- )- continue- logger.warning(- "GitHubIntegration: list_repositories non-JSON response",- integration_id=self.integration.id,- status_code=response.status_code,- )- raise GitHubIntegrationError("GitHubIntegration: list_repositories non-JSON response")-- if response.status_code == 200 and isinstance(body, dict):- page_repos = extract_repos(body)- has_more = len(page_repos) == per_page- return page_repos, has_more-- if response.status_code in transient_status_codes and attempt == 0:- logger.info(- "GitHubIntegration: list_repositories retrying transient error",- status_code=response.status_code,- error=body if isinstance(body, dict) else None,- )- continue-+ response = self.api_request(+ "GET",+ f"/installation/repositories?page={page}&per_page={per_page}",+ endpoint="/installation/repositories",+ )+ try:+ body = response.json()+ except Exception:logger.warning(- "GitHubIntegration: failed to list repositories",+ "GitHubIntegration: list_repositories non-JSON response",integration_id=self.integration.id,status_code=response.status_code,- error=body if isinstance(body, dict) else None,)- raise GitHubIntegrationError("GitHubIntegration: failed to list repositories")- raise GitHubIntegrationError("GitHubIntegration: failed to list repositories after retries")+ raise GitHubIntegrationError("GitHubIntegration: list_repositories non-JSON response")+ if response.status_code == 200 and isinstance(body, dict):+ page_repos = extract_repos(body)+ has_more = len(page_repos) == per_page+ return page_repos, has_more+ logger.warning(+ "GitHubIntegration: failed to list repositories",+ integration_id=self.integration.id,+ status_code=response.status_code,+ error=body if isinstance(body, dict) else None,+ )+ raise GitHubIntegrationError("GitHubIntegration: failed to list repositories")def list_all_repositories(self) -> list[dict]:"""Fetch all accessible repositories, paginating through GitHub's API."""@@ -1047,23 +839,11 @@ class GitHubIntegrationBase:"""GITHUB_PER_PAGE = 100- try:- if self.access_token_expired():- self.refresh_access_token()- except Exception:- logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)-def fetch(page: int) -> requests.Response:- access_token = (self.integration.sensitive_config or {}).get("access_token")- return self._github_api_get(- f"https://api.github.com/repos/{repo}/branches?per_page={GITHUB_PER_PAGE}&page={page}",+ return self.api_request(+ "GET",+ f"/repos/{repo}/branches?per_page={GITHUB_PER_PAGE}&page={page}",endpoint="/repos/{owner}/{repo}/branches",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },- timeout=10,)def extract_names(data: list) -> list[str]:@@ -1076,30 +856,14 @@ class GitHubIntegrationBase:skip = offset % GITHUB_PER_PAGEneeded = skip + limit- # Fetch the first required page (with 401-retry logic).+ # Fetch the first required page.current_page = first_pagetry:response = fetch(current_page)- except requests.RequestException:- logger.warning("GitHubIntegration: list_branches network error", repo=repo, exc_info=True)+ except GitHubIntegrationError:+ logger.warning("GitHubIntegration: list_branches request failed", repo=repo, exc_info=True)return [], False- if response.status_code == 401:- try:- self.refresh_access_token()- except Exception as exc:- logger.exception(- "GitHubIntegration: token refresh after 401 failed",- integration_id=self.integration.id,- status_code=getattr(exc, "status_code", None),- )- return [], False- try:- response = fetch(current_page)- except requests.RequestException:- logger.warning("GitHubIntegration: list_branches network error on retry", repo=repo, exc_info=True)- return [], False-if response.status_code != 200:logger.warning("GitHubIntegration: failed to list branches",@@ -1128,7 +892,7 @@ class GitHubIntegrationBase:current_page += 1try:response = fetch(current_page)- except requests.RequestException:+ except GitHubIntegrationError:breakif response.status_code != 200:logger.warning(@@ -1173,32 +937,12 @@ class GitHubIntegrationBase:Returns the full repository name in format 'org/repo', or None if no repos available."""try:- if self.access_token_expired():- self.refresh_access_token()- except Exception:- logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)-- def fetch(page: int = 1) -> requests.Response:- access_token = (self.integration.sensitive_config or {}).get("access_token")- return self._github_api_get(- f"https://api.github.com/installation/repositories?page={page}&per_page=100",- endpoint="/installation/repositories",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },+ response = self.api_request(+ "GET", "/installation/repositories?page=1&per_page=100", endpoint="/installation/repositories")-- response = fetch()-- if response.status_code == 401:- try:- self.refresh_access_token()- except Exception:- logger.warning("GitHubIntegration: token refresh after 401 failed", exc_info=True)- else:- response = fetch()+ except GitHubIntegrationError:+ logger.warning("GitHubIntegration: get_top_starred_repository request failed", exc_info=True)+ return Nonetry:body = response.json()@@ -1232,20 +976,7 @@ class GitHubIntegrationBase:if isinstance(cached, str):return cached- access_token = (self.integration.sensitive_config or {}).get("access_token")- if not access_token:- raise ValueError("GitHub access token not configured")-- response = self._github_api_get(- f"https://api.github.com/repos/{repo_path}",- endpoint="/repos/{owner}/{repo}",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },- timeout=10,- )+ response = self.api_request("GET", f"/repos/{repo_path}", endpoint="/repos/{owner}/{repo}")if response.status_code == 200:repo_data = response.json()@@ -1466,88 +1197,84 @@ class GitHubIntegrationBase:return result, default_branch, has_moredef get_access_token(self) -> str:- """Return a valid installation access token, refreshing it if expired."""+ """Return a valid installation access token, refreshing it past the half-life threshold."""if self.access_token_expired():- self.refresh_access_token()+ try:+ self.refresh_access_token()+ except Exception:+ # The refresh threshold is the token's half-life, so the stored token is typically+ # still valid — use it rather than failing the request on a transient App-endpoint+ # error; a genuinely dead token gets the 401 refresh-retry as the backstop.+ logger.warning("GitHubIntegration: proactive token refresh failed, using stored token", exc_info=True)token = (self.integration.sensitive_config or {}).get("access_token")if not token:raise GitHubIntegrationError("Access token unavailable after refresh")return token- @staticmethod- def _is_secondary_rate_limit(response: requests.Response) -> bool:- """GitHub signals secondary rate limits via 429, or 403 + ``Retry-After`` /- ``X-RateLimit-Remaining: 0``, or 403 with a body marker (no headers)."""- if response.status_code == 429:- return True- if response.status_code != 403:- return False- if response.headers.get("Retry-After"):- return True- if response.headers.get("X-RateLimit-Remaining") == "0":- return True- # Some 403s carry the secondary-limit signal only in the body.- body = (response.text or "").lower()- return "secondary rate limit" in body or "abuse detection" in body+ def api_request(+ self,+ method: str,+ path: str,+ *,+ endpoint: str | None = None,+ params: dict[str, str | int] | None = None,+ json_body: Mapping[str, object] | None = None,+ headers: dict[str, str] | None = None,+ timeout: int = 10,+ retry_transient: bool | None = None,+ ) -> requests.Response:+ """Authenticated request against ``https://api.github.com`` returning the raw response.- @staticmethod- def _parse_retry_after_seconds(response: requests.Response) -> float | None:- header = response.headers.get("Retry-After")- if header:- try:- return max(0.0, float(header))- except ValueError:- return None- reset = response.headers.get("X-RateLimit-Reset")- if reset:- try:- return max(0.0, float(reset) - time.time())- except ValueError:- return None- return None+ Owns the shared token lifecycle — proactive refresh, one refresh-retry on 401, and one retry+ on a transient network error or 5xx where a repeat is safe (``retry_transient`` defaults to+ GET only; read-only POSTs like GraphQL opt in). Raises :class:`GitHubRateLimitError` when+ GitHub rate-limits the call; every other response is returned as-is for the caller's+ status-driven handling. ``_gh_api_get`` layers JSON parsing and non-2xx raising on top for+ callers that want dict-or-raise semantics.- def _gh_api_get(self, path: str, *, endpoint: str, timeout: int = 10) -> dict:- """Authenticated GET against ``https://api.github.com`` returning parsed JSON."""- # 1. Validate path + assemble URL.+ ``endpoint`` is the normalized label for egress telemetry; leave it ``None`` to let the+ recorder template the raw URL. Attribution uses ``self.source``.+ """if not path.startswith("/"):- raise ValueError(f"_gh_api_get path must start with '/', got {path!r}")+ raise ValueError(f"api_request path must start with '/', got {path!r}")url = f"https://api.github.com{path}"transient_status_codes = {502, 503, 504}- # 2. Proactively refresh expiring tokens (failure here is non-fatal — fetch will retry on 401).+ if retry_transient is None:+ retry_transient = method.upper() == "GET"+ # Proactively refresh expiring tokens (failure here is non-fatal — the loop retries on 401).try:if self.access_token_expired():self.refresh_access_token()except Exception:logger.warning("GitHubIntegration: token refresh pre-check failed", exc_info=True)- def fetch() -> requests.Response:- return self._github_api_get(- url,- endpoint=endpoint,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {self.get_access_token()}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },- timeout=timeout,- )-- # 3. Try up to twice — second attempt covers token refresh after 401 or one transient 5xx.- last_error_message = "GitHubIntegration: _gh_api_get exhausted retries"for attempt in range(2):- # Network call (one retry on connection-level failure).+ # Outside the try: a failing token refresh must fail fast, not be retried as a+ # transient network error.+ token = self.get_access_token()try:- response = fetch()+ response = github_request(+ method,+ url,+ source=self.source,+ # Token last: a caller-supplied Authorization must not bypass the managed lifecycle.+ headers={**(headers or {}), "Authorization": f"Bearer {token}"},+ installation_id=self.github_installation_id,+ endpoint=endpoint,+ params=params,+ json=json_body,+ timeout=timeout,+ )except requests.RequestException as exc:- if attempt == 0:+ if retry_transient and attempt == 0:logger.info(- "GitHubIntegration: _gh_api_get retrying network error",+ "GitHubIntegration: api_request retrying network error",path=path,exc_info=True,)continue- raise GitHubIntegrationError(f"GitHubIntegration: _gh_api_get network error on {path}") from exc- # Auth failure → refresh token and retry once.+ raise GitHubIntegrationError(f"GitHubIntegration: api_request network error on {path}") from exc+ # Auth failure → refresh token and retry once (safe for any method: 401 means nothing ran).if response.status_code == 401 and attempt == 0:try:self.refresh_access_token()@@ -1556,50 +1283,47 @@ class GitHubIntegrationBase:f"GitHubIntegration: token refresh after 401 failed on {path}") from exccontinue- # Secondary rate limit → bubble up with retry hint (no in-method retry).- if self._is_secondary_rate_limit(response):- # When headers don't give us a delay (body-only signal), GitHub recommends ≥60s.- retry_after = self._parse_retry_after_seconds(response) or 60.0- raise GitHubIntegrationError(- f"GitHubIntegration: secondary rate limit on {path}",- status_code=response.status_code,- is_rate_limit=True,- retry_after_seconds=retry_after,- )- # Transient 5xx → retry once.- if response.status_code in transient_status_codes and attempt == 0:+ # Rate limit → bubble up with retry hints (no in-method retry; the caller owns backoff).+ raise_if_github_rate_limited(response)+ if retry_transient and response.status_code in transient_status_codes and attempt == 0:logger.info(- "GitHubIntegration: _gh_api_get retrying transient error",+ "GitHubIntegration: api_request retrying transient error",path=path,status_code=response.status_code,)continue- # Any remaining non-2xx is terminal.- if response.status_code < 200 or response.status_code >= 300:- logger.warning(- "GitHubIntegration: _gh_api_get non-2xx response",- path=path,- status_code=response.status_code,- )- raise GitHubIntegrationError(- f"GitHubIntegration: _gh_api_get failed on {path}",- status_code=response.status_code,- )- # 4. Parse + shape-check the response body.- try:- body = response.json()- except Exception as exc:- raise GitHubIntegrationError(- f"GitHubIntegration: _gh_api_get non-JSON response on {path}",- status_code=response.status_code,- ) from exc- if not isinstance(body, dict):- raise GitHubIntegrationError(- f"GitHubIntegration: _gh_api_get unexpected payload on {path}",- status_code=response.status_code,- )- return body- raise GitHubIntegrationError(last_error_message)+ return response+ raise GitHubIntegrationError(f"GitHubIntegration: api_request exhausted retries on {path}")++ def _gh_api_get(self, path: str, *, endpoint: str, timeout: int = 10) -> dict:+ """Authenticated GET against ``https://api.github.com`` returning parsed JSON.++ Dict-or-raise sugar over :meth:`api_request`: any non-2xx (or non-dict body) becomes a+ :class:`GitHubIntegrationError`; rate limits propagate as :class:`GitHubRateLimitError`."""+ response = self.api_request("GET", path, endpoint=endpoint, timeout=timeout)+ if response.status_code < 200 or response.status_code >= 300:+ logger.warning(+ "GitHubIntegration: _gh_api_get non-2xx response",+ path=path,+ status_code=response.status_code,+ )+ raise GitHubIntegrationError(+ f"GitHubIntegration: _gh_api_get failed on {path}",+ status_code=response.status_code,+ )+ try:+ body = response.json()+ except Exception as exc:+ raise GitHubIntegrationError(+ f"GitHubIntegration: _gh_api_get non-JSON response on {path}",+ status_code=response.status_code,+ ) from exc+ if not isinstance(body, dict):+ raise GitHubIntegrationError(+ f"GitHubIntegration: _gh_api_get unexpected payload on {path}",+ status_code=response.status_code,+ )+ return body@database_sync_to_async_pooldef list_all_cached_repositories_async(self, max_repos: int | None = None) -> list[dict]:diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex ff911a90505e..5c5219619807 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -39,7 +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_VERSION+from posthog.egress.github.transport import github_requestfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationError@@ -2529,13 +2529,12 @@ class GitHubIntegration(GitHubIntegrationBase):)return None- user_response = requests.get(+ # Identity-blind: a fresh user OAuth token with no installation budget behind it.+ user_response = github_request(+ "GET","https://api.github.com/user",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": "2022-11-28",- },+ source="integration",+ headers={"Authorization": f"Bearer {access_token}"},timeout=10,)if user_response.status_code != 200:@@ -2559,7 +2558,9 @@ class GitHubIntegration(GitHubIntegrationBase):)@classmethod- def first_for_team_repository(cls, team_id: int, repository: str) -> "GitHubIntegration | None":+ def first_for_team_repository(+ cls, team_id: int, repository: str, *, source: str | None = None+ ) -> "GitHubIntegration | None":"""First GitHub integration for the team whose installation can access ``repository`` (``owner/name``).``repository`` reaches us from team-writable content (e.g. artefact payloads), and the access@@ -2570,15 +2571,17 @@ class GitHubIntegration(GitHubIntegrationBase):if not _is_safe_github_repo_path(repository):return Nonefor integration in Integration.objects.filter(team_id=team_id, kind="github").order_by("id"):- github = cls(integration)+ github = cls(integration, source=source)if github.installation_can_access_repository(repository):return githubreturn None- def __init__(self, integration: Integration) -> None:+ def __init__(self, integration: Integration, *, source: str | None = None) -> None:if integration.kind != "github":raise Exception("GitHubIntegration init called with Integration with wrong 'kind'")self.integration = integration+ if source is not None:+ self.source = sourcedef _on_token_refresh_failed(self, response: requests.Response) -> None:logger.warning(f"Failed to refresh token for {self}", response=response.text)@@ -2598,25 +2601,28 @@ class GitHubIntegration(GitHubIntegrationBase):) -> tuple[list[dict], bool]:return self.list_cached_repositories(search=search, limit=limit, offset=offset)- def create_issue(self, config: dict[str, str]):+ def create_issue(self, config: dict[str, Any]):title: str = config.pop("title")body: str = config.pop("body")repository: str = config.pop("repository")+ labels = config.pop("labels", None)- org = self.organization()- access_token = self.integration.sensitive_config["access_token"]+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"+ json_body: dict[str, Any] = {"title": title, "body": body}+ if labels:+ json_body["labels"] = labels- response = self._github_api_post(- f"https://api.github.com/repos/{org}/{repository}/issues",+ response = self.api_request(+ "POST",+ f"/repos/{repo_path}/issues",endpoint="/repos/{owner}/{repo}/issues",- json_body={"title": title, "body": body},- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },+ json_body=json_body,)-+ if response.status_code != 201:+ raise GitHubIntegrationError(+ f"GitHubIntegration: failed to create issue in {repo_path}: {response.text[:300]}",+ status_code=response.status_code,+ )issue = response.json()return {"number": issue["number"], "repository": repository}@@ -2624,21 +2630,16 @@ class GitHubIntegration(GitHubIntegrationBase):def create_branch(self, repository: str, branch_name: str, base_branch: str | None = None) -> dict[str, Any]:"""Create a new branch from a base branch."""org = self.organization()- access_token = self.integration.sensitive_config["access_token"]# Get the SHA of the base branch (default to repository's default branch)if not base_branch:base_branch = self.get_default_branch(repository)# Get the SHA of the base branch- ref_response = self._github_api_get(- f"https://api.github.com/repos/{org}/{repository}/git/ref/heads/{base_branch}",+ ref_response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/git/ref/heads/{base_branch}",endpoint="/repos/{owner}/{repo}/git/ref/heads/{branch}",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },)if ref_response.status_code != 200:@@ -2650,18 +2651,14 @@ class GitHubIntegration(GitHubIntegrationBase):base_sha = ref_response.json()["object"]["sha"]# Create the new branch- response = self._github_api_post(- f"https://api.github.com/repos/{org}/{repository}/git/refs",+ response = self.api_request(+ "POST",+ f"/repos/{org}/{repository}/git/refs",endpoint="/repos/{owner}/{repo}/git/refs",json_body={"ref": f"refs/heads/{branch_name}","sha": base_sha,},- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },)if response.status_code == 201:@@ -2716,20 +2713,15 @@ class GitHubIntegration(GitHubIntegrationBase):# validated values, so the compare path can't be steered off-endpoint.base_ref = base_sha or base_branchtarget_ref = target_sha or target_branch- access_token = self.integration.sensitive_config["access_token"]try:- response = self._github_api_get(- f"https://api.github.com/repos/{repo_path}/compare/{base_ref}...{target_ref}",+ response = self.api_request(+ "GET",+ f"/repos/{repo_path}/compare/{base_ref}...{target_ref}",endpoint="/repos/{owner}/{repo}/compare/{basehead}",- headers={- "Accept": "application/vnd.github.diff",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },- timeout=10,+ headers={"Accept": "application/vnd.github.diff"},)- except requests.RequestException:+ except GitHubIntegrationError:# Don't let a slow/unreachable GitHub hang a worker or 500 the caller.return {"success": False, "error": "Could not reach GitHub.", "status_code": 502}if response.status_code != 200:@@ -2748,19 +2740,14 @@ class GitHubIntegration(GitHubIntegrationBase):) -> dict[str, Any]:"""Create or update a file in the repository."""org = self.organization()- access_token = self.integration.sensitive_config["access_token"]# If no SHA provided, try to get existing file's SHAif not sha:- get_response = self._github_api_get(- f"https://api.github.com/repos/{org}/{repository}/contents/{file_path}",+ get_response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/contents/{file_path}",endpoint="/repos/{owner}/{repo}/contents/{path}",params={"ref": branch},- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },)if get_response.status_code == 200:sha = get_response.json()["sha"]@@ -2776,15 +2763,11 @@ class GitHubIntegration(GitHubIntegrationBase):if sha:data["sha"] = sha- response = self._github_api_put(- f"https://api.github.com/repos/{org}/{repository}/contents/{file_path}",+ response = self.api_request(+ "PUT",+ f"/repos/{org}/{repository}/contents/{file_path}",endpoint="/repos/{owner}/{repo}/contents/{path}",json_body=data,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },)if response.status_code in [200, 201]:@@ -2810,18 +2793,13 @@ class GitHubIntegration(GitHubIntegrationBase):pass it straight to ``update_file`` for a conflict-safe write. Counterpart to``update_file``, kept here so URL and token handling stay inside the client."""- org = self.organization()- access_token = self.integration.sensitive_config["access_token"]+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"- response = self._github_api_get(- f"https://api.github.com/repos/{org}/{repository}/contents/{file_path}",+ response = self.api_request(+ "GET",+ f"/repos/{repo_path}/contents/{file_path}",endpoint="/repos/{owner}/{repo}/contents/{path}",params={"ref": ref} if ref else None,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },)if response.status_code == 404:return None@@ -2838,13 +2816,13 @@ class GitHubIntegration(GitHubIntegrationBase):) -> dict[str, Any]:"""Create a pull request."""org = self.organization()- access_token = self.integration.sensitive_config["access_token"]if not base_branch:base_branch = self.get_default_branch(repository)- response = self._github_api_post(- f"https://api.github.com/repos/{org}/{repository}/pulls",+ response = self.api_request(+ "POST",+ f"/repos/{org}/{repository}/pulls",endpoint="/repos/{owner}/{repo}/pulls",json_body={"title": title,@@ -2852,11 +2830,6 @@ class GitHubIntegration(GitHubIntegrationBase):"head": head_branch,"base": base_branch,},- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },)if response.status_code == 201:@@ -2878,16 +2851,11 @@ class GitHubIntegration(GitHubIntegrationBase):def get_branch_info(self, repository: str, branch_name: str) -> dict[str, Any]:"""Get information about a specific branch."""org = self.organization()- access_token = self.integration.sensitive_config["access_token"]- response = self._github_api_get(- f"https://api.github.com/repos/{org}/{repository}/branches/{branch_name}",+ response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/branches/{branch_name}",endpoint="/repos/{owner}/{repo}/branches/{branch}",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },)if response.status_code == 200:@@ -2915,18 +2883,13 @@ class GitHubIntegration(GitHubIntegrationBase):def list_pull_requests(self, repository: str, state: str = "open") -> dict[str, Any]:"""List pull requests for a repository."""org = self.organization()- access_token = self.integration.sensitive_config["access_token"]params: dict[str, str | int] = {"state": state, "per_page": 100}- response = self._github_api_get(- f"https://api.github.com/repos/{org}/{repository}/pulls",+ response = self.api_request(+ "GET",+ f"/repos/{org}/{repository}/pulls",endpoint="/repos/{owner}/{repo}/pulls",params=params,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },)if response.status_code == 200:diff --git a/posthog/models/integration_repository_cache.py b/posthog/models/integration_repository_cache.pyindex a2454aaa6dd0..8c3c7ccb5338 100644--- a/posthog/models/integration_repository_cache.py+++ b/posthog/models/integration_repository_cache.py@@ -28,6 +28,7 @@ from django.utils import timezoneimport structlogfrom posthog import redis as posthog_redis+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.helpers.async_concurrency import run_parallel_with_backofffrom posthog.models.github_integration_base import GitHubIntegrationBasefrom posthog.models.integration import GitHubIntegration, GitHubIntegrationError, Integration@@ -218,7 +219,8 @@ class GitHubRepositoryFullCache:readme_text = base64.b64decode(encoded).decode("utf-8", errors="replace")except GitHubIntegrationError as exc:if getattr(exc, "status_code", None) != 404:- # Rate-limit and other retryable errors propagate so run_parallel_with_backoff can retry.+ # Non-404 failures propagate; rate limits bypass this catch entirely (they raise+ # GitHubRateLimitError) so run_parallel_with_backoff can retry them.raise# Recursive file tree → newline-separated blob paths for ARRAY JOIN grep.tree_data = self.github._gh_api_get(@@ -380,8 +382,8 @@ class GitHubRepositoryFullCache:results = await run_parallel_with_backoff([make_fn(name) for name in valid_full_names],concurrency=concurrency,- is_retryable=lambda exc: isinstance(exc, GitHubIntegrationError) and exc.is_rate_limit,- get_retry_delay=lambda exc: getattr(exc, "retry_after_seconds", None),+ is_retryable=lambda exc: isinstance(exc, GitHubRateLimitError),+ get_retry_delay=lambda exc: getattr(exc, "retry_after", None),)# 4. Single summary line — distinguishes "warm cache, all hits" from "did real work".errors = sum(1 for r in results if isinstance(r, BaseException))diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex 4f2f675bd105..8056a50b0a44 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -949,7 +949,7 @@ class TestGitHubIntegrationModel(BaseTest):integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})github = GitHubIntegration(integration)mock_response = MagicMock(status_code=200, text="diff --git a b")- with patch.object(github, "_github_api_get", return_value=mock_response) as mock_get:+ with patch.object(github, "api_request", return_value=mock_response) as mock_get:result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")assert result == {"success": True,@@ -957,13 +957,13 @@ class TestGitHubIntegrationModel(BaseTest):"truncated": False,}mock_get.assert_called_once()- assert "/compare/master...feature/foo" in mock_get.call_args.args[0]+ assert "/compare/master...feature/foo" in mock_get.call_args.args[1]def test_get_diff_pins_to_shas_when_given(self):integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})github = GitHubIntegration(integration)mock_response = MagicMock(status_code=200, text="diff --git a b")- with patch.object(github, "_github_api_get", return_value=mock_response) as mock_get:+ with patch.object(github, "api_request", return_value=mock_response) as mock_get:result = github.get_diff("PostHog/posthog",target_branch="feature/foo",@@ -972,20 +972,20 @@ class TestGitHubIntegrationModel(BaseTest):base_sha="def456a",)assert result["success"] is True- assert "/compare/def456a...abc123f" in mock_get.call_args.args[0]+ assert "/compare/def456a...abc123f" in mock_get.call_args.args[1]def test_get_diff_maps_upstream_error(self):integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})github = GitHubIntegration(integration)mock_response = MagicMock(status_code=404, text="Not Found")- with patch.object(github, "_github_api_get", return_value=mock_response):+ with patch.object(github, "api_request", return_value=mock_response):result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")assert result == {"success": False, "error": "Not Found", "status_code": 404}def test_get_diff_handles_request_exception(self):integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})github = GitHubIntegration(integration)- with patch.object(github, "_github_api_get", side_effect=requests.ConnectionError("boom")):+ with patch.object(github, "api_request", side_effect=GitHubIntegrationError("network error")):result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")assert result["success"] is Falseassert result["status_code"] == 502@@ -1026,7 +1026,7 @@ class TestGitHubIntegrationModel(BaseTest):github = GitHubIntegration(integration)oversized = "x" * (_MAX_DIFF_CHARS + 100)mock_response = MagicMock(status_code=200, text=oversized)- with patch.object(github, "_github_api_get", return_value=mock_response):+ with patch.object(github, "api_request", return_value=mock_response):result = github.get_diff("PostHog/posthog", target_branch="feature/foo", base_branch="master")assert result["success"] is Trueassert result["truncated"] is True@@ -1050,7 +1050,7 @@ class TestGitHubIntegrationModel(BaseTest):github = GitHubIntegration(integration)kwargs: dict = {"repository": "PostHog/posthog", "target_branch": "feature/foo", "base_branch": "master"}kwargs.update(overrides)- with patch.object(github, "_github_api_get") as mock_get:+ with patch.object(github, "api_request") as mock_get:result = github.get_diff(**kwargs)assert result["success"] is Falseassert result["status_code"] == 400@@ -1060,7 +1060,7 @@ class TestGitHubIntegrationModel(BaseTest):integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})github = GitHubIntegration(integration)mock_response = MagicMock(status_code=200, text="diff --git a b")- with patch.object(github, "_github_api_get", return_value=mock_response) as mock_get:+ with patch.object(github, "api_request", return_value=mock_response) as mock_get:result = github.get_diff("PostHog/posthog", target_branch="feature/nested/branch", base_branch="release/v1.2")@@ -1154,11 +1154,12 @@ class TestGitHubIntegrationModel(BaseTest):}previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0- GitHubIntegration(integration)._github_api_get(- "https://api.github.com/repos/PostHog/posthog",- endpoint="/repos/{owner}/{repo}",- headers={"Accept": "application/vnd.github+json"},- )+ with patch.object(GitHubIntegration, "access_token_expired", return_value=False):+ GitHubIntegration(integration).api_request(+ "GET",+ "/repos/PostHog/posthog",+ endpoint="/repos/{owner}/{repo}",+ )assert REGISTRY.get_sample_value("github_integration_api_requests_total", labels) == previous_count + 1assert (@@ -1200,36 +1201,18 @@ class TestGitHubIntegrationModel(BaseTest):}previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0- with pytest.raises(requests.RequestException):- GitHubIntegration(integration)._github_api_get(- "https://api.github.com/repos/PostHog/posthog",+ with (+ patch.object(GitHubIntegration, "access_token_expired", return_value=False),+ pytest.raises(GitHubIntegrationError),+ ):+ GitHubIntegration(integration).api_request(+ "GET",+ "/repos/PostHog/posthog",endpoint="/repos/{owner}/{repo}",- headers={"Accept": "application/vnd.github+json"},)- assert REGISTRY.get_sample_value("github_integration_api_requests_total", labels) == previous_count + 1-- @patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")- def test_github_refresh_access_token_metrics_include_request_exceptions(self, mock_client_request):- integration = self.create_integration(- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},- {"access_token": "ACCESS_TOKEN"},- )- mock_client_request.side_effect = requests.RequestException("network failure")-- labels = {- "installation_id": integration.integration_id,- "method": "POST",- "endpoint": "/app/installations/{installation_id}/access_tokens",- "status_code": "exception",- "source": "integration",- }- previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0-- with pytest.raises(requests.RequestException):- GitHubIntegration(integration).refresh_access_token()-- assert REGISTRY.get_sample_value("github_integration_api_requests_total", labels) == previous_count + 1+ # GET retries the network error once; both attempts record an exception sample.+ assert REGISTRY.get_sample_value("github_integration_api_requests_total", labels) == previous_count + 2@patch("posthog.models.github_integration_base.GitHubIntegrationBase.client_request")def test_github_integration_refresh_token(self, mock_client_request):@@ -1926,8 +1909,7 @@ class TestGitHubIntegrationModel(BaseTest):# 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+ assert err.retry_after == 45# --- get_access_token ---@@ -2014,15 +1996,14 @@ class TestGitHubIntegrationGhApiGet(BaseTest):def test_raises_rate_limit_error_on_secondary_limit(self, _mock_expired, mock_get):resp = MagicMock()resp.status_code = 403- resp.headers = {"Retry-After": "5"}+ resp.headers = {"retry-after": "5"}resp.json.return_value = {"message": "secondary rate limit"}mock_get.return_value = respintegration = self._create_integration()- with pytest.raises(GitHubIntegrationError) as excinfo:+ with pytest.raises(GitHubRateLimitError) as excinfo:GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")- assert excinfo.value.is_rate_limit is True- assert excinfo.value.retry_after_seconds == 5.0+ assert excinfo.value.retry_after == 5@patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.access_token_expired", return_value=False)@@ -2035,10 +2016,9 @@ class TestGitHubIntegrationGhApiGet(BaseTest):mock_get.return_value = respintegration = self._create_integration()- with pytest.raises(GitHubIntegrationError) as excinfo:+ with pytest.raises(GitHubRateLimitError) as excinfo:GitHubIntegration(integration)._gh_api_get("/repos/PostHog/posthog", endpoint="/repos/{owner}/{repo}")- assert excinfo.value.is_rate_limit is True- assert excinfo.value.retry_after_seconds == 60.0+ assert excinfo.value.retry_after == 60@patch("posthog.egress.transport.transport.requests.request")@patch("posthog.models.integration.GitHubIntegration.refresh_access_token")diff --git a/posthog/models/test/test_integration_repository_cache.py b/posthog/models/test/test_integration_repository_cache.pyindex a0d4c2345f8e..da15ceacd611 100644--- a/posthog/models/test/test_integration_repository_cache.py+++ b/posthog/models/test/test_integration_repository_cache.py@@ -11,6 +11,7 @@ from django.utils import timezonefrom asgiref.sync import async_to_sync+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.integration import GitHubIntegration, GitHubIntegrationError, Integrationfrom posthog.models.integration_repository_cache import (GITHUB_REPOSITORY_FULL_CACHE_TTL_SECONDS,@@ -228,12 +229,7 @@ class TestGitHubRepositoryFullCache(BaseTest):def _side_effect(self_, path, *, endpoint=None, timeout=10):if path.startswith("/repos/posthog/posthog/readme"):- raise GitHubIntegrationError(- "secondary rate limit on /readme",- status_code=403,- is_rate_limit=True,- retry_after_seconds=60.0,- )+ raise GitHubRateLimitError("secondary rate limit on /readme", retry_after=60)return responses[path]with patch(@@ -241,11 +237,10 @@ class TestGitHubRepositoryFullCache(BaseTest):autospec=True,side_effect=_side_effect,):- with pytest.raises(GitHubIntegrationError) as excinfo:+ with pytest.raises(GitHubRateLimitError) as excinfo:async_to_sync(self._cache_for(integration).sync_full_cache_entry_async)("posthog/posthog")- assert excinfo.value.is_rate_limit is True- assert excinfo.value.retry_after_seconds == 60.0+ assert excinfo.value.retry_after == 60assert not IntegrationRepositoryCacheEntry.objects.filter(integration=integration).exists()def test_sync_full_cache_entry_propagates_non_404_readme_errors(self):diff --git a/posthog/models/user_integration.py b/posthog/models/user_integration.pyindex f01c0437d755..59e467c8d1b2 100644--- a/posthog/models/user_integration.py+++ b/posthog/models/user_integration.py@@ -132,10 +132,12 @@ class UserGitHubIntegration(GitHubIntegrationBase):integration: UserIntegration- def __init__(self, integration: UserIntegration) -> None:+ def __init__(self, integration: UserIntegration, *, source: str | None = None) -> None:if integration.kind != "github":raise Exception("UserGitHubIntegration initialized with non-github integration")self.integration = integration+ if source is not None:+ self.source = source# --- Token refresh hooks ---diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex 61fd39b79cf7..deeec084a050 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -19,9 +19,10 @@ import requestsimport structlogfrom celery import shared_task-from posthog.egress.github.transport import github_request+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.comment import Comment as CommentModel+from posthog.models.github_integration_base import GitHubIntegrationErrorfrom posthog.models.team import Teamfrom posthog.models.uploaded_media import UploadedMediafrom posthog.scoping_audit import skip_team_scope_audit@@ -1766,7 +1767,12 @@ def post_reply_to_github(logger.warning("github_reply_missing_issue_info", ticket_id=ticket_id)return- github = GitHubIntegration.first_for_team_repository(team_id, ticket.github_repo)+ try:+ github = GitHubIntegration.first_for_team_repository(team_id, ticket.github_repo, source="conversations")+ except GitHubRateLimitError as e:+ # The access probe hit GitHub's limit — retry the reply later rather than dropping it.+ logger.warning("github_reply_rate_limited", ticket_id=ticket_id)+ raise cast(Any, post_reply_to_github).retry(exc=e, countdown=min(e.retry_after or 60, 600))if not github:logger.warning("github_reply_no_integration", team_id=team_id, repo=ticket.github_repo)return@@ -1779,17 +1785,11 @@ def post_reply_to_github(if author_name:reply_text = f"**{author_name}** replied:\n\n{reply_text}"- access_token = github.get_access_token()- url = f"https://api.github.com/repos/{ticket.github_repo}/issues/{ticket.github_issue_number}/comments"-try:- resp = github_request(+ resp = github.api_request("POST",- url,- source="conversations",- headers={"Authorization": f"Bearer {access_token}"},- installation_id=github.github_installation_id,- json={"body": reply_text},+ f"/repos/{ticket.github_repo}/issues/{ticket.github_issue_number}/comments",+ json_body={"body": reply_text},timeout=15,)if resp.status_code not in (200, 201):@@ -1814,7 +1814,10 @@ def post_reply_to_github()logger.info("github_reply_posted", ticket_id=ticket_id, repo=ticket.github_repo)- except requests.RequestException as e:+ except GitHubRateLimitError as e:+ logger.warning("github_reply_rate_limited", ticket_id=ticket_id)+ raise cast(Any, post_reply_to_github).retry(exc=e, countdown=min(e.retry_after or 60, 600))+ except (GitHubIntegrationError, requests.RequestException) as e:logger.exception("github_reply_post_error", ticket_id=ticket_id, error=str(e))raise cast(Any, post_reply_to_github).retry(exc=e)@@ -1844,30 +1847,17 @@ def create_github_issue(logger.warning("github_create_issue_integration_not_found", integration_id=integration_id)return None- github = GitHubIntegration(integration)- access_token = github.get_access_token()-- json_body: dict[str, Any] = {"title": title, "body": body}- if labels:- json_body["labels"] = labels+ github = GitHubIntegration(integration, source="conversations")- url = f"https://api.github.com/repos/{repo}/issues"try:- resp = github_request(- "POST",- url,- source="conversations",- headers={"Authorization": f"Bearer {access_token}"},- installation_id=github.github_installation_id,- json=json_body,- timeout=15,- )- resp.raise_for_status()- except requests.RequestException as e:+ issue_data = github.create_issue({"title": title, "body": body, "repository": repo, "labels": labels})+ except GitHubRateLimitError as e:+ logger.warning("github_create_issue_rate_limited", repo=repo)+ raise cast(Any, create_github_issue).retry(exc=e, countdown=min(e.retry_after or 60, 600))+ except GitHubIntegrationError as e:logger.exception("github_create_issue_failed", repo=repo, error=str(e))raise cast(Any, create_github_issue).retry(exc=e)- issue_data = resp.json()issue_number = issue_data.get("number")ticket = Ticket.objects.create_with_number(diff --git a/products/engineering_analytics/backend/logic/job_logs/activity.py b/products/engineering_analytics/backend/logic/job_logs/activity.pyindex fa8fe36a6908..2aaf80d60d7e 100644--- a/products/engineering_analytics/backend/logic/job_logs/activity.py+++ b/products/engineering_analytics/backend/logic/job_logs/activity.py@@ -67,7 +67,7 @@ async def fetch_and_emit_job_log_activity(inputs: FetchJobLogInputs) -> dict[strgithub_token, installation_id, log_ingest_token = await database_sync_to_async(_resolve_credentials, thread_sensitive=False)(inputs.team_id, inputs.integration_id)- if not await acquire_github_installation(installation_id):+ if not await acquire_github_installation(installation_id, source="job_logs"):# Over budget — raise so Temporal retries with backoff instead of blocking a worker.raise ApplicationError("GitHub egress budget exhausted", type="GithubEgressBudgetExhausted")archive = await asyncio.to_thread(fetch_job_log, inputs.repo, inputs.job_id, github_token)diff --git a/products/engineering_analytics/backend/logic/job_logs/fetcher.py b/products/engineering_analytics/backend/logic/job_logs/fetcher.pyindex 3984485fae86..8de8bf6ab36a 100644--- a/products/engineering_analytics/backend/logic/job_logs/fetcher.py+++ b/products/engineering_analytics/backend/logic/job_logs/fetcher.py@@ -6,13 +6,12 @@ following the redirect is fine (no SSRF surface). Rate limits surface as ``GitHuthe Temporal retry honors the reset."""-import requests+import contextlib-from posthog.egress.github.transport import GITHUB_API_VERSION, raise_if_github_rate_limited+from posthog.egress.github.transport import github_request, raise_if_github_rate_limitedfrom 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}# A connected repo's failed job can print an arbitrarily large log; cap the bytes we pull into memory# before thinning (the thinner only caps line count, after the bytes are already decoded)._MAX_LOG_BYTES = 20 * 1024 * 1024@@ -27,11 +26,22 @@ def fetch_job_log(# value can't steer this authenticated request to a different GitHub endpoint.raise ValueError(f"Unsafe GitHub repo path: {repo!r}")url = f"{_GITHUB_API}/repos/{repo}/actions/jobs/{job_id}/logs"- headers = {**_BASE_HEADERS, "Authorization": f"Bearer {access_token}"}# Stream within the byte budget so a pathological log can't OOM the worker. Keep a bounded head# AND a rolling tail: failures surface at the end (the run summary), so a head-only cap could drop# the very lines thin_log needs if a job pads the start with noise.- with requests.get(url, headers=headers, timeout=timeout, allow_redirects=True, stream=True) as response:+ # Identity-blind on purpose: the activity already gated this call against the installation+ # budget before dispatch, so gating here again would consume the budget twice.+ with contextlib.closing(+ github_request(+ "GET",+ url,+ source="job_logs",+ headers={"Authorization": f"Bearer {access_token}"},+ timeout=timeout,+ allow_redirects=True,+ stream=True,+ )+ ) as response:raise_if_github_rate_limited(response)if response.status_code == 404:return Nonediff --git a/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py b/products/engineering_analytics/backend/logic/job_logs/test/test_activity.pyindex c9f4da6b4966..0a3e4e23cb7d 100644--- a/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py+++ b/products/engineering_analytics/backend/logic/job_logs/test/test_activity.py@@ -43,7 +43,7 @@ class _FakeEmitter:def _patch(monkeypatch, *, acquired=True, archive="l1\nl2\nl3"):- async def _acquire(_installation_id):+ async def _acquire(_installation_id, **_kwargs):return acquiredmonkeypatch.setattr(activity_module, "acquire_github_installation", _acquire)diff --git a/products/growth/dags/github_sdk_versions.py b/products/growth/dags/github_sdk_versions.pyindex 805516006be5..30fd3a854788 100644--- a/products/growth/dags/github_sdk_versions.py+++ b/products/growth/dags/github_sdk_versions.py@@ -6,11 +6,11 @@ from typing import Any, Optional, castfrom django.conf import settingsimport dagster-import requestsimport structlogfrom posthog.dags.common import JobOwnersfrom posthog.dags.common.resources import redis+from posthog.egress.github.transport import github_requestfrom posthog.exceptions_capture import capture_exceptionfrom products.growth.backend.constants import SDK_CACHE_EXPIRY, SDK_TYPES, SdkTypes, github_sdk_versions_key@@ -134,7 +134,8 @@ def fetch_releases_from_repo(repo: str, skip_cache: bool = False) -> list[Any]:url = f"https://api.github.com/repos/{repo}/releases?per_page=100&page={page}"logger.info(f"[SDK Health] Fetching releases from {url}")- response = requests.get(url, timeout=10)+ # Identity-blind, unauthenticated call — records volume telemetry, no installation budget.+ response = github_request("GET", url, source="growth", timeout=10)if not response.ok:logger.error(f"[SDK Health] Failed to fetch releases for {repo}", status_code=response.status_code)diff --git a/products/growth/dags/tests/test_github_sdk_versions.py b/products/growth/dags/tests/test_github_sdk_versions.pyindex 7e38a19f114b..d4c4833a38fe 100644--- a/products/growth/dags/tests/test_github_sdk_versions.py+++ b/products/growth/dags/tests/test_github_sdk_versions.py@@ -88,7 +88,7 @@ class TestFetchSdkDataBase:class TestFetchWebSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_web_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_js_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -102,7 +102,7 @@ class TestFetchWebSdkData(TestFetchSdkDataBase):assert result["releaseDates"]["1.298.1"] == "2025-11-26T13:26:47Z"assert mock_get.call_count == 2 # Assert that it attempted to paginate- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_web_sdk_data_request_failure(self, mock_get):response = MagicMock()response.ok = False@@ -116,7 +116,7 @@ class TestFetchWebSdkData(TestFetchSdkDataBase):class TestFetchPythonSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_python_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_python_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -132,7 +132,7 @@ class TestFetchPythonSdkData(TestFetchSdkDataBase):class TestFetchNodeSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_node_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_js_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -151,7 +151,7 @@ class TestFetchNodeSdkData(TestFetchSdkDataBase):class TestFetchReactNativeSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_react_native_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_js_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -170,7 +170,7 @@ class TestFetchReactNativeSdkData(TestFetchSdkDataBase):class TestFetchFlutterSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_flutter_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_flutter_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -189,7 +189,7 @@ class TestFetchFlutterSdkData(TestFetchSdkDataBase):class TestFetchIosSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_ios_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_ios_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -205,7 +205,7 @@ class TestFetchIosSdkData(TestFetchSdkDataBase):class TestFetchAndroidSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_android_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_android_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -221,7 +221,7 @@ class TestFetchAndroidSdkData(TestFetchSdkDataBase):class TestFetchGoSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_go_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_go_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -237,7 +237,7 @@ class TestFetchGoSdkData(TestFetchSdkDataBase):class TestFetchPhpSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_php_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_php_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -253,7 +253,7 @@ class TestFetchPhpSdkData(TestFetchSdkDataBase):class TestFetchRubySdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_ruby_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_ruby_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -269,7 +269,7 @@ class TestFetchRubySdkData(TestFetchSdkDataBase):class TestFetchElixirSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_elixir_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_elixir_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -285,7 +285,7 @@ class TestFetchElixirSdkData(TestFetchSdkDataBase):class TestFetchDotnetSdkData(TestFetchSdkDataBase):- @patch("products.growth.dags.github_sdk_versions.requests.get")+ @patch("posthog.egress.transport.transport.requests.request")def test_fetch_dotnet_sdk_data_success(self, mock_get):releases_data = self.load_releases("posthog_dotnet_releases.json")self.setup_ok_json_mock(mock_get, releases_data)@@ -321,7 +321,7 @@ class TestSupportsUnprefixedReleaseTags(TestFetchSdkDataBase):def test_supports_unprefixed_release_tags(self, fetch_fn, latest_tag, previous_tag, previous_version, latest_created_at, previous_created_at):- with patch("products.growth.dags.github_sdk_versions.requests.get") as mock_get:+ with patch("posthog.egress.transport.transport.requests.request") as mock_get:self.setup_ok_json_mock(mock_get,[diff --git a/products/signals/backend/management/commands/create_github_app.py b/products/signals/backend/management/commands/create_github_app.pyindex b4bbc0b2f8b3..64c25c2fef80 100644--- a/products/signals/backend/management/commands/create_github_app.py+++ b/products/signals/backend/management/commands/create_github_app.py@@ -41,7 +41,7 @@ from django.core.management.base import BaseCommand, CommandErrorimport jwtimport requests-from posthog.models.integration import GITHUB_API_VERSION+from posthog.egress.github.transport import github_requestGITHUB_APP_KEYS = ["GITHUB_APP_CLIENT_ID", "GITHUB_APP_CLIENT_SECRET", "GITHUB_APP_SLUG", "GITHUB_APP_PRIVATE_KEY"]DEFAULT_BASE_URL = "http://localhost:8010"@@ -286,9 +286,10 @@ class Command(BaseCommand):def _exchange_code(self, code: str) -> dict[str, Any]:self.stdout.write(" Exchanging authorization code for credentials…")try:- resp = requests.post(+ resp = github_request(+ "POST",f"https://api.github.com/app-manifests/{quote(code, safe='')}/conversions",- headers={"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": GITHUB_API_VERSION},+ source="signals",timeout=30,)except requests.RequestException as err:@@ -342,13 +343,11 @@ class Command(BaseCommand):loaded_key,algorithm="RS256",)- resp = requests.get(+ resp = github_request(+ "GET","https://api.github.com/app",- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {token}",- "X-GitHub-Api-Version": GITHUB_API_VERSION,- },+ source="signals",+ headers={"Authorization": f"Bearer {token}"},timeout=30,)except Exception as err:diff --git a/products/signals/backend/report_generation/resolve_reviewers.py b/products/signals/backend/report_generation/resolve_reviewers.pyindex ba8725bf47ca..14ae64d0b0eb 100644--- a/products/signals/backend/report_generation/resolve_reviewers.py+++ b/products/signals/backend/report_generation/resolve_reviewers.py@@ -16,6 +16,7 @@ from social_django.models import UserSocialAuthfrom posthog.schema import RelevantCommit+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.integration import GitHubIntegration, Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Team@@ -122,7 +123,12 @@ def resolve_suggested_reviewers(if not commit_hashes_with_reasons or not repository:return []- github = GitHubIntegration.first_for_team_repository(team_id, repository)+ try:+ github = GitHubIntegration.first_for_team_repository(team_id, repository)+ except GitHubRateLimitError:+ # Suggested reviewers are an optional artefact — omit them rather than failing the report.+ logger.info("GitHub rate limited while probing %s, skipping reviewer resolution", repository)+ return []if github is None:logger.info("No GitHub integration for team %d can access %s, cannot resolve reviewers",@@ -142,7 +148,11 @@ def resolve_suggested_reviewers(pool.submit(github.get_commit_author_info, repository, sha): i for i, (sha, _reason) in enumerate(items)}for future in as_completed(future_to_idx):- author_results[future_to_idx[future]] = future.result()+ try:+ author_results[future_to_idx[future]] = future.result()+ except GitHubRateLimitError:+ # Best-effort: score reviewers from whatever lookups landed before the limit.+ logger.info("GitHub rate limited during commit author lookups for %s", repository)# Weight earlier commits more heavily (position-based weighting)login_weights: Counter[str] = Counter()diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex d81dc941ad30..2a86d596896e 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -41,9 +41,11 @@ from rest_framework.views import APIViewfrom temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedError+from posthog.api.integration import github_rate_limited_responsefrom posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.auth import InternalAPIAuthentication, OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, Userfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity@@ -2042,7 +2044,10 @@ class SignalReportArtefactViewSet(# repository: a report's work legitimately spans multiple repos (cross-repo fixes, stacked# PRs). That connection boundary is the intended scope — any `task:write` holder can already# run agents against those same repos — and the repo/ref values are validated in `get_diff`.- github = GitHubIntegration.first_for_team_repository(self.team.id, repository)+ try:+ github = GitHubIntegration.first_for_team_repository(self.team.id, repository)+ except GitHubRateLimitError as e:+ return github_rate_limited_response(e)if github is None:return Response({"error": f"No GitHub integration can access '{repository}'."},@@ -2054,6 +2059,8 @@ class SignalReportArtefactViewSet(# commit was recorded — e.g. after PR babysitting or customer tweaks.base_branch = github.get_default_branch(repository)result = github.get_diff(repository, target_branch=str(branch), base_branch=base_branch)+ except GitHubRateLimitError as e:+ return github_rate_limited_response(e)except Exception: # noqa: BLE001 — never let an upstream GitHub failure 500 this endpointlogger.warning("signals branch diff fetch errored",diff --git a/products/tasks/backend/repository_readiness.py b/products/tasks/backend/repository_readiness.pyindex 09f33f787591..147f9b9eb3fb 100644--- a/products/tasks/backend/repository_readiness.py+++ b/products/tasks/backend/repository_readiness.py@@ -127,32 +127,23 @@ def _refresh_installation_token(integration: Integration) -> None:def _github_get(github: GitHubIntegration,- access_token: str,path: str,*,endpoint: str,params: dict[str, str | int] | None = None,) -> requests.Response:- url = f"https://api.github.com{path}"- return github._github_api_get(- url,+ return github.api_request(+ "GET",+ path,endpoint=endpoint,params=params,timeout=GITHUB_REQUEST_TIMEOUT_SECONDS,- headers={- "Accept": "application/vnd.github+json",- "Authorization": f"Bearer {access_token}",- "X-GitHub-Api-Version": "2022-11-28",- },)-def _fetch_repository_tree(- github: GitHubIntegration, access_token: str, repository: str-) -> tuple[list[str], str | None]:+def _fetch_repository_tree(github: GitHubIntegration, repository: str) -> tuple[list[str], str | None]:repo_response = _github_get(github,- access_token,f"/repos/{repository}",endpoint="/repos/{owner}/{repo}",)@@ -166,7 +157,6 @@ def _fetch_repository_tree(tree_response = _github_get(github,- access_token,f"/repos/{repository}/git/trees/{default_branch}",endpoint="/repos/{owner}/{repo}/git/trees/{tree_sha}",params={"recursive": 1},@@ -216,12 +206,9 @@ def _select_candidate_paths(paths: list[str]) -> list[str]:return candidates[:MAX_CANDIDATE_PATHS]-def _fetch_file_content(- github: GitHubIntegration, access_token: str, repository: str, path: str, ref: str | None-) -> str | None:+def _fetch_file_content(github: GitHubIntegration, repository: str, path: str, ref: str | None) -> str | None:response = _github_get(github,- access_token,f"/repos/{repository}/contents/{path}",endpoint="/repos/{owner}/{repo}/contents/{path}",params={"ref": ref} if ref else None,@@ -244,11 +231,9 @@ def _fetch_file_content(return None-def _scan_repository(- integration: Integration, access_token: str, repository: str-) -> tuple[RepositoryScanEvidence, list[str]]:- github = GitHubIntegration(integration)- tree_paths, default_branch = _fetch_repository_tree(github, access_token, repository)+def _scan_repository(integration: Integration, repository: str) -> tuple[RepositoryScanEvidence, list[str]]:+ github = GitHubIntegration(integration, source="tasks")+ tree_paths, default_branch = _fetch_repository_tree(github, repository)found_posthog_init = Falsefound_posthog_capture = False@@ -265,7 +250,7 @@ def _scan_repository(extra={"repository": repository, "scanned": scanned},)break- content = _fetch_file_content(github, access_token, repository, path, default_branch)+ content = _fetch_file_content(github, repository, path, default_branch)if content is None:continue@@ -443,7 +428,7 @@ def compute_repository_readiness(return responsetry:- scan_evidence, tree_paths = _scan_repository(integration, access_token, repository)+ scan_evidence, tree_paths = _scan_repository(integration, repository)except Exception:logger.exception("repository_readiness.scan_failed", extra={"repository": repository})scan_evidence = RepositoryScanEvidence(diff --git a/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py b/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.pyindex 6239e912f988..e916ba9ce9db 100644--- a/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py+++ b/products/tasks/backend/temporal/code_workstreams/activities/discover_branch_prs.py@@ -8,6 +8,7 @@ from django.utils import timezoneimport requestsfrom temporalio import activity+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationErrorfrom posthog.temporal.common.utils import close_db_connections@@ -130,7 +131,7 @@ def discover_branch_prs_for_team(activity.logger.warning("code_workstreams_discover_integration_missing", repository=candidate.repository)integrations[cache_key] = Nonecontinue- except (GitHubIntegrationError, requests.RequestException) as e:+ except (GitHubIntegrationError, GitHubRateLimitError, requests.RequestException) as e:# Token-refresh failure; skip this candidate rather than aborting the activity.activity.logger.warning("code_workstreams_discover_integration_unavailable", repository=candidate.repository, error=str(e)diff --git a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.pyindex c4eb3507ef42..4174c0cc7e4f 100644--- a/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py+++ b/products/tasks/backend/temporal/code_workstreams/activities/poll_pull_requests.py@@ -11,6 +11,7 @@ from django.utils.dateparse import parse_datetimeimport requestsfrom temporalio import activity+from posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models.github_integration_base import GitHubIntegrationBase, GitHubIntegrationErrorfrom posthog.models.scoping import team_scopefrom posthog.temporal.common.utils import close_db_connections@@ -74,7 +75,7 @@ def poll_pull_requests_for_team(except ObjectDoesNotExist:activity.logger.warning("code_workstreams_pr_integration_missing", pr_url=ref.pr_url)continue- except (GitHubIntegrationError, requests.RequestException) as e:+ except (GitHubIntegrationError, GitHubRateLimitError, requests.RequestException) as e:# A token-refresh failure for one PR must not abort the whole activity (which would# block the team's rebuild this cycle); skip this PR and move on.activity.logger.warning("code_workstreams_pr_integration_unavailable", pr_url=ref.pr_url, error=str(e))@@ -84,11 +85,11 @@ def poll_pull_requests_for_team(try:snap = integration.get_pull_request_snapshot(ref.pr_url)+ except GitHubRateLimitError:+ activity.logger.warning("code_workstreams_pr_rate_limited", team_id=team_id, polled=polled)+ rate_limited = True+ breakexcept GitHubIntegrationError as e:- if getattr(e, "is_rate_limit", False):- activity.logger.warning("code_workstreams_pr_rate_limited", team_id=team_id, polled=polled)- rate_limited = True- breakactivity.logger.warning("code_workstreams_pr_fetch_failed", pr_url=ref.pr_url, error=str(e))continueexcept Exception as e:diff --git a/products/visual_review/backend/github.py b/products/visual_review/backend/github.pydeleted file mode 100644index 2e337ff65e11..000000000000--- a/products/visual_review/backend/github.py+++ /dev/null@@ -1,118 +0,0 @@-"""-GitHub API client wrapper for visual_review.--Centralizes auth headers, rate limit logging, and rate limit error detection-so individual call sites don't need to handle any of this.-"""--from __future__ import annotations--import requests-import structlog--from posthog.egress.github.transport import (- GitHubRateLimitError,- github_request as _egress_github_request,- raise_if_github_rate_limited,-)--logger = structlog.get_logger(__name__)---def github_request(- method: str,- url: str,- access_token: str,- *,- installation_id: str | None = None,- **kwargs,-) -> requests.Response:- """Make a GitHub API request with standard headers, rate limit logging, and rate limit detection.-- Pass ``installation_id`` (the GitHub App installation id) so egress telemetry records the shared- rate-limit gauges, not just request volume.-- Raises GitHubRateLimitError on 403/429 when the rate limit is exhausted.- """- # 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)-- return response---def _safe_int(value: str | None) -> int | None:- if not value:- return None- try:- return int(value)- except (ValueError, TypeError):- return None---def _log_rate_limit_headers(response: requests.Response, method: str, url: str) -> None:- remaining = response.headers.get("x-ratelimit-remaining")- if remaining is None:- return-- limit = response.headers.get("x-ratelimit-limit")- used = response.headers.get("x-ratelimit-used")- reset = response.headers.get("x-ratelimit-reset")- resource = response.headers.get("x-ratelimit-resource")-- remaining_int = _safe_int(remaining)-- if remaining_int is not None and remaining_int < 100:- logger.warning(- "visual_review.github_rate_limit_low",- remaining=remaining,- limit=limit,- used=used,- reset=reset,- resource=resource,- method=method,- url=_sanitize_url(url),- )- else:- logger.debug(- "visual_review.github_rate_limit",- remaining=remaining,- limit=limit,- used=used,- resource=resource,- )---def _check_rate_limit_response(response: requests.Response, method: str, url: str) -> None:- # GitHub returns 429 for secondary rate limits (concurrent request limits)- # and 403 with "rate limit" in the body for primary rate limits.- # raise_if_github_rate_limited handles detection and construction; we add structlog context here.- try:- raise_if_github_rate_limited(response)- except GitHubRateLimitError as e:- logger.error( # noqa: TRY400 — rate limiting is expected; no traceback needed- "visual_review.github_rate_limit_exceeded",- method=method,- url=_sanitize_url(url),- status_code=response.status_code,- reset_at=e.reset_at,- retry_after=e.retry_after,- remaining=response.headers.get("x-ratelimit-remaining"),- limit=response.headers.get("x-ratelimit-limit"),- resource=response.headers.get("x-ratelimit-resource"),- )- raise---def _sanitize_url(url: str) -> str:- """Strip query params from URL for logging (may contain tokens in rare cases)."""- return url.split("?")[0]diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex 25881141be60..d39bfa3c3da4 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -10,10 +10,11 @@ from __future__ import annotationsimport reimport htmlfrom collections import Counter-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom datetime import datetimefrom typing import TYPE_CHECKING+from urllib.parse import quotefrom uuid import UUIDfrom django.conf import settings@@ -28,10 +29,13 @@ from django.utils import timezoneimport structlogif TYPE_CHECKING:+ import requests+from posthog.models.integration import GitHubIntegrationfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.helpers.trigram_search import TrigramSearchField, apply_trigram_search, normalize_search_term+from posthog.models.github_integration_base import GitHubIntegrationErrorfrom .classifier import SnapshotClassifierfrom .db import READER_DB, WRITER_DB@@ -422,22 +426,12 @@ def _resolve_baselines_at_ref(repo: Repo, github: GitHubIntegration, run_type: sdef _get_merge_base_sha(github: GitHubIntegration, repo_full_name: str, base: str, head: str) -> str | None:"""Get the merge-base SHA between two refs via the GitHub Compare API."""- from urllib.parse import quote-- import requests-- from .github import github_request-- access_token = github.get_access_token()try:- response = github_request(+ response = github.api_request("GET",- f"https://api.github.com/repos/{repo_full_name}/compare/{quote(base, safe='')}...{quote(head, safe='')}",- access_token=access_token,- installation_id=github.github_installation_id,- timeout=10,+ f"/repos/{repo_full_name}/compare/{quote(base, safe='')}...{quote(head, safe='')}",)- except requests.RequestException:+ except GitHubIntegrationError:logger.warning("visual_review.merge_base_fetch_failed", repo=repo_full_name, base=base, head=head)return None@@ -463,33 +457,15 @@ def _get_merge_base_sha(github: GitHubIntegration, repo_full_name: str, base: stdef _get_default_branch(github: GitHubIntegration, repo_full_name: str) -> str:- """Get the repo's default branch name via the GitHub API. Falls back to 'master'."""- import requests-- from .github import github_request-- access_token = github.get_access_token()+ """The repo's default branch via the integration's cached verb. Falls back to 'master'."""try:- response = github_request(- "GET",- f"https://api.github.com/repos/{repo_full_name}",- access_token=access_token,- installation_id=github.github_installation_id,- timeout=10,- )- except requests.RequestException:+ return github.get_default_branch(repo_full_name)+ except GitHubRateLimitError:+ raise+ except Exception:logger.warning("visual_review.default_branch_fetch_failed", repo=repo_full_name)return "master"- if response.status_code == 200:- return response.json().get("default_branch", "master")- logger.warning(- "visual_review.default_branch_fetch_failed",- repo=repo_full_name,- status=response.status_code,- )- return "master"-def _run_is_on_default_branch(repo: Repo, branch: str) -> bool:"""Whether this run targets the repo's GitHub default branch.@@ -503,8 +479,6 @@ def _run_is_on_default_branch(repo: Repo, branch: str) -> bool:"""try:github = get_github_integration_for_repo(repo)- if github.access_token_expired():- github.refresh_access_token()except Exception:logger.info("visual_review.no_github_integration", repo_id=str(repo.id))return False@@ -520,8 +494,6 @@ def _resolve_baselines(repo, run_type: str, branch: str) -> dict[str, str]:"""try:github = get_github_integration_for_repo(repo)- if github.access_token_expired():- github.refresh_access_token()except Exception:logger.info("visual_review.no_github_integration", repo_id=str(repo.id))return {}@@ -552,8 +524,6 @@ def _resolve_baselines_with_merge_base("""try:github = get_github_integration_for_repo(repo)- if github.access_token_expired():- github.refresh_access_token()except Exception:logger.info("visual_review.no_github_integration", repo_id=str(repo.id))return {}, 0@@ -1301,12 +1271,7 @@ def _rerun_github_job(run: Run, check_run_id: str) -> tuple[bool, str | None]:# `${{ job.check_run_id }}` doubles as the Actions job ID, so the jobs API# gives us head_sha and the owning workflow run (run_id) in one call.try:- job_response = _github_api_request(- "GET",- repo,- f"actions/jobs/{check_run_id}",- timeout=10,- )+ job_response = _github_api_request("GET", repo, f"actions/jobs/{check_run_id}")except Exception:return False, "Failed to verify CI job ownership"@@ -1339,12 +1304,7 @@ def _rerun_github_job(run: Run, check_run_id: str) -> tuple[bool, str | None]:return False, "CI job does not belong to this run's workflow"try:- response = _github_api_request(- "POST",- repo,- f"actions/jobs/{check_run_id}/rerun",- timeout=10,- )+ response = _github_api_request("POST", repo, f"actions/jobs/{check_run_id}/rerun")except Exception:return False, "Failed to trigger job rerun"@@ -1368,7 +1328,7 @@ def get_github_integration_for_repo(repo: Repo):if not integration:raise GitHubIntegrationNotFoundError(f"No GitHub integration found for team {repo.team_id}")- return GitHubIntegration(integration)+ return GitHubIntegration(integration, source="visual_review")def _resolve_repo_by_id(github, repo_external_id: int) -> str | None:@@ -1379,16 +1339,7 @@ def _resolve_repo_by_id(github, repo_external_id: int) -> str | None:latest full_name even if the repo was renamed or transferred.Returns None if the repo is inaccessible."""- from .github import github_request-- access_token = github.get_access_token()- response = github_request(- "GET",- f"https://api.github.com/repositories/{repo_external_id}",- access_token=access_token,- installation_id=github.github_installation_id,- timeout=10,- )+ response = github.api_request("GET", f"/repositories/{repo_external_id}")if response.status_code == 200:return response.json().get("full_name")return None@@ -1398,8 +1349,10 @@ def _github_api_request(method: str,repo: Repo,path: str,- **kwargs,-):+ *,+ json: Mapping[str, object] | None = None,+ timeout: int = 10,+) -> requests.Response:"""Make a GitHub API request, auto-resolving renamed repos on 404.@@ -1407,20 +1360,12 @@ def _github_api_request(the current full_name via /repositories/{id}. If it changed, updatesthe stored repo_full_name and retries once."""- from urllib.parse import quote-- from .github import github_request-# Prevent path traversal — each segment must be safesafe_path = "/".join(quote(segment, safe="") for segment in path.split("/"))github = get_github_integration_for_repo(repo)- access_token = github.get_access_token()- url = f"https://api.github.com/repos/{repo.repo_full_name}/{safe_path}"- response = github_request(- method, url, access_token=access_token, installation_id=github.github_installation_id, **kwargs- )+ response = github.api_request(method, f"/repos/{repo.repo_full_name}/{safe_path}", json_body=json, timeout=timeout)if response.status_code == 404 and repo.repo_external_id:new_full_name = _resolve_repo_by_id(github, repo.repo_external_id)@@ -1434,9 +1379,8 @@ def _github_api_request(repo.repo_full_name = new_full_namerepo.save(update_fields=["repo_full_name"])- url = f"https://api.github.com/repos/{new_full_name}/{safe_path}"- response = github_request(- method, url, access_token=access_token, installation_id=github.github_installation_id, **kwargs+ response = github.api_request(+ method, f"/repos/{new_full_name}/{safe_path}", json_body=json, timeout=timeout)return response@@ -1448,17 +1392,7 @@ def _get_pr_info(github, repo_full_name: str, pr_number: int) -> dict:Returns dict with head_ref (branch) and head_sha."""- from .github import github_request-- access_token = github.get_access_token()-- response = github_request(- "GET",- f"https://api.github.com/repos/{repo_full_name}/pulls/{pr_number}",- access_token=access_token,- installation_id=github.github_installation_id,- timeout=10,- )+ response = github.api_request("GET", f"/repos/{repo_full_name}/pulls/{pr_number}")if response.status_code != 200:raise GitHubCommitError(f"Failed to fetch PR info: {response.status_code} {response.text}")@@ -1480,34 +1414,21 @@ def _fetch_baseline_file(identifier to ``{hash: "v1.kid.hash.tag"}`` (the signed format).If the file doesn't exist, returns ``({}, None)``."""- import base64-import yaml- from .github import github_request-- access_token = github.get_access_token()-- response = github_request(- "GET",- f"https://api.github.com/repos/{repo_full_name}/contents/{file_path}",- access_token=access_token,- installation_id=github.github_installation_id,- params={"ref": branch},- timeout=10,- )+ try:+ result = github.get_file_contents(repo_full_name, file_path, ref=branch)+ except GitHubRateLimitError:+ raise+ except GitHubIntegrationError as e:+ raise GitHubCommitError(f"Failed to fetch baseline file: {e}") from e- if response.status_code == 404:+ if result is None:return {}, None- if response.status_code != 200:- raise GitHubCommitError(f"Failed to fetch baseline file: {response.status_code} {response.text}")-- data = response.json()- content = base64.b64decode(data["content"]).decode("utf-8")- file_sha = data["sha"]+ file_sha = result["sha"]- parsed = yaml.safe_load(content)+ parsed = yaml.safe_load(result["content"])if not parsed or parsed.get("version") != 1:return {}, file_sha@@ -1588,8 +1509,6 @@ def _post_commit_status(if not repo.repo_full_name:return- from .github import github_request-context = f"PostHog Visual Review / {run.run_type}"# Tracking-only (observe) and partial runs must never satisfy the gating context that# branch protection evaluates. Both purpose and is_partial are client-supplied, so an@@ -1603,28 +1522,22 @@ def _post_commit_status(try:github = get_github_integration_for_repo(repo)- if github.access_token_expired():- github.refresh_access_token()except Exception:logger.debug("visual_review.status_check_skipped", run_id=str(run.id), reason="no_github_integration")return- access_token = github.get_access_token()target_url = _run_url(run, repo)try:- response = github_request(+ response = github.api_request("POST",- f"https://api.github.com/repos/{repo.repo_full_name}/statuses/{run.commit_sha}",- access_token=access_token,- installation_id=github.github_installation_id,- json={+ f"/repos/{repo.repo_full_name}/statuses/{run.commit_sha}",+ json_body={"state": state,"description": description[:140],"context": context,"target_url": target_url,},- timeout=10,)if response.status_code != 201:@@ -1674,9 +1587,6 @@ def _commit_baseline_to_github(github = get_github_integration_for_repo(repo)- if github.access_token_expired():- github.refresh_access_token()-if run.pr_number is None:raise GitHubCommitError("Cannot commit to GitHub: run has no associated PR number")@@ -1787,7 +1697,6 @@ def _post_review_prompt_comment(run: Run, repo: Repo) -> None:repo=repo,path=f"issues/comments/{existing_comment_id}",json={"body": comment_body},- timeout=10,)if response.status_code == 200:run.metadata["github_comment_id"] = existing_comment_id@@ -1806,7 +1715,6 @@ def _post_review_prompt_comment(run: Run, repo: Repo) -> None:repo=repo,path=f"issues/{run.pr_number}/comments",json={"body": comment_body},- timeout=10,)if response.status_code == 201:comment_id = response.json().get("id")@@ -2289,8 +2197,6 @@ def build_signed_baseline(run_id: UUID, team_id: int | None = None) -> str:baseline_path = baseline_paths.get(run.run_type) or baseline_paths.get("default", ".snapshots.yml")github = get_github_integration_for_repo(repo)- if github.access_token_expired():- github.refresh_access_token()current_baselines, _file_sha = _fetch_baseline_file(github, repo.repo_full_name, baseline_path, run.branch)snapshots = list(run.snapshots.all())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 c6c3b591cefb..2be8254e41aa 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@@ -363,8 +363,8 @@ def _github_retry_wait(state: RetryCallState) -> float:exponential backoff."""if state.outcome is not None and state.outcome.failed:exc = state.outcome.exception()- if isinstance(exc, GitHubRateLimitError) and exc.retry_after_seconds is not None:- return min(exc.retry_after_seconds, GITHUB_MAX_RETRY_AFTER_SECONDS) + random.uniform(0, 1)+ if isinstance(exc, GitHubRateLimitError) and exc.retry_after is not None:+ return min(float(exc.retry_after), GITHUB_MAX_RETRY_AFTER_SECONDS) + random.uniform(0, 1)return _github_backoff_wait(state)