fix(fetcher): guard REST calls so a rate limit can't poison user records

The five REST calls parsed `.json()` with no status check, so a 403
{"message": "API rate limit exceeded..."} body was returned as user data.
`_is_github_not_found` only matched "Not Found", so it was recorded as a
successful fetch and upsert_user overwrote the user's last-good row. Every
user touched during the exhaustion window then served a blank card for up
to 24h while /metrics reported ok.

Reuse the existing `_raise_if_transient` on all five so exhaustion raises
GitHubTransientError before the upsert, preserving last-good and letting
the caller retry. `_raise_if_transient` was GraphQL-shaped and crashed on
the JSON arrays the list endpoints return, so it now ignores non-dict
bodies. A rate limit inside the per-repo fan-out aborts the fetch; a 404
on a single repo stays non-fatal.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BwMoSbmK77Ph7XaV5YnAdS
This commit is contained in:
shay
2026-08-22 16:10:26 -07:00
co-authored by Claude Opus 5
parent eea1734a04
commit 06ab1c878e
4 changed files with 181 additions and 6 deletions
+6
View File
@@ -242,6 +242,12 @@ def _is_github_not_found(data: dict) -> bool:
return True return True
if isinstance(user, dict) and user.get("message") == "Not Found": if isinstance(user, dict) and user.get("message") == "Not Found":
return True return True
# An error body (rate limit, abuse detection, anything else GitHub answers
# with a bare {"message": ...}) carries no login. It is not user data and
# must never be recorded as a successful fetch. github.py raises
# GitHubTransientError before we get here in practice; this is the backstop.
if isinstance(user, dict) and "login" not in user:
return True
return False return False
+28 -6
View File
@@ -58,12 +58,18 @@ def _raise_if_transient(resp) -> None:
# budget at 0 (or a "secondary rate limit" message). # budget at 0 (or a "secondary rate limit" message).
if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining") == "0": if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining") == "0":
raise GitHubTransientError("REST rate limit exhausted") raise GitHubTransientError("REST rate limit exhausted")
if resp.status_code == 403 and "rate limit" in (resp.text or "").lower():
raise GitHubTransientError("REST rate limit exhausted")
# GraphQL reports rate limits as HTTP 200 with an `errors` array — the same # GraphQL reports rate limits as HTTP 200 with an `errors` array — the same
# 200 that a valid response uses — so the body has to be inspected. # 200 that a valid response uses — so the body has to be inspected.
try: try:
body = resp.json() body = resp.json()
except ValueError: except ValueError:
return return
# REST list endpoints (events, repos, contributors) answer with a JSON
# array — only a GraphQL-shaped object can carry an `errors` block.
if not isinstance(body, dict):
return
for err in (body.get("errors") or []): for err in (body.get("errors") or []):
if err.get("type") in ("RATE_LIMITED", "SERVICE_UNAVAILABLE"): if err.get("type") in ("RATE_LIMITED", "SERVICE_UNAVAILABLE"):
raise GitHubTransientError(err.get("message") or err.get("type")) raise GitHubTransientError(err.get("message") or err.get("type"))
@@ -163,23 +169,27 @@ class DirectAPISource:
def fetch_user_data(self, username: str) -> dict: def fetch_user_data(self, username: str) -> dict:
"""Fetch user profile data.""" """Fetch user profile data."""
_assert_username(username) _assert_username(username)
return requests.get( resp = requests.get(
f"{self.base}/users/{username}", f"{self.base}/users/{username}",
headers=self.headers, headers=self.headers,
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
).json() )
_raise_if_transient(resp)
return resp.json()
def fetch_repos(self, username: str) -> list: def fetch_repos(self, username: str) -> list:
"""Fetch user repositories (owned + contributed to).""" """Fetch user repositories (owned + contributed to)."""
_assert_username(username) _assert_username(username)
def _get(repo_type: str): def _get(repo_type: str):
return requests.get( resp = requests.get(
f"{self.base}/users/{username}/repos", f"{self.base}/users/{username}/repos",
headers=self.headers, headers=self.headers,
params={"per_page": 100, "sort": "pushed", "type": repo_type}, params={"per_page": 100, "sort": "pushed", "type": repo_type},
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
).json() )
_raise_if_transient(resp)
return resp.json()
# The two REST calls are independent — fire them in parallel so the # The two REST calls are independent — fire them in parallel so the
# second isn't waiting on the first to come back. # second isn't waiting on the first to come back.
@@ -209,8 +219,10 @@ class DirectAPISource:
headers=self.headers, headers=self.headers,
params={"per_page": 100}, params={"per_page": 100},
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
).json() )
return resp if isinstance(resp, list) else [] _raise_if_transient(resp)
events = resp.json()
return events if isinstance(events, list) else []
def fetch_commits(self, username: str, repos: list = None) -> list: def fetch_commits(self, username: str, repos: list = None) -> list:
""" """
@@ -529,6 +541,7 @@ class DirectAPISource:
timeout=config.API_TIMEOUT timeout=config.API_TIMEOUT
) )
_raise_if_transient(resp)
if resp.ok: if resp.ok:
contributors = resp.json() contributors = resp.json()
# Filter by minimum commits # Filter by minimum commits
@@ -536,6 +549,8 @@ class DirectAPISource:
c for c in contributors c for c in contributors
if c.get("contributions", 0) >= min_commits if c.get("contributions", 0) >= min_commits
] ]
except GitHubTransientError:
raise
except Exception as e: except Exception as e:
print(f"Warning: Failed to fetch contributors from {repo_name}: {e}") print(f"Warning: Failed to fetch contributors from {repo_name}: {e}")
@@ -622,9 +637,12 @@ class DirectAPISource:
headers=self.headers, headers=self.headers,
timeout=config.API_TIMEOUT, timeout=config.API_TIMEOUT,
) )
_raise_if_transient(resp)
if resp.ok: if resp.ok:
data = resp.json() data = resp.json()
return data if isinstance(data, dict) else {} return data if isinstance(data, dict) else {}
except GitHubTransientError:
raise
except Exception: except Exception:
pass pass
return {} return {}
@@ -729,6 +747,8 @@ def _enrich_repo_languages(repos: list, source: GitHubDataSource) -> None:
i = futures[fut] i = futures[fut]
try: try:
repos[i]["language_bytes"] = fut.result() or {} repos[i]["language_bytes"] = fut.result() or {}
except GitHubTransientError:
raise
except Exception: except Exception:
repos[i]["language_bytes"] = {} repos[i]["language_bytes"] = {}
@@ -803,6 +823,8 @@ def _fetch_collaborators_data(
full_name = futures[fut] full_name = futures[fut]
try: try:
contributors_by_repo[full_name] = fut.result() or [] contributors_by_repo[full_name] = fut.result() or []
except GitHubTransientError:
raise
except Exception as e: except Exception as e:
print(f" failed to fetch contributors for {full_name}: {e}") print(f" failed to fetch contributors for {full_name}: {e}")
contributors_by_repo[full_name] = [] contributors_by_repo[full_name] = []
+11
View File
@@ -192,3 +192,14 @@ def test_fetch_async_dedupes_inflight(client, monkeypatch):
break break
threading.Event().wait(0.05) threading.Event().wait(0.05)
assert fetch_calls["n"] == 1 assert fetch_calls["n"] == 1
def test_rate_limit_body_is_not_classified_as_valid_user_data():
# A rate-limit body reaching the classifier must never take the success
# branch — that is what overwrote a good record with a blank card.
data = {"user": {"message": "API rate limit exceeded for user ID 123.",
"documentation_url": "https://docs.github.com/"}}
assert apimod._is_github_not_found(data) is True
assert apimod._is_github_not_found({"user": {"login": "alice"}}) is False
assert apimod._is_github_not_found({"user": {"message": "Not Found"}}) is True
assert apimod._is_github_not_found({"user": None}) is True
+136
View File
@@ -114,3 +114,139 @@ def test_commit_count_zero_on_not_found_is_not_transient():
) )
src = github.DirectAPISource(token="t") src = github.DirectAPISource(token="t")
assert src.fetch_commit_count("ghost", []) == 0 assert src.fetch_commit_count("ghost", []) == 0
# --- REST rate-limit guards -------------------------------------------------
# The REST calls used to hand `.json()` straight back, so a 403 rate-limit body
# ({"message": "API rate limit exceeded for user ID ..."}) was persisted as if
# it were real data, wiping the user's last-good record for up to 24h.
RATE_LIMIT_BODY = {
"message": "API rate limit exceeded for user ID 123.",
"documentation_url": "https://docs.github.com/rest/overview/rate-limits",
}
RATE_LIMIT_HEADERS = {"X-RateLimit-Remaining": "0"}
@responses.activate
def test_fetch_user_data_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/users/alice",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_user_data("alice")
@responses.activate
def test_fetch_user_data_raises_on_rate_limit_without_header():
# Secondary rate limits come back as 403 without the remaining-budget
# header — the message is the only signal.
responses.add(
responses.GET, "https://api.github.com/users/alice",
json={"message": "You have exceeded a secondary rate limit."}, status=403,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_user_data("alice")
@responses.activate
def test_fetch_repos_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/users/alice/repos",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_repos("alice")
@responses.activate
def test_fetch_events_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/users/alice/events",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_events("alice")
@responses.activate
def test_fetch_repo_contributors_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/contributors",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_repo_contributors("alice/proj")
@responses.activate
def test_fetch_repo_languages_raises_on_rest_rate_limit():
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/languages",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
with pytest.raises(github.GitHubTransientError):
src.fetch_repo_languages("alice/proj")
@responses.activate
def test_single_repo_404_stays_non_fatal():
# A deleted/renamed repo is a real per-repo answer, not a budget problem:
# it must keep degrading gracefully instead of aborting the whole fetch.
responses.add(
responses.GET, "https://api.github.com/repos/alice/gone/languages",
json={"message": "Not Found"}, status=404,
)
responses.add(
responses.GET, "https://api.github.com/repos/alice/gone/contributors",
json={"message": "Not Found"}, status=404,
)
src = github.DirectAPISource(token="t")
assert src.fetch_repo_languages("alice/gone") == {}
assert src.fetch_repo_contributors("alice/gone") == []
@responses.activate
def test_rest_success_path_unchanged():
responses.add(
responses.GET, "https://api.github.com/users/alice",
json={"login": "alice", "followers": 5}, status=200,
)
responses.add(
responses.GET, "https://api.github.com/users/alice/events",
json=[{"type": "PushEvent"}], status=200,
)
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/languages",
json={"Python": 100}, status=200,
)
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/contributors",
json=[{"login": "bob", "contributions": 4}], status=200,
)
src = github.DirectAPISource(token="t")
assert src.fetch_user_data("alice")["login"] == "alice"
assert src.fetch_events("alice") == [{"type": "PushEvent"}]
assert src.fetch_repo_languages("alice/proj") == {"Python": 100}
assert src.fetch_repo_contributors("alice/proj") == [{"login": "bob", "contributions": 4}]
@responses.activate
def test_rate_limited_repo_languages_aborts_whole_fetch():
# A rate limit inside the per-repo fan-out means the budget is gone, so it
# must propagate rather than being swallowed into an empty breakdown.
responses.add(
responses.GET, "https://api.github.com/repos/alice/proj/languages",
json=RATE_LIMIT_BODY, status=403, headers=RATE_LIMIT_HEADERS,
)
src = github.DirectAPISource(token="t")
repos = [{"full_name": "alice/proj"}]
with pytest.raises(github.GitHubTransientError):
github._enrich_repo_languages(repos, src)