:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(devex): meter GitHub search resources separately in the egress limiter (#68899)
Julian Bezdc7b88780a3f
diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex 9c703a3ecfb9..9a8bba179950 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -39,8 +39,13 @@ The GitHub helpers wrap the key construction; other domains expose their own thiA budget is a `RatePolicy`: one or more `(count, period_seconds)` limits enforced _together_, so you can cap the hour and smooth per-minute bursts on the same key.Each domain registers its policy with `register_policy(domain, policy)`, usually as a provider taking the full limiter key, so the budget is read at acquire time (settings + per-scope state) rather than frozen at import.-GitHub's budget is per **installation** (the unit GitHub meters), scaled to the installation's real tier: `api_request` persists each installation's last-observed core `X-RateLimit-Limit` (only trusted installation-token responses feed this), and the policy budgets 90% of it for the hour with a proportional per-minute smoothing cap (most installations sit on GitHub's 5,000/hour tier, not the 15,000 top tier).-Unobserved installations fall back to the settings defaults (13,500/hour + 750/minute) until their first recorded response.+GitHub meters its REST resources on **separate per-installation counters**, so it registers three domains — one per resource — and the transport routes each request to its meter by URL:++- `github` — the `core` resource (5,000–15,000/hour), budgeted per **installation** and scaled to the installation's real tier: `api_request` persists each installation's last-observed core `X-RateLimit-Limit` (only trusted installation-token responses feed this), and the policy budgets 90% of it for the hour with a proportional per-minute smoothing cap (most installations sit on GitHub's 5,000/hour tier, not the 15,000 top tier). Unobserved installations fall back to the settings defaults (13,500/hour + 750/minute) until their first recorded response.+- `github_search` — the `search` resource, a static 27/minute (under GitHub's real 30/min).+- `github_code_search` — the `code_search` resource (`/search/code`), a static 8/minute (under GitHub's real 10/min).++The two search budgets are static because GitHub's search rate limits are fixed regardless of the account's plan tier, so there is no tier to observe (unlike core).Budgets stay deliberately under the real ceiling so reactive backoff absorbs drift (clock skew, multi-process races, untracked PAT traffic on the same account).### Priority lanesdiff --git a/posthog/egress/github/limiter.py b/posthog/egress/github/limiter.pyindex 75e405b27dae..73db66da0617 100644--- a/posthog/egress/github/limiter.py+++ b/posthog/egress/github/limiter.py@@ -1,18 +1,25 @@"""GitHub egress — the first consumer of the outbound rate limiter.-A GitHub App installation gets 5,000–15,000 REST requests/hour depending on the account's-plan tier, shared across every PostHog consumer of that installation (warehouse sources,-Tasks, Code, Conversations, Visual review). This module budgets each installation to its-observed tier and registers that budget as a policy keyed per installation. The budget is-one shared envelope across GitHub's resources (REST core, GraphQL, …) — deliberately-conservative rather than modeling each resource's separate meter.--Importing this module registers the policy as a side effect — import it (directly or via-``acquire_github_installation``) before using a ``github:...`` limiter key.+A GitHub App installation gets 5,000–15,000 REST requests/hour on the ``core`` resource+depending on the account's plan tier, shared across every PostHog consumer of that+installation (warehouse sources, Tasks, Code, Conversations, Visual review). GitHub meters+its other REST resources on their own separate, per-installation counters — ``search`` at a+fixed 30/min and ``code_search`` at a fixed 10/min, regardless of plan. So each resource+gets its own limiter domain and budget here rather than sharing one envelope: charging a+``/search/code`` call (10/min real ceiling) against the 5,000/hour core budget let it sail+through while GitHub itself 403/429'd it.++This module budgets ``core`` to each installation's observed tier and the two search+resources to their fixed real ceilings, registering each as a policy keyed per installation.++Importing this module registers the policies as a side effect — import it (directly or via+``acquire_github_installation``) before using a ``github*:...`` limiter key."""import time+from enum import Enumfrom typing import TYPE_CHECKING+from urllib.parse import urlparsefrom django.conf import settingsfrom django.core.cache import cache@@ -24,6 +31,42 @@ from posthog.egress.limiter.outbound import get_outbound_rate_limiterfrom posthog.egress.limiter.policies import Priority, RatePolicy, register_policyGITHUB_DOMAIN = "github"+GITHUB_SEARCH_DOMAIN = "github_search"+GITHUB_CODE_SEARCH_DOMAIN = "github_code_search"+++class GitHubRateResource(Enum):+ """A GitHub REST rate-limit resource — each metered on its own per-installation counter."""++ CORE = "core"+ SEARCH = "search"+ CODE_SEARCH = "code_search"+++def classify_github_resource(url: str) -> GitHubRateResource:+ """Map a GitHub API URL to the resource GitHub meters it against.++ ``/search/code`` is the ``code_search`` resource (10/min); any other ``/search/...`` is+ ``search`` (30/min); everything else is ``core``. GraphQL (``/graphql``) deliberately routes+ to ``core``: GitHub meters it on its own tier-scaled *point*-based resource, and a plain+ request counter can't model point costs — charging it to our core envelope errs conservative.+ """+ path = urlparse(url).path+ if path == "/search/code" or path.startswith("/search/code/"):+ return GitHubRateResource.CODE_SEARCH+ if path == "/search" or path.startswith("/search/"):+ return GitHubRateResource.SEARCH+ return GitHubRateResource.CORE+++# Maps a resource to the limiter domain that carries its budget. New domains (not key suffixes)+# so resolve_policy dispatches on them, installation_id_from_key's rpartition still round-trips,+# and outbound_rate_limit_decisions_total gets a distinct metric series per resource for free.+_RESOURCE_DOMAINS: dict[GitHubRateResource, str] = {+ GitHubRateResource.CORE: GITHUB_DOMAIN,+ GitHubRateResource.SEARCH: GITHUB_SEARCH_DOMAIN,+ GitHubRateResource.CODE_SEARCH: GITHUB_CODE_SEARCH_DOMAIN,+}# Reserved-floor ladder: BATCH calls are denied once 70% of a window is consumed, NORMAL at 90%,# CRITICAL can use the full budget. Active now that deferrable callers declare their lane@@ -171,28 +214,55 @@ def _github_policy(key: str) -> RatePolicy:register_policy(GITHUB_DOMAIN, _github_policy)--def github_installation_key(installation_id: str | int) -> str:- """Limiter key for one GitHub App installation — the unit GitHub's budget is scoped to."""- return f"{GITHUB_DOMAIN}:installation:{installation_id}"+# Static budgets, no observed-limit persistence: GitHub's search rate limits are fixed regardless+# of the account's plan tier (unlike core), so there is no tier to observe. Both sit just under+# GitHub's real per-installation ceilings (10/min and 30/min) so our reactive backoff absorbs+# drift. Same reserve ladder as core so BATCH/NORMAL callers still shed first as the window fills.+register_policy(+ GITHUB_CODE_SEARCH_DOMAIN,+ RatePolicy(limits=((8, 60.0),), in_memory_divider=4, reserve=_RESERVE),+)+register_policy(+ GITHUB_SEARCH_DOMAIN,+ RatePolicy(limits=((27, 60.0),), in_memory_divider=4, reserve=_RESERVE),+)+++def github_installation_key(+ installation_id: str | int, *, resource: GitHubRateResource = GitHubRateResource.CORE+) -> str:+ """Limiter key for one GitHub App installation and one metered resource — the unit GitHub's+ budget is scoped to. The resource picks the domain (its own counter); the scope stays the+ installation."""+ return f"{_RESOURCE_DOMAINS[resource]}:installation:{installation_id}"async def acquire_github_installation(- installation_id: str | int, n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown"+ installation_id: str | int,+ n: int = 1,+ *,+ priority: Priority = Priority.NORMAL,+ source: str = "unknown",+ resource: GitHubRateResource = GitHubRateResource.CORE,) -> bool:- """Reserve ``n`` requests against an installation's hourly GitHub budget. Returns False when the+ """Reserve ``n`` requests against an installation's budget for ``resource``. Returns False when thebudget (or this ``priority``'s reserved floor) is exhausted — back off and retry rather thancalling GitHub."""return await get_outbound_rate_limiter().acquire(- github_installation_key(installation_id), n, priority=priority, source=source+ github_installation_key(installation_id, resource=resource), n, priority=priority, source=source)def consume_github_installation_sync(- installation_id: str | int, n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown"+ installation_id: str | int,+ n: int = 1,+ *,+ priority: Priority = Priority.NORMAL,+ source: str = "unknown",+ resource: GitHubRateResource = GitHubRateResource.CORE,) -> bool:"""Sync variant of :func:`acquire_github_installation` for callers outside an event loop (e.g. thewarehouse source iterator, which runs in a thread pool)."""return get_outbound_rate_limiter().consume_sync(- github_installation_key(installation_id), n, priority=priority, source=source+ github_installation_key(installation_id, resource=resource), n, priority=priority, source=source)diff --git a/posthog/egress/github/transport.py b/posthog/egress/github/transport.pyindex 738ad7164cff..db923ba94109 100644--- a/posthog/egress/github/transport.py+++ b/posthog/egress/github/transport.py@@ -15,7 +15,7 @@ from typing import Anyimport requests-from posthog.egress.github.limiter import consume_github_installation_sync+from posthog.egress.github.limiter import classify_github_resource, consume_github_installation_syncfrom posthog.egress.github.observability import record_github_api_exception, record_github_api_responsefrom posthog.egress.limiter.policies import Priorityfrom posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient@@ -98,8 +98,10 @@ class GitHubClient(EgressClient):def _standard_headers(self) -> dict[str, str]:return {"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": GITHUB_API_VERSION}- def _consume(self, scope: str, priority: Priority, source: str) -> bool:- return consume_github_installation_sync(scope, priority=priority, source=source)+ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ return consume_github_installation_sync(+ scope, resource=classify_github_resource(url), priority=priority, source=source+ )def _record_response(self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | Nonediff --git a/posthog/egress/test/test_github_limiter.py b/posthog/egress/test/test_github_limiter.pyindex 17c6d733a6e4..4484c01a277b 100644--- a/posthog/egress/test/test_github_limiter.py+++ b/posthog/egress/test/test_github_limiter.py@@ -8,11 +8,14 @@ from parameterized import parameterizedfrom requests.structures import CaseInsensitiveDictfrom posthog.egress.github.limiter import (+ GitHubRateResource,_last_written,_observed_memo,_tier_budgets,+ classify_github_resource,get_observed_core_limit,github_installation_key,+ installation_id_from_key,observed_core_limit_cache_key,remember_observed_core_limit,)@@ -110,3 +113,56 @@ class TestObservedCoreLimitStore(GitHubLimiterTestCase):# the policy's window smaller than a single call and raise on every acquire, CRITICAL included).cache.set(observed_core_limit_cache_key(self.installation_id), cached, 60)assert get_observed_core_limit(self.installation_id) is None+++class TestClassifyGithubResource(SimpleTestCase):+ # The routing that this whole fix hinges on: a /search/code call charged to core would sail+ # through the 5k/hour budget while GitHub 403/429s it at 10/min. Guards that each URL lands on+ # the resource GitHub actually meters it against.+ @parameterized.expand(+ [+ ("code_search_full_url", "https://api.github.com/search/code?q=x", GitHubRateResource.CODE_SEARCH),+ ("code_search_bare_path", "/search/code", GitHubRateResource.CODE_SEARCH),+ ("search_issues", "/search/issues", GitHubRateResource.SEARCH),+ ("search_repositories", "/search/repositories?q=x", GitHubRateResource.SEARCH),+ ("core_repo_call", "/repos/o/r/pulls/1", GitHubRateResource.CORE),+ ("graphql_routes_to_core", "/graphql", GitHubRateResource.CORE),+ ("access_tokens_is_core", "/app/installations/1/access_tokens", GitHubRateResource.CORE),+ ]+ )+ def test_classify(self, _name: str, url: str, expected: GitHubRateResource) -> None:+ assert classify_github_resource(url) == expected+++class TestSearchResourcePolicies(SimpleTestCase):+ # The static search budgets and the reserve ladder attach: a regression here silently reverts+ # /search/code to the flat core budget (the bug this fix closes) or drops the shedding ladder.+ @parameterized.expand(+ [+ ("code_search", GitHubRateResource.CODE_SEARCH, (8, 60.0)),+ ("search", GitHubRateResource.SEARCH, (27, 60.0)),+ ]+ )+ def test_static_policy_and_reserve_ladder(+ self, _name: str, resource: GitHubRateResource, expected_limit: tuple[int, float]+ ) -> None:+ policy = resolve_policy(github_installation_key("x", resource=resource))+ assert policy.limits == (expected_limit,)+ assert policy.reserve_fraction(Priority.BATCH) > policy.reserve_fraction(Priority.NORMAL) > 0.0+ assert policy.reserve_fraction(Priority.CRITICAL) == 0.0+++class TestInstallationKeyResource(SimpleTestCase):+ # The resource -> domain mapping plus the key round-trip: a broken mapping keys the wrong meter,+ # and a broken round-trip means the tier lookup reads the wrong installation.+ @parameterized.expand(+ [+ ("core", GitHubRateResource.CORE, "github"),+ ("search", GitHubRateResource.SEARCH, "github_search"),+ ("code_search", GitHubRateResource.CODE_SEARCH, "github_code_search"),+ ]+ )+ def test_key_domain_and_round_trip(self, _name: str, resource: GitHubRateResource, expected_domain: str) -> None:+ key = github_installation_key(42, resource=resource)+ assert key.split(":")[0] == expected_domain+ assert installation_id_from_key(key) == "42"diff --git a/posthog/egress/test/test_github_transport.py b/posthog/egress/test/test_github_transport.pynew file mode 100644index 000000000000..e4c0a7f16600--- /dev/null+++ b/posthog/egress/test/test_github_transport.py@@ -0,0 +1,48 @@+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++import requests+from parameterized import parameterized+from requests.structures import CaseInsensitiveDict++from posthog.egress.github.limiter import GitHubRateResource+from posthog.egress.github.transport import GitHubClient, github_request+++def _response(status: int = 200) -> requests.Response:+ response = requests.models.Response()+ response.status_code = status+ response.headers = CaseInsensitiveDict({})+ prepared = requests.models.PreparedRequest()+ prepared.method = "GET"+ prepared.url = "https://api.github.com/search/code"+ response.request = prepared+ return response+++class TestGitHubTransport(SimpleTestCase):+ @parameterized.expand(+ [+ ("code_search", "https://api.github.com/search/code?q=x", GitHubRateResource.CODE_SEARCH),+ ("core", "https://api.github.com/repos/o/r/pulls/1", GitHubRateResource.CORE),+ ]+ )+ def test_consume_routes_resource_by_url(self, _name: str, url: str, expected: GitHubRateResource) -> None:+ # The gate must charge each URL to the meter GitHub bills it against — the whole point of the+ # per-resource split. A regression here reverts /search/code to the core envelope.+ client = GitHubClient()+ with patch("posthog.egress.github.transport.consume_github_installation_sync", return_value=True) as consume:+ client._consume("42", MagicMock(), "test", url)+ assert consume.call_args.kwargs["resource"] == expected++ def test_identity_blind_call_never_touches_the_limiter(self) -> None:+ # A None installation_id (public token / raw PAT) records volume only and must skip the gate,+ # or unrelated tokens would share and clobber one phantom budget.+ with (+ patch("posthog.egress.github.transport.consume_github_installation_sync") as consume,+ patch("requests.request", return_value=_response()),+ patch("posthog.egress.github.transport.record_github_api_response"),+ ):+ github_request("GET", "https://api.github.com/search/code?q=x", source="test", installation_id=None)+ consume.assert_not_called()diff --git a/posthog/egress/test/test_outbound_rate_limiter.py b/posthog/egress/test/test_outbound_rate_limiter.pyindex 89b0bdd22748..b2221e9be014 100644--- a/posthog/egress/test/test_outbound_rate_limiter.py+++ b/posthog/egress/test/test_outbound_rate_limiter.py@@ -3,7 +3,7 @@ import pytestimport posthog.egress.limiter.backends as backends_moduleimport posthog.egress.limiter.outbound as outbound_moduleimport posthog.egress.limiter.policies as policies_module-from posthog.egress.github.limiter import acquire_github_installation, github_installation_key+from posthog.egress.github.limiter import GitHubRateResource, acquire_github_installation, github_installation_keyfrom posthog.egress.limiter.backends import LimitsBackendfrom posthog.egress.limiter.outbound import OutboundRateLimiterfrom posthog.egress.limiter.policies import Priority, RatePolicy, register_policy, resolve_policy@@ -127,6 +127,20 @@ async def test_github_adapter_registers_policy_and_keys_per_installation():assert await acquire_github_installation(987654321, 1) is True+async def test_github_search_resource_meter_is_independent_of_core():+ # The heart of the fix: code_search has its own 8/min meter, so it denies the 9th call while the+ # SAME installation's core budget (thousands/hour) still grants — a regression that folded them+ # back into one envelope would let /search/code sail past its real 10/min ceiling.+ limiter = _fresh_limiter()+ installation = "1234567890"+ code_search_key = github_installation_key(installation, resource=GitHubRateResource.CODE_SEARCH)+ core_key = github_installation_key(installation, resource=GitHubRateResource.CORE)++ grants = [await limiter.acquire(code_search_key, 1, priority=Priority.CRITICAL) for _ in range(9)]+ assert grants == [True] * 8 + [False]+ assert await limiter.acquire(core_key, 1, priority=Priority.CRITICAL) is True++_RESERVE = {Priority.NORMAL: 0.1, Priority.BATCH: 0.3}diff --git a/posthog/egress/transport/transport.py b/posthog/egress/transport/transport.pyindex bb4f0ae4e733..a25acb594640 100644--- a/posthog/egress/transport/transport.py+++ b/posthog/egress/transport/transport.py@@ -46,7 +46,7 @@ class EgressClient(ABC):session: requests.Session | None = None,**kwargs: Any,) -> requests.Response:- self._gate(scope, source, priority)+ self._gate(scope, source, priority, url)request_headers = {**self._standard_headers(), **(headers or {})}sender = session or requests@@ -60,12 +60,12 @@ class EgressClient(ABC):self._record_response(response, source=source, scope=scope, method=method, endpoint=endpoint)return response- def _gate(self, scope: str | None, source: str, priority: Priority) -> None:+ def _gate(self, scope: str | None, source: str, priority: Priority, url: str) -> None:# Identity-blind callers have no shared budget to draw on — record volume only, never gate.# An empty scope is no identity either: gating on it would key a phantom budget/metric series.if not scope:return- granted = self._consume(scope, priority, source)+ granted = self._consume(scope, priority, source, url)# CRITICAL never blocks: it records the decision (and consumes if there's room) but proceeds# regardless, so a user-facing call is never shed by us — the API's own 429 is the backstop.# Sheddable lanes back off so their headroom is left for higher-priority traffic.@@ -79,8 +79,9 @@ class EgressClient(ABC):"""Default headers merged under the caller's (the caller's win) — e.g. Accept, API version."""@abstractmethod- def _consume(self, scope: str, priority: Priority, source: str) -> bool:- """Draw ``1`` from the domain's shared budget for ``scope`` at ``priority``; True if granted."""+ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ """Draw ``1`` from the domain's shared budget for ``scope`` at ``priority``; True if granted.+ ``url`` lets a domain route the draw to the resource-specific meter GitHub bills the URL to."""@abstractmethoddef _record_response(diff --git a/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py b/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.pyindex 677c9288e7ed..54e40d379058 100644--- a/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py+++ b/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py@@ -1,7 +1,9 @@import urllib.parsefrom concurrent.futures import ThreadPoolExecutor, as_completed+from dataclasses import dataclassfrom django.conf import settings+from django.core.cache import cacheimport requestsimport structlog@@ -11,13 +13,62 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.utils import action-from posthog.egress.github.transport import github_request+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, github_request+from posthog.egress.limiter.policies import Priorityfrom posthog.models.integration import GitHubIntegration, GitLabIntegration, Integrationlogger = structlog.get_logger(__name__)MISSING_REQUIRED_PARAMS_ERROR = "owner, repository, code_sample, and file_name are required"+# Circuit breaker for the shared public GitHub token's code-search path. Django-cache-backed so it+# is shared across worker processes; best-effort so a cache outage never blocks the request path.+_PUBLIC_TOKEN_CIRCUIT_OPEN_KEY = "error_tracking:github_public_token:circuit_open"+_PUBLIC_TOKEN_UNAUTHORIZED_COUNT_KEY = "error_tracking:github_public_token:unauthorized_count"+_UNAUTHORIZED_WINDOW_SECONDS = 600 # 10 min: consecutive 401s inside this window trip the breaker+_CIRCUIT_OPEN_SECONDS = 900 # 15 min: skip the public token path while a dead PAT recovers+_UNAUTHORIZED_THRESHOLD = 3+++class PublicGitHubTokenCircuit:+ """Trips off the shared public GitHub token after repeated 401s so a dead PAT stops spamming+ GitHub with unauthorized requests. While open, the resolver skips straight to the integration+ path — identical behavior to the token being unset, so no user-visible change."""++ def is_open(self) -> bool:+ try:+ return bool(cache.get(_PUBLIC_TOKEN_CIRCUIT_OPEN_KEY))+ except Exception:+ return False++ def record_success(self) -> None:+ # Any non-401 response breaks the consecutive-401 streak; clearing the open flag too means+ # an in-flight success that races the trip closes the circuit immediately.+ try:+ cache.delete(_PUBLIC_TOKEN_UNAUTHORIZED_COUNT_KEY)+ cache.delete(_PUBLIC_TOKEN_CIRCUIT_OPEN_KEY)+ except Exception:+ pass++ def record_unauthorized(self) -> None:+ try:+ cache.add(_PUBLIC_TOKEN_UNAUTHORIZED_COUNT_KEY, 0, _UNAUTHORIZED_WINDOW_SECONDS)+ count = cache.incr(_PUBLIC_TOKEN_UNAUTHORIZED_COUNT_KEY)+ if count >= _UNAUTHORIZED_THRESHOLD:+ cache.set(_PUBLIC_TOKEN_CIRCUIT_OPEN_KEY, True, _CIRCUIT_OPEN_SECONDS)+ logger.error("github_public_token_circuit_opened", unauthorized_count=count)+ except Exception:+ pass+++@dataclass(frozen=True)+class GitHubSearchOutcome:+ """Result of one code-search request: ``url`` is the first match (or None), ``status_code`` is+ the HTTP status the request returned (None when the request raised before a response)."""++ url: str | None+ status_code: int | None+class GitProviderFileLinkResolveQuerySerializer(serializers.Serializer):owner = serializers.CharField(help_text="Repository owner or namespace.")@@ -74,13 +125,22 @@ def prepare_gitlab_search_query(q: str | None) -> str:return " ".join("".join(result).split())-def get_github_file_url(- code_sample: str, token: str, owner: str, repository: str, file_name: str, installation_id: str | None = None-) -> str | None:- """Search GitHub code using the Code Search API. Returns URL to first match or None.+def search_github_file(+ code_sample: str,+ token: str,+ owner: str,+ repository: str,+ file_name: str,+ installation_id: str | None = None,+ priority: Priority = Priority.CRITICAL,+) -> GitHubSearchOutcome:+ """Search GitHub code using the Code Search API. Returns the first match's URL and the request's+ status code so callers can feed the public-token circuit breaker.``installation_id`` is set on the integration-token path (private repos) so the installation's- rate-limit gauges are recorded; the public PostHog-token path leaves it None (no installation)."""+ rate-limit gauges are recorded; the public PostHog-token path leaves it None (no installation).+ ``priority`` lets the integration path yield to our egress limiter (NORMAL) instead of forcing+ the call through (CRITICAL) — a shed search degrades to not-found, which the endpoint tolerates."""code_query = prepare_github_search_query(code_sample)search_query = f"{code_query} repo:{owner}/{repository} filename:{file_name}"encoded_query = urllib.parse.quote(search_query)@@ -93,21 +153,51 @@ def get_github_file_url(try:response = github_request(- "GET", url, source="error_tracking", headers=headers, installation_id=installation_id, timeout=10+ "GET",+ url,+ source="error_tracking",+ headers=headers,+ installation_id=installation_id,+ priority=priority,+ timeout=10,)-if response.status_code == 200:- data = response.json()- items = data.get("items", [])- if items:- return items[0].get("html_url")- return None-- logger.warning("github_code_search_failed", status_code=response.status_code)- return None+ # Body parsing stays inside the guard: a 200 with a malformed body must degrade to+ # not-found like any other failure, not escape as a 500.+ items = response.json().get("items", [])+ return GitHubSearchOutcome(url=items[0].get("html_url") if items else None, status_code=200)+ if response.status_code != 401 or installation_id is not None:+ # The public-token path (no installation) logs its own distinct error for 401s — a+ # second generic warning per request would double the noise without adding signal.+ logger.warning("github_code_search_failed", status_code=response.status_code)+ return GitHubSearchOutcome(url=None, status_code=response.status_code)+ except GitHubEgressBudgetExhausted:+ # Our own limiter shed the (sheddable) call before sending it — treat as not found.+ return GitHubSearchOutcome(url=None, status_code=None)except Exception as error:logger.exception("github_code_search_request_failed", error=str(error))- return None+ return GitHubSearchOutcome(url=None, status_code=None)+++def get_github_file_url(+ code_sample: str,+ token: str,+ owner: str,+ repository: str,+ file_name: str,+ installation_id: str | None = None,+ priority: Priority = Priority.CRITICAL,+) -> str | None:+ """Thin wrapper over :func:`search_github_file` returning only the URL, for the integration path."""+ return search_github_file(+ code_sample=code_sample,+ token=token,+ owner=owner,+ repository=repository,+ file_name=file_name,+ installation_id=installation_id,+ priority=priority,+ ).urldef get_gitlab_file_url(@@ -185,19 +275,27 @@ class GitProviderFileLinksViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):code_sample = serializer.validated_data["code_sample"]file_name = serializer.validated_data["file_name"]- url = None+ circuit = PublicGitHubTokenCircuit()- # Try with PostHog's token first (public repos).- if settings.GITHUB_TOKEN:- url = get_github_file_url(+ # Try with PostHog's token first (public repos). Skip while the circuit is open — a dead PAT+ # would otherwise keep spamming 401s. Skipping is identical to GITHUB_TOKEN being unset.+ if settings.GITHUB_TOKEN and not circuit.is_open():+ outcome = search_github_file(code_sample=code_sample,token=settings.GITHUB_TOKEN,owner=owner,repository=repository,file_name=file_name,)- if url:- return Response({"found": True, "url": url})+ if outcome.status_code == 401:+ circuit.record_unauthorized()+ logger.error("github_public_token_unauthorized", status_code=401)+ elif outcome.status_code is not None:+ # Any completed non-401 response breaks the streak — the breaker is for a dead PAT+ # (consistent 401s), not for interleaved rate-limit or server errors.+ circuit.record_success()+ if outcome.url:+ return Response({"found": True, "url": outcome.url})# Try with assigned GitHub integration (private repos).integration = Integration.objects.filter(team_id=self.team.id, kind="github").first()@@ -217,6 +315,7 @@ class GitProviderFileLinksViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):repository=repository,file_name=file_name,installation_id=github.github_installation_id,+ priority=Priority.NORMAL,)if url:return Response({"found": True, "url": url})diff --git a/products/error_tracking/backend/tests/api/test_git_provider_file_links.py b/products/error_tracking/backend/tests/api/test_git_provider_file_links.pynew file mode 100644index 000000000000..a7346ea4aadd--- /dev/null+++ b/products/error_tracking/backend/tests/api/test_git_provider_file_links.py@@ -0,0 +1,104 @@+import json++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.core.cache import cache+from django.test import override_settings++import requests+from requests.structures import CaseInsensitiveDict++from posthog.egress.github.transport import GitHubEgressBudgetExhausted+from posthog.egress.limiter.policies import Priority++from products.error_tracking.backend.presentation.views.git_provider_file_link_resolver import (+ _PUBLIC_TOKEN_CIRCUIT_OPEN_KEY,+ _PUBLIC_TOKEN_UNAUTHORIZED_COUNT_KEY,+ search_github_file,+)+++def _response(status: int, body: dict | None = None, raw: bytes | None = None) -> requests.Response:+ response = requests.models.Response()+ response.status_code = status+ response.headers = CaseInsensitiveDict({})+ response._content = raw if raw is not None else json.dumps(body or {}).encode()+ return response+++@override_settings(GITHUB_TOKEN="public-pat")+class TestGitProviderFileLinksResolveGithub(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ cache.delete(_PUBLIC_TOKEN_CIRCUIT_OPEN_KEY)+ cache.delete(_PUBLIC_TOKEN_UNAUTHORIZED_COUNT_KEY)+ self.addCleanup(cache.delete, _PUBLIC_TOKEN_CIRCUIT_OPEN_KEY)+ self.addCleanup(cache.delete, _PUBLIC_TOKEN_UNAUTHORIZED_COUNT_KEY)++ def _url(self) -> str:+ return f"/api/projects/{self.team.id}/error_tracking/git-provider-file-links/resolve_github/"++ def _query(self) -> dict[str, str]:+ return {"owner": "o", "repository": "r", "code_sample": "print(1)", "file_name": "main.py"}++ def test_three_unauthorized_trip_circuit_and_skip_public_token(self) -> None:+ # A dead public PAT must stop being called after 3 consecutive 401s, or it spams GitHub with+ # unauthorized requests forever (the prod symptom this fix targets).+ with patch(+ "products.error_tracking.backend.presentation.views.git_provider_file_link_resolver.github_request",+ return_value=_response(401),+ ) as gh:+ for _ in range(3):+ self.client.get(self._url(), self._query())+ assert gh.call_count == 3 # no integration configured, so one call per request++ gh.reset_mock()+ response = self.client.get(self._url(), self._query())++ assert response.json() == {"found": False}+ gh.assert_not_called() # circuit open -> public token path skipped entirely++ def test_success_resets_unauthorized_count(self) -> None:+ # Two 401s then a 2xx must clear the counter, so intermittent auth blips never trip the breaker.+ with patch(+ "products.error_tracking.backend.presentation.views.git_provider_file_link_resolver.github_request"+ ) as gh:+ gh.side_effect = [_response(401), _response(401), _response(200, {"items": []})]+ for _ in range(3):+ self.client.get(self._url(), self._query())++ assert cache.get(_PUBLIC_TOKEN_UNAUTHORIZED_COUNT_KEY) is None+ assert cache.get(_PUBLIC_TOKEN_CIRCUIT_OPEN_KEY) is None++ def test_budget_exhausted_on_integration_path_degrades_to_not_found(self) -> None:+ # The integration path (installation set, sheddable NORMAL lane) is the one place the+ # limiter can shed a search — removing the except clause would 500 the endpoint instead+ # of degrading to not-found.+ with patch(+ "products.error_tracking.backend.presentation.views.git_provider_file_link_resolver.github_request",+ side_effect=GitHubEgressBudgetExhausted("shed"),+ ):+ outcome = search_github_file(+ code_sample="print(1)",+ token="tok",+ owner="o",+ repository="r",+ file_name="main.py",+ installation_id="123",+ priority=Priority.NORMAL,+ )++ assert outcome.url is None+ assert outcome.status_code is None++ def test_malformed_success_body_degrades_to_not_found(self) -> None:+ # A 200 with a non-JSON body must not escape as a 500 — parsing lives inside the guard.+ with patch(+ "products.error_tracking.backend.presentation.views.git_provider_file_link_resolver.github_request",+ return_value=_response(200, raw=b"not json"),+ ):+ response = self.client.get(self._url(), self._query())++ assert response.status_code == 200+ assert response.json() == {"found": False}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.pyindex 92d45495ac9c..906636336ed7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py@@ -4,6 +4,7 @@ from unittest import mockimport requestsfrom prometheus_client import REGISTRY+from posthog.egress.github.limiter import GitHubRateResourcefrom posthog.egress.limiter.policies import Priorityfrom products.warehouse_sources.backend.temporal.data_imports.sources.github import github@@ -79,7 +80,11 @@ def test_fetch_page_gates_on_egress_budget_when_installation_known():assert session.request.call_count == 0assert gate.call_count == 5assert gate.call_args.args[0] == "123"- assert gate.call_args.kwargs == {"priority": Priority.BATCH, "source": "warehouse"}+ assert gate.call_args.kwargs == {+ "priority": Priority.BATCH,+ "source": "warehouse",+ "resource": GitHubRateResource.CORE,+ }def test_fetch_page_skips_gate_on_pat_path():