Skip to content

: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.

feat(devex): unify GitHub egress telemetry across all clients (#67010)

Julian Bez37df5a3a4960
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 9cacaa0f0912..d94816c7539c 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -20,32 +20,16 @@ from django.utils import timezone
import jwt
import requests
import structlog
-from prometheus_client import Counter, Gauge
+from prometheus_client import Counter
+from posthog.rate_limiting.github_observability import record_github_api_exception, record_github_api_response
from posthog.sync import database_sync_to_async_pool
logger = structlog.get_logger(__name__)
-github_api_request_counter = Counter(
- "github_integration_api_requests",
- "Number of GitHub API requests made through a GitHub integration.",
- labelnames=["integration_id", "method", "endpoint", "status_code"],
-)
-github_api_rate_limit_remaining_gauge = Gauge(
- "github_integration_api_rate_limit_remaining",
- "Most recently observed GitHub API rate limit remaining count by integration and resource.",
- labelnames=["integration_id", "resource"],
-)
-github_api_rate_limit_limit_gauge = Gauge(
- "github_integration_api_rate_limit_limit",
- "Most recently observed GitHub API rate limit limit by integration and resource.",
- labelnames=["integration_id", "resource"],
-)
-github_api_rate_limit_reset_timestamp_gauge = Gauge(
- "github_integration_api_rate_limit_reset_timestamp_seconds",
- "Most recently observed GitHub API rate limit reset timestamp by integration and resource.",
- labelnames=["integration_id", "resource"],
-)
+# This client always knows its installation, so it records under source="integration" with a real id.
+_OBSERVABILITY_SOURCE = "integration"
+
github_cache_access_counter = Counter(
"github_integration_cache_accesses",
"Number of GitHub integration cache accesses by cache type, repository, and result.",
@@ -266,38 +250,22 @@ class GitHubIntegrationBase:
)
raise requests.RequestException(f"Unexpected status {response.status_code} verifying installation access")
- @staticmethod
- def _rate_limit_header(headers: Mapping[str, str] | None, name: str) -> float | None:
- if headers is None:
- return None
- value = headers.get(name)
- if value is None:
- return None
- try:
- return float(value)
- except (TypeError, ValueError):
- return None
-
def _record_github_api_response(self, response: requests.Response, method: str, endpoint: str) -> None:
- integration_id = str(self.integration.id)
- status_code = str(response.status_code)
- github_api_request_counter.labels(integration_id, method, endpoint, status_code).inc()
-
- headers = response.headers if isinstance(response.headers, Mapping) else None
- resource = headers.get("X-RateLimit-Resource", "unknown") if headers is not None else "unknown"
- remaining = self._rate_limit_header(headers, "X-RateLimit-Remaining")
- limit = self._rate_limit_header(headers, "X-RateLimit-Limit")
- reset_at = self._rate_limit_header(headers, "X-RateLimit-Reset")
-
- if remaining is not None:
- github_api_rate_limit_remaining_gauge.labels(integration_id, resource).set(remaining)
- if limit is not None:
- github_api_rate_limit_limit_gauge.labels(integration_id, resource).set(limit)
- if reset_at is not None:
- github_api_rate_limit_reset_timestamp_gauge.labels(integration_id, resource).set(reset_at)
+ 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:
- github_api_request_counter.labels(str(self.integration.id), method, endpoint, "exception").inc()
+ 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
diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.py
index 209c43f7a399..ebc4f2954152 100644
--- a/posthog/models/test/test_integration_model.py
+++ b/posthog/models/test/test_integration_model.py
@@ -910,8 +910,14 @@ class TestGitHubIntegrationModel(BaseTest):
_config.update(config or {})
_sensitive_config.update(sensitive_config or {})
+ # Mirror production (integration_from_installation_id): the model integration_id field holds the
+ # GitHub App installation id, which is what egress telemetry keys its gauges on.
return Integration.objects.create(
- team=self.team, kind="github", config=_config, sensitive_config=_sensitive_config
+ team=self.team,
+ kind="github",
+ integration_id=(config or {}).get("installation_id"),
+ config=_config,
+ sensitive_config=_sensitive_config,
)
def mock_github_client_request(
@@ -1128,8 +1134,11 @@ class TestGitHubIntegrationModel(BaseTest):
expected_reset: int | None,
mock_get,
):
+ # Distinct installation id per case: the gauges are keyed by installation_id on a process-global
+ # registry that isn't reset between methods, so a shared id would make the no_headers "== None"
+ # assertion depend on parametrize ordering (another case sets the same (id, "unknown") series).
integration = self.create_integration(
- {"installation_id": "INSTALL", "account": {"name": "PostHog"}},
+ {"installation_id": f"INSTALL-{_name}", "account": {"name": "PostHog"}},
{"access_token": "ACCESS_TOKEN"},
)
response = MagicMock()
@@ -1138,10 +1147,11 @@ class TestGitHubIntegrationModel(BaseTest):
mock_get.return_value = response
labels = {
- "integration_id": str(integration.id),
+ "installation_id": integration.integration_id,
"method": "GET",
"endpoint": "/repos/{owner}/{repo}",
"status_code": "200",
+ "source": "integration",
}
previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0
@@ -1155,21 +1165,21 @@ class TestGitHubIntegrationModel(BaseTest):
assert (
REGISTRY.get_sample_value(
"github_integration_api_rate_limit_remaining",
- {"integration_id": str(integration.id), "resource": expected_resource},
+ {"installation_id": integration.integration_id, "resource": expected_resource},
)
== expected_remaining
)
assert (
REGISTRY.get_sample_value(
"github_integration_api_rate_limit_limit",
- {"integration_id": str(integration.id), "resource": expected_resource},
+ {"installation_id": integration.integration_id, "resource": expected_resource},
)
== expected_limit
)
assert (
REGISTRY.get_sample_value(
"github_integration_api_rate_limit_reset_timestamp_seconds",
- {"integration_id": str(integration.id), "resource": expected_resource},
+ {"installation_id": integration.integration_id, "resource": expected_resource},
)
== expected_reset
)
@@ -1183,10 +1193,11 @@ class TestGitHubIntegrationModel(BaseTest):
mock_get.side_effect = requests.RequestException("network failure")
labels = {
- "integration_id": str(integration.id),
+ "installation_id": integration.integration_id,
"method": "GET",
"endpoint": "/repos/{owner}/{repo}",
"status_code": "exception",
+ "source": "integration",
}
previous_count = REGISTRY.get_sample_value("github_integration_api_requests_total", labels) or 0
@@ -1208,10 +1219,11 @@ class TestGitHubIntegrationModel(BaseTest):
mock_client_request.side_effect = requests.RequestException("network failure")
labels = {
- "integration_id": str(integration.id),
+ "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
diff --git a/posthog/rate_limiting/github_observability.py b/posthog/rate_limiting/github_observability.py
new file mode 100644
index 000000000000..9e577769c3be
--- /dev/null
+++ b/posthog/rate_limiting/github_observability.py
@@ -0,0 +1,159 @@
+"""GitHub egress telemetry — the first domain registered with the generic observability mechanism.
+
+Every GitHub API client in the codebase funnels its responses through ``record_github_api_response``
+so request volume and GitHub's own ``X-RateLimit-*`` headers land on one metric set, regardless of
+which subsystem made the call (installation integration, warehouse source, Visual review,
+Conversations, ...). The ``source`` label keeps them apart on a single dashboard.
+
+The metric names are kept stable (``github_integration_api_*``) so existing dashboards stay valid;
+the mechanism is the generic :class:`EgressObservability`, so a new outbound API is just another
+adapter module like this one.
+"""
+
+import re
+from collections.abc import Mapping
+from urllib.parse import urlparse
+
+import requests
+from prometheus_client import Counter, Gauge
+
+from posthog.rate_limiting.observability import (
+ EgressMetrics,
+ EgressObservability,
+ RateLimitSnapshot,
+ register_egress_observability,
+)
+
+GITHUB_DOMAIN = "github"
+
+_metrics = EgressMetrics(
+ request_counter=Counter(
+ "github_integration_api_requests",
+ "Number of GitHub API requests made through a GitHub client.",
+ labelnames=["installation_id", "method", "endpoint", "status_code", "source"],
+ ),
+ # Gauges are keyed by installation_id, not integration_id: GitHub meters the rate limit per App
+ # installation, and several PostHog integration rows can share one installation. Keying by the row
+ # would split one real budget into flip-flopping per-row series; the installation is the true budget
+ # owner. Gauges also carry no source label — all sources sharing an installation update one series.
+ remaining_gauge=Gauge(
+ "github_integration_api_rate_limit_remaining",
+ "Most recently observed GitHub API rate limit remaining count by installation and resource.",
+ labelnames=["installation_id", "resource"],
+ ),
+ limit_gauge=Gauge(
+ "github_integration_api_rate_limit_limit",
+ "Most recently observed GitHub API rate limit limit by installation and resource.",
+ labelnames=["installation_id", "resource"],
+ ),
+ reset_gauge=Gauge(
+ "github_integration_api_rate_limit_reset_timestamp_seconds",
+ "Most recently observed GitHub API rate limit reset timestamp by installation and resource.",
+ labelnames=["installation_id", "resource"],
+ ),
+)
+
+
+def _float_header(headers: Mapping[str, str] | None, name: str) -> float | None:
+ if headers is None:
+ return None
+ value = headers.get(name)
+ if value is None:
+ return None
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+
+def _parse_github_rate_limit(response: requests.Response) -> RateLimitSnapshot:
+ headers = response.headers if isinstance(response.headers, Mapping) else None
+ return RateLimitSnapshot(
+ resource=headers.get("X-RateLimit-Resource", "unknown") if headers is not None else "unknown",
+ remaining=_float_header(headers, "X-RateLimit-Remaining"),
+ limit=_float_header(headers, "X-RateLimit-Limit"),
+ reset_at=_float_header(headers, "X-RateLimit-Reset"),
+ )
+
+
+# A git object id (full or abbreviated SHA). Templated so per-commit URLs (/statuses/{sha},
+# /commits/{sha}, git/{blobs,trees,commits}/{sha}) don't each mint a distinct endpoint label.
+_SHA_RE = re.compile(r"\A[0-9a-f]{7,40}\Z")
+
+# Path segments whose *next* segment is free-form to the end of the path (a file path or a compare
+# ref), so everything after them is collapsed to one placeholder rather than kept verbatim.
+_REST_IS_FREEFORM = {"contents": "{path}", "compare": "{refs}"}
+
+
+def _normalize_github_endpoint(url: str | None) -> str:
+ """Collapse a GitHub URL to a low-cardinality endpoint label. Owner/repo, numeric ids, commit
+ SHAs, and free-form tails (file paths, compare refs) are templated out — e.g.
+ ``.../repos/posthog/posthog/actions/runs/42/jobs`` becomes ``/repos/{owner}/{repo}/actions/runs/{id}/jobs``
+ and ``.../repos/o/r/statuses/<sha>`` becomes ``/repos/{owner}/{repo}/statuses/{sha}``.
+
+ The leading-slash, ``{placeholder}`` style matches the curated endpoint strings the installation
+ integration passes (e.g. ``/repos/{owner}/{repo}`` in github_integration_base), so the ``endpoint``
+ label reads consistently whether it's hand-written or derived from a URL. Without this, callers
+ that pass no explicit endpoint (Visual review, warehouse) would emit a unique label per commit
+ SHA / branch / file path and blow up Prometheus cardinality — the thing this layer prevents."""
+ if not url:
+ return "unknown"
+ path = urlparse(url).path.strip("/")
+ if not path:
+ return "/"
+ parts = path.split("/")
+ out: list[str] = []
+ i = 0
+ while i < len(parts):
+ seg = parts[i]
+ # "/repos/{owner}/{repo}/..." — the two segments after "repos" are always owner+repo.
+ if seg == "repos" and i + 2 < len(parts):
+ out.extend(["repos", "{owner}", "{repo}"])
+ i += 3
+ continue
+ # /contents/<file path...> and /compare/<base>...<head>: the remainder is a single free-form
+ # value (and a file path can itself contain slashes), so collapse it and stop.
+ if seg in _REST_IS_FREEFORM and i + 1 < len(parts):
+ out.extend([seg, _REST_IS_FREEFORM[seg]])
+ break
+ if seg.isdigit():
+ out.append("{id}")
+ elif _SHA_RE.match(seg):
+ out.append("{sha}")
+ else:
+ out.append(seg)
+ i += 1
+ return "/" + "/".join(out)
+
+
+github_egress = EgressObservability(
+ GITHUB_DOMAIN, _metrics, _parse_github_rate_limit, endpoint_normalizer=_normalize_github_endpoint
+)
+register_egress_observability(github_egress)
+
+
+def record_github_api_response(
+ response: requests.Response,
+ *,
+ source: str,
+ installation_id: str | None = None,
+ method: str | None = None,
+ endpoint: str | None = None,
+) -> None:
+ """Record one GitHub API response. ``installation_id`` is the GitHub App installation — the shared
+ rate-limit budget GitHub meters. Pass it when known so the rate-limit gauges are set; identity-blind
+ callers (raw PATs) get request volume only. ``source`` attributes the call to a subsystem."""
+ github_egress.record_response(response, source=source, scope=installation_id, method=method, endpoint=endpoint)
+
+
+def record_github_api_exception(
+ *,
+ source: str,
+ method: str,
+ endpoint: str | None = None,
+ url: str | None = None,
+ installation_id: str | None = None,
+) -> None:
+ """Record a request that raised before a response (timeout, connection error). Pass a curated
+ ``endpoint`` or a raw ``url`` (normalised internally)."""
+ github_egress.record_exception(source=source, scope=installation_id, method=method, endpoint=endpoint, url=url)
diff --git a/posthog/rate_limiting/observability.py b/posthog/rate_limiting/observability.py
new file mode 100644
index 000000000000..0aa47f4530e8
--- /dev/null
+++ b/posthog/rate_limiting/observability.py
@@ -0,0 +1,178 @@
+"""Generic outbound API egress observability — the metrics analog of the egress limiter.
+
+Mirrors the limiter's shape (:mod:`posthog.rate_limiting.outbound`): a domain-agnostic mechanism,
+with each third-party API registered as a *domain* that supplies its own metric set and a parser for
+that API's rate-limit response headers. A consumer records a response against a domain; the registered
+:class:`EgressObservability` does the rest.
+
+Each domain keeps its own metric names (rather than one shared namespace) so existing dashboards stay
+valid and every API can name its metrics idiomatically — the reuse is in the recording mechanism, the
+endpoint-normalisation, and the registry, not in a single metric series.
+"""
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from urllib.parse import urlparse
+
+import requests
+from prometheus_client import Counter, Gauge
+
+
+@dataclass(frozen=True)
+class RateLimitSnapshot:
+ """What a domain's parser extracts from one response. Any field may be ``None`` if the API
+ didn't report it on this response (e.g. an error before headers were attached)."""
+
+ resource: str = "unknown"
+ remaining: float | None = None
+ limit: float | None = None
+ reset_at: float | None = None
+
+
+# Parses a response into a RateLimitSnapshot. Per-domain because each API exposes its budget
+# differently (GitHub: X-RateLimit-* headers; others may use different headers or a body field).
+ResponseParser = Callable[[requests.Response], RateLimitSnapshot]
+
+
+@dataclass(frozen=True)
+class EgressMetrics:
+ """The Prometheus instruments one domain records on. The recorder fills labels positionally,
+ so a domain's metrics must declare them in this order: the counter as
+ ``(<scope>, method, endpoint, status_code, source)`` and each gauge as ``(<scope>, resource)``.
+
+ ``<scope>`` is the rate-limit budget owner in the *domain's own* id space — for GitHub the App
+ ``installation_id`` (what GitHub actually meters), never a PostHog DB row id. Keeping the identity in
+ the external API's namespace is what lets one shared budget map to one series: several PostHog
+ integration rows can share a GitHub installation, and they must all land on the same gauge, otherwise
+ one real budget splits into N flip-flopping per-row series. The recorder fills ``<scope>`` from the
+ ``scope`` argument; per-caller attribution is the ``source`` label's job, not the identity's.
+
+ The gauges deliberately carry no ``source``: the budget is shared across sources, so all sources must
+ update one series per (scope, resource). Labeling gauges by source would strand a stale last-observed
+ value per source after that source goes quiet, misreporting remaining budget."""
+
+ request_counter: Counter
+ remaining_gauge: Gauge
+ limit_gauge: Gauge
+ reset_gauge: Gauge
+
+
+def default_normalize_endpoint(url: str | None) -> str:
+ """Collapse a URL path to a low-cardinality endpoint label by templating out numeric ids.
+ Domains with structured paths (e.g. GitHub's owner/repo) can pass their own normaliser."""
+ if not url:
+ return "unknown"
+ path = urlparse(url).path.strip("/")
+ if not path:
+ return "/"
+ return "/" + "/".join("{id}" if seg.isdigit() else seg for seg in path.split("/"))
+
+
+class EgressObservability:
+ """One third-party API's egress telemetry: a metric set, a response parser, and an endpoint
+ normaliser. Construct one per domain and register it; consumers record through it.
+
+ ``scope`` is the rate-limit budget owner in the domain's own id space (e.g. a GitHub App installation
+ id, which several PostHog integrations can share) — not a PostHog DB row id. The counter is always
+ incremented; the gauges are only set when a ``scope`` is given, since a last-observed gauge is
+ meaningless when many owners alias onto one empty label.
+ """
+
+ def __init__(
+ self,
+ domain: str,
+ metrics: EgressMetrics,
+ parser: ResponseParser,
+ endpoint_normalizer: Callable[[str | None], str] = default_normalize_endpoint,
+ ) -> None:
+ self.domain = domain
+ self._metrics = metrics
+ self._parser = parser
+ self._normalize_endpoint = endpoint_normalizer
+
+ def record_response(
+ self,
+ response: requests.Response,
+ *,
+ source: str,
+ scope: str | None = None,
+ method: str | None = None,
+ endpoint: str | None = None,
+ ) -> None:
+ # The response's .request (and its method/url) may be absent or non-string — a response built
+ # without a prepared request, or a test mock whose attributes are themselves Mocks. Coerce to
+ # str-or-None so a recorder never raises into the request flow: telemetry is best-effort, and a
+ # urlparse(Mock) blowing up here must not fail the actual GitHub call.
+ request = getattr(response, "request", None)
+ req_method = getattr(request, "method", None)
+ req_url = getattr(request, "url", None)
+ method_label = (method or (req_method if isinstance(req_method, str) else None) or "GET").upper()
+ endpoint_label = (
+ endpoint
+ if endpoint is not None
+ else self._normalize_endpoint(req_url if isinstance(req_url, str) else None)
+ )
+ self._metrics.request_counter.labels(
+ scope or "", method_label, endpoint_label, str(response.status_code), source
+ ).inc()
+
+ if scope is None:
+ return
+
+ # Gauges are keyed by (scope, resource) only — the shared budget owner, no source. Every
+ # source sharing one budget updates one series; a per-source gauge would strand stale values.
+ snapshot = self._parser(response)
+ if snapshot.remaining is not None:
+ self._metrics.remaining_gauge.labels(scope, snapshot.resource).set(snapshot.remaining)
+ if snapshot.limit is not None:
+ self._metrics.limit_gauge.labels(scope, snapshot.resource).set(snapshot.limit)
+ if snapshot.reset_at is not None:
+ self._metrics.reset_gauge.labels(scope, snapshot.resource).set(snapshot.reset_at)
+
+ def record_exception(
+ self,
+ *,
+ source: str,
+ method: str,
+ endpoint: str | None = None,
+ url: str | None = None,
+ scope: str | None = None,
+ ) -> None:
+ """Record a request that raised before a response (timeout, connection error). Pass a pre-normalised
+ ``endpoint`` or a raw ``url`` (normalised here via the domain's normaliser) — mirrors record_response,
+ so a caller that only holds a URL doesn't need the domain's normaliser."""
+ endpoint_label = endpoint if endpoint is not None else self._normalize_endpoint(url)
+ # Uppercase to match record_response, so a method never splits into two series by case.
+ self._metrics.request_counter.labels(scope or "", method.upper(), endpoint_label, "exception", source).inc()
+
+
+_REGISTRY: dict[str, EgressObservability] = {}
+
+
+def register_egress_observability(observability: EgressObservability) -> None:
+ _REGISTRY[observability.domain] = observability
+
+
+def resolve_egress_observability(domain: str) -> EgressObservability:
+ obs = _REGISTRY.get(domain)
+ if obs is None:
+ raise ValueError(
+ f"No egress observability registered for domain '{domain}'; "
+ "register one with register_egress_observability() before recording against it"
+ )
+ return obs
+
+
+def record_outbound_api_response(
+ response: requests.Response,
+ *,
+ domain: str,
+ source: str,
+ scope: str | None = None,
+ method: str | None = None,
+ endpoint: str | None = None,
+) -> None:
+ """Domain-keyed convenience for generic callers that hold only a domain string."""
+ resolve_egress_observability(domain).record_response(
+ response, source=source, scope=scope, method=method, endpoint=endpoint
+ )
diff --git a/posthog/rate_limiting/test/test_github_observability.py b/posthog/rate_limiting/test/test_github_observability.py
new file mode 100644
index 000000000000..d4c4714e9350
--- /dev/null
+++ b/posthog/rate_limiting/test/test_github_observability.py
@@ -0,0 +1,193 @@
+from unittest.mock import MagicMock
+
+from django.test import SimpleTestCase
+
+import requests
+from parameterized import parameterized
+from prometheus_client import REGISTRY
+from requests.structures import CaseInsensitiveDict
+
+from posthog.rate_limiting.github_observability import (
+ _normalize_github_endpoint,
+ record_github_api_exception,
+ record_github_api_response,
+)
+from posthog.rate_limiting.observability import (
+ default_normalize_endpoint,
+ record_outbound_api_response,
+ resolve_egress_observability,
+)
+
+_COUNTER = "github_integration_api_requests_total"
+_REMAINING = "github_integration_api_rate_limit_remaining"
+
+
+def _response(
+ *,
+ status: int = 200,
+ headers: dict[str, str] | None = None,
+ method: str = "GET",
+ url: str = "https://api.github.com/repos/posthog/posthog/commits",
+) -> requests.Response:
+ response = requests.models.Response()
+ response.status_code = status
+ response.headers = CaseInsensitiveDict(headers or {})
+ prepared = requests.models.PreparedRequest()
+ prepared.method = method
+ prepared.url = url
+ response.request = prepared
+ return response
+
+
+class TestGithubObservability(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("https://api.github.com/repos/posthog/posthog/commits", "/repos/{owner}/{repo}/commits"),
+ (
+ "https://api.github.com/repos/o/r/actions/runs/42/jobs",
+ "/repos/{owner}/{repo}/actions/runs/{id}/jobs",
+ ),
+ ("https://api.github.com/repositories/12345", "/repositories/{id}"),
+ ("https://api.github.com/search/code?q=x", "/search/code"),
+ # Visual review's high-cardinality URLs: commit SHA, compare refs, and file path.
+ (
+ "https://api.github.com/repos/o/r/statuses/a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0",
+ "/repos/{owner}/{repo}/statuses/{sha}",
+ ),
+ ("https://api.github.com/repos/o/r/compare/main...feature", "/repos/{owner}/{repo}/compare/{refs}"),
+ (
+ "https://api.github.com/repos/o/r/contents/.github/visual-review.yml",
+ "/repos/{owner}/{repo}/contents/{path}",
+ ),
+ (None, "unknown"),
+ ]
+ )
+ def test_normalize_endpoint_bounds_cardinality(self, url: str | None, expected: str) -> None:
+ self.assertEqual(_normalize_github_endpoint(url), expected)
+
+ @parameterized.expand(
+ [
+ ("https://example.com/v1/widgets/42", "/v1/widgets/{id}"),
+ ("https://example.com/", "/"),
+ (None, "unknown"),
+ ]
+ )
+ def test_default_normalizer_collapses_numeric_ids(self, url: str | None, expected: str) -> None:
+ self.assertEqual(default_normalize_endpoint(url), expected)
+
+ def test_records_counter_and_gauges_when_installation_id_known(self) -> None:
+ before = REGISTRY.get_sample_value(
+ _COUNTER,
+ {
+ "installation_id": "42",
+ "method": "GET",
+ "endpoint": "/repos/{owner}/{repo}/commits",
+ "status_code": "200",
+ "source": "unit-known",
+ },
+ )
+ record_github_api_response(
+ _response(headers={"X-RateLimit-Remaining": "4321", "X-RateLimit-Resource": "core"}),
+ source="unit-known",
+ installation_id="42",
+ )
+
+ after = REGISTRY.get_sample_value(
+ _COUNTER,
+ {
+ "installation_id": "42",
+ "method": "GET",
+ "endpoint": "/repos/{owner}/{repo}/commits",
+ "status_code": "200",
+ "source": "unit-known",
+ },
+ )
+ self.assertEqual((after or 0) - (before or 0), 1)
+ self.assertEqual(
+ REGISTRY.get_sample_value(_REMAINING, {"installation_id": "42", "resource": "core"}),
+ 4321,
+ )
+
+ def test_skips_gauges_when_identity_unknown(self) -> None:
+ # Identity-blind callers (raw-token sources) must not set the per-installation gauge — otherwise
+ # many installations alias onto the empty installation_id and the last write wins, misleadingly.
+ record_github_api_response(
+ _response(headers={"X-RateLimit-Remaining": "10", "X-RateLimit-Resource": "core"}),
+ source="unit-blind",
+ )
+ self.assertIsNone(REGISTRY.get_sample_value(_REMAINING, {"installation_id": "", "resource": "core"}))
+ self.assertEqual(
+ REGISTRY.get_sample_value(
+ _COUNTER,
+ {
+ "installation_id": "",
+ "method": "GET",
+ "endpoint": "/repos/{owner}/{repo}/commits",
+ "status_code": "200",
+ "source": "unit-blind",
+ },
+ ),
+ 1,
+ )
+
+ def test_generic_resolver_routes_to_github(self) -> None:
+ self.assertIs(resolve_egress_observability("github").domain, "github")
+ record_outbound_api_response(
+ _response(status=403, url="https://api.github.com/search/code"),
+ domain="github",
+ source="unit-generic",
+ )
+ self.assertEqual(
+ REGISTRY.get_sample_value(
+ _COUNTER,
+ {
+ "installation_id": "",
+ "method": "GET",
+ "endpoint": "/search/code",
+ "status_code": "403",
+ "source": "unit-generic",
+ },
+ ),
+ 1,
+ )
+
+ def test_unregistered_domain_raises(self) -> None:
+ with self.assertRaises(ValueError):
+ resolve_egress_observability("definitely-not-registered")
+
+ def test_records_without_crashing_when_request_is_a_mock(self) -> None:
+ # A MagicMock response auto-vivifies .request.url / .request.method as Mocks (non-str);
+ # the recorder must coerce them to defaults, not raise urlparse(Mock) into the caller.
+ response = MagicMock()
+ response.status_code = 200
+ response.headers = CaseInsensitiveDict({})
+ record_github_api_response(response, source="unit-mockreq")
+ self.assertEqual(
+ REGISTRY.get_sample_value(
+ _COUNTER,
+ {
+ "installation_id": "",
+ "method": "GET",
+ "endpoint": "unknown",
+ "status_code": "200",
+ "source": "unit-mockreq",
+ },
+ ),
+ 1,
+ )
+
+ def test_exception_record_uppercases_method(self) -> None:
+ record_github_api_exception(source="unit-exc", method="get", endpoint="/foo")
+ self.assertEqual(
+ REGISTRY.get_sample_value(
+ _COUNTER,
+ {
+ "installation_id": "",
+ "method": "GET",
+ "endpoint": "/foo",
+ "status_code": "exception",
+ "source": "unit-exc",
+ },
+ ),
+ 1,
+ )
diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.py
index 5cae5d9393eb..dbf04632df62 100644
--- a/products/conversations/backend/tasks.py
+++ b/products/conversations/backend/tasks.py
@@ -23,6 +23,7 @@ from posthog.models.activity_logging.activity_log import Change, Detail, log_act
from posthog.models.comment import Comment as CommentModel
from posthog.models.team import Team
from posthog.models.uploaded_media import UploadedMedia
+from posthog.rate_limiting.github_observability import record_github_api_response
from posthog.scoping_audit import skip_team_scope_audit
from posthog.storage import object_storage
@@ -1791,6 +1792,7 @@ def post_reply_to_github(
},
timeout=15,
)
+ record_github_api_response(resp, source="conversations", installation_id=github.github_installation_id)
if resp.status_code not in (200, 201):
logger.warning(
"github_reply_post_failed",
@@ -1862,6 +1864,7 @@ def create_github_issue(
},
timeout=15,
)
+ record_github_api_response(resp, source="conversations", installation_id=github.github_installation_id)
resp.raise_for_status()
except requests.RequestException as e:
logger.exception("github_create_issue_failed", repo=repo, error=str(e))
diff --git a/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py b/products/error_tracking/backend/presentation/views/git_provider_file_link_resolver.py
index 763118fcc0ce..b4d34f9a8b0b 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
@@ -12,6 +12,7 @@ from rest_framework.response import Response
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.utils import action
from posthog.models.integration import GitHubIntegration, GitLabIntegration, Integration
+from posthog.rate_limiting.github_observability import record_github_api_response
logger = structlog.get_logger(__name__)
@@ -73,8 +74,13 @@ 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) -> str | None:
- """Search GitHub code using the Code Search API. Returns URL to first match or None."""
+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.
+
+ ``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)."""
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)
@@ -88,6 +94,7 @@ def get_github_file_url(code_sample: str, token: str, owner: str, repository: st
try:
response = requests.get(url, headers=headers, timeout=10)
+ record_github_api_response(response, source="error_tracking", installation_id=installation_id)
if response.status_code == 200:
data = response.json()
@@ -209,6 +216,7 @@ class GitProviderFileLinksViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
owner=owner,
repository=repository,
file_name=file_name,
+ installation_id=github.github_installation_id,
)
if url:
return Response({"found": True, "url": url})
diff --git a/products/visual_review/backend/github.py b/products/visual_review/backend/github.py
index 742678237830..c8307adc6dd9 100644
--- a/products/visual_review/backend/github.py
+++ b/products/visual_review/backend/github.py
@@ -11,6 +11,7 @@ import requests
import structlog
from posthog.models.integration import GITHUB_API_VERSION, GitHubRateLimitError, raise_if_github_rate_limited
+from posthog.rate_limiting.github_observability import record_github_api_response
logger = structlog.get_logger(__name__)
@@ -19,10 +20,15 @@ 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.
"""
headers = {
@@ -34,6 +40,8 @@ def github_request(
response = requests.request(method, url, headers=headers, **kwargs)
+ # source="visual_review"; the existing structlog lines below stay for low-remaining alerts.
+ record_github_api_response(response, source="visual_review", installation_id=installation_id)
_log_rate_limit_headers(response, method, url)
_check_rate_limit_response(response, method, url)
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
index 72de2e9d2710..67249a75eff1 100644
--- a/products/visual_review/backend/logic.py
+++ b/products/visual_review/backend/logic.py
@@ -434,6 +434,7 @@ def _get_merge_base_sha(github: GitHubIntegration, repo_full_name: str, base: st
"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,
)
except requests.RequestException:
@@ -473,6 +474,7 @@ def _get_default_branch(github: GitHubIntegration, repo_full_name: str) -> str:
"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:
@@ -1384,6 +1386,7 @@ def _resolve_repo_by_id(github, repo_external_id: int) -> str | None:
"GET",
f"https://api.github.com/repositories/{repo_external_id}",
access_token=access_token,
+ installation_id=github.github_installation_id,
timeout=10,
)
if response.status_code == 200:
@@ -1415,7 +1418,9 @@ def _github_api_request(
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, **kwargs)
+ response = github_request(
+ method, url, access_token=access_token, installation_id=github.github_installation_id, **kwargs
+ )
if response.status_code == 404 and repo.repo_external_id:
new_full_name = _resolve_repo_by_id(github, repo.repo_external_id)
@@ -1430,7 +1435,9 @@ def _github_api_request(
repo.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, **kwargs)
+ response = github_request(
+ method, url, access_token=access_token, installation_id=github.github_installation_id, **kwargs
+ )
return response
@@ -1449,6 +1456,7 @@ def _get_pr_info(github, repo_full_name: str, pr_number: int) -> dict:
"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,
)
@@ -1484,6 +1492,7 @@ def _fetch_baseline_file(
"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,
)
@@ -1608,6 +1617,7 @@ def _post_commit_status(
"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={
"state": state,
"description": description[:140],
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.py
index 6f25759185e8..99c0f949ee09 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/github/github.py
@@ -15,6 +15,7 @@ from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_
from urllib3.util.retry import Retry
from posthog.models.integration import GitHubRateLimitError, raise_if_github_rate_limited
+from posthog.rate_limiting.github_observability import record_github_api_exception, record_github_api_response
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
@@ -367,7 +368,20 @@ def _github_retry_wait(state: RetryCallState) -> float:
reraise=True,
)
def _fetch_page(page_url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> requests.Response:
- response = make_tracked_session(retry=_NO_ADAPTER_RETRY).get(page_url, headers=headers, timeout=60)
+ # Record transport failures (ReadTimeout/ConnectionError from the retry tuple) too, so a GitHub
+ # connectivity incident doesn't silently zero out warehouse telemetry exactly when it matters. Best
+ # effort — the recorder never raises, and we re-raise the original error untouched.
+ try:
+ response = make_tracked_session(retry=_NO_ADAPTER_RETRY).get(page_url, headers=headers, timeout=60)
+ except requests.RequestException:
+ record_github_api_exception(source="warehouse", method="GET", url=page_url)
+ raise
+
+ # Record before the branching below so rate-limited (403/429) and error responses count too.
+ # This source authenticates with a raw token and has no installation id in scope, so it records
+ # request volume only (source="warehouse"); the per-installation gauges stay with callers that
+ # know their installation.
+ record_github_api_response(response, source="warehouse")
# Transient server errors: retry with plain exponential backoff.
if response.status_code >= 500:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py b/products/warehouse_sources/backend/temporal/data_imports/sources/github/tests/test_github_fetch_page.py
index 349410d8c428..8c3cf8f80072 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
@@ -2,6 +2,7 @@ import pytest
from unittest import mock
import requests
+from prometheus_client import REGISTRY
from products.warehouse_sources.backend.temporal.data_imports.sources.github import github
@@ -37,8 +38,20 @@ def test_fetch_page_reraises_chunked_encoding_error_after_exhausting_retries():
session = mock.Mock()
session.get.side_effect = [requests.exceptions.ChunkedEncodingError("Connection broken")] * 5
+ exception_labels = {
+ "installation_id": "",
+ "method": "GET",
+ "endpoint": "/repos/{owner}/{repo}/issues",
+ "status_code": "exception",
+ "source": "warehouse",
+ }
+ before = REGISTRY.get_sample_value("github_integration_api_requests_total", exception_labels) or 0
+
with mock.patch.object(github, "make_tracked_session", return_value=session):
with pytest.raises(requests.exceptions.ChunkedEncodingError):
github._fetch_page("https://api.github.com/repos/o/r/issues", {}, mock.Mock())
assert session.get.call_count == 5
+ # Every transport failure is recorded, so a GitHub outage doesn't silently zero warehouse telemetry.
+ after = REGISTRY.get_sample_value("github_integration_api_requests_total", exception_labels) or 0
+ assert after - before == session.get.call_count