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.

fix(warehouse): skip GitHub's code_frequency stats when a repo exceeds 10k commits (#75949)

Tom Owers3aab337bb094
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 757208eae30a..59c6595263a3 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
@@ -78,6 +78,15 @@ class GithubOrgNotFoundError(Exception):
pass
+class GithubRepositoryTooLargeError(Exception):
+ """GitHub's /stats/code_frequency permanently 422s once a repository passes 10,000 commits — a
+ documented limit of that specific endpoint (other stats endpoints keep working, just with
+ zeroed addition/deletion counts for large repos). Retrying can never succeed, so `_fetch_page`
+ raises this and the caller syncs zero rows instead of failing the schema forever."""
+
+ pass
+
+
@dataclasses.dataclass
class GithubResumeConfig:
next_url: str
@@ -245,6 +254,20 @@ def _is_empty_repository_response(response: requests.Response) -> bool:
return isinstance(message, str) and "repository is empty" in message.lower()
+def _is_repository_too_large_for_code_frequency(response: requests.Response) -> bool:
+ """GitHub returns 422 on /stats/code_frequency with a stable "must have fewer than 10000
+ commits" message once a repository crosses that commit count — a hard, permanent limit of this
+ one endpoint, not a transient or credential problem."""
+ if response.status_code != 422:
+ return False
+ try:
+ body = response.json()
+ message = body.get("message", "") if isinstance(body, dict) else ""
+ except (ValueError, TypeError):
+ message = response.text or ""
+ return isinstance(message, str) and "fewer than 10000 commits" in message.lower()
+
+
def _as_utc(dt: datetime) -> datetime:
"""Treat naive datetimes as UTC so tz-aware values (GitHub returns ISO 8601
with `Z`) can be safely compared against naive cutoffs from the DB."""
@@ -676,6 +699,9 @@ def _fetch_page(
if _is_empty_repository_response(response):
raise GithubEmptyRepositoryError()
+ if _is_repository_too_large_for_code_frequency(response):
+ raise GithubRepositoryTooLargeError()
+
# An org-scoped endpoint 404s when the repo owner is a user (no org) or the token lacks org
# access. Signal it so the caller syncs zero rows rather than failing the schema — a benign skip
# like an empty repository, not a real "repository not found".
@@ -996,6 +1022,9 @@ def get_rows(
except GithubOrgNotFoundError:
logger.debug(f"Github: no accessible org teams for {endpoint}, syncing zero rows: url={url}")
break
+ except GithubRepositoryTooLargeError:
+ logger.debug(f"Github: repository too large for code frequency stats, syncing zero rows: url={url}")
+ break
# The /stats/* aggregates are computed asynchronously: GitHub answers 202 with no body
# while a fresh computation runs. Nothing to sync this time; the next sync picks it up.
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 f6b128775720..d58d32440d7b 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
@@ -1,3 +1,5 @@
+import json
+
import pytest
from unittest import mock
@@ -62,6 +64,42 @@ def test_fetch_page_404_skips_only_for_org_scoped_endpoints(skip_on_not_found, e
)
+def _unprocessable_response(message: str) -> mock.Mock:
+ response = mock.Mock(spec=requests.Response)
+ response.status_code = 422
+ response.ok = False
+ response.headers = {}
+ response.text = json.dumps({"message": message})
+ response.json.return_value = {"message": message}
+ response.request = None
+ response.raise_for_status.side_effect = requests.exceptions.HTTPError(
+ "422 Client Error: Unprocessable Entity for url", response=response
+ )
+ return response
+
+
+def test_fetch_page_raises_repository_too_large_for_code_frequency_422():
+ # GitHub permanently 422s /stats/code_frequency once a repo passes 10,000 commits; the caller
+ # must treat this as a benign skip, not crash and retry the activity forever.
+ session = mock.Mock()
+ session.request.return_value = _unprocessable_response("repository must have fewer than 10000 commits")
+
+ with mock.patch.object(github, "make_tracked_session", return_value=session):
+ with pytest.raises(github.GithubRepositoryTooLargeError):
+ github._fetch_page("https://api.github.com/repos/o/r/stats/code_frequency", {}, mock.Mock())
+
+
+def test_fetch_page_reraises_other_422_errors():
+ # A generic 422 (e.g. malformed request params) is a real, fixable problem and must stay fatal
+ # rather than being swallowed by the too-large-repository check.
+ session = mock.Mock()
+ session.request.return_value = _unprocessable_response("Validation failed")
+
+ with mock.patch.object(github, "make_tracked_session", return_value=session):
+ with pytest.raises(requests.exceptions.HTTPError):
+ github._fetch_page("https://api.github.com/repos/o/r/stats/code_frequency", {}, mock.Mock())
+
+
def test_fetch_page_retries_chunked_encoding_error():
session = mock.Mock()
session.request.side_effect = [requests.exceptions.ChunkedEncodingError("Connection broken"), _ok_response()]