fix(fetcher): keep last-good counts on GitHub rate limits + expose fetch metrics

Rate-limited / 5xx / network failures were silently returning 0 from the
commit- and PR-count paths, then overwriting good values in fetcher.db —
turning a traffic spike into permanently-wrong "0 commits" cards. Raise
GitHubTransientError instead so the fetch aborts and the last-good row is
retained; genuine NOT_FOUND still yields 0.

Add a shared fetch-outcome counter (fetch_metrics table, spanning the web
workers and the cron container) surfaced at an unauthenticated GET /metrics
as ghstats_fetch_total{outcome="ok|not_found|rate_limited|error"}, so rate
limits are visible to the monitoring stack instead of dying silently.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
shay
2026-07-18 11:45:42 -07:00
co-authored by Claude Opus 4.8
parent d1e89fb1c3
commit 0586f83a33
8 changed files with 227 additions and 4 deletions
+38 -4
View File
@@ -58,6 +58,24 @@ def health():
return jsonify({"status": "ok", "service": "fetcher", "users": len(db.list_usernames())})
@app.route("/metrics", methods=["GET"])
def metrics():
"""Prometheus-format fetch-outcome counters for the monitoring stack.
Deliberately unauthenticated (the rest of the API requires the internal
token): it exposes only aggregate counts — no usernames, no payloads — and
the scraper (vmagent) can't send our internal header. The counts are read
from fetcher.db, so they include the cron container's fetches too."""
counts = db.read_fetch_metrics()
lines = [
"# HELP ghstats_fetch_total GitHub fetch outcomes by result.",
"# TYPE ghstats_fetch_total counter",
]
for outcome, n in counts.items():
lines.append(f'ghstats_fetch_total{{outcome="{outcome}"}} {n}')
return Response("\n".join(lines) + "\n", mimetype="text/plain; version=0.0.4")
@app.route("/data/<username>", methods=["GET"])
@require_internal_token
def get_data(username: str):
@@ -98,17 +116,19 @@ def force_fetch():
t0 = time.monotonic()
try:
data = github.fetch_github_data(username, token=config.GITHUB_PAT)
except Exception:
except Exception as e:
# Previously returned f"fetch failed: {e}" which leaks internal
# exception text (URLs, stack fragments) across the trust boundary.
analytics.record_fetch(username, 502, int((time.monotonic() - t0) * 1000))
log.exception("github fetch failed for %s", username)
_record_fetch_failure(username, e)
return jsonify({"error": "fetch_failed"}), 502
if _is_github_not_found(data):
data = {"error": "not_found"}
analytics.record_fetch(username, 404, int((time.monotonic() - t0) * 1000))
db.bump_fetch_metric("not_found")
else:
analytics.record_fetch(username, 200, int((time.monotonic() - t0) * 1000))
db.bump_fetch_metric("ok")
old = db.get_user(username)
old_hash = old["payload_hash"] if old else None
new_hash = db.upsert_user(username, data)
@@ -132,13 +152,15 @@ def _bg_fetch(username: str) -> None:
if _is_github_not_found(data):
data = {"error": "not_found"}
analytics.record_fetch(username, 404, int((time.monotonic() - t0) * 1000))
db.bump_fetch_metric("not_found")
else:
analytics.record_fetch(username, 200, int((time.monotonic() - t0) * 1000))
db.bump_fetch_metric("ok")
payload_hash = db.upsert_user(username, data)
ok = True
except Exception:
except Exception as e:
analytics.record_fetch(username, 502, int((time.monotonic() - t0) * 1000))
log.exception("background fetch failed for %s", username)
_record_fetch_failure(username, e)
payload_hash = ""
ok = False
_notify_generator_data_ready(username, payload_hash, ok)
@@ -223,6 +245,18 @@ def _is_github_not_found(data: dict) -> bool:
return False
def _record_fetch_failure(username: str, exc: Exception) -> None:
"""Classify a failed fetch for metrics + logs. A transient failure (rate
limit / 5xx / network) is the signal worth surfacing: it means we aborted
and kept the last-good record instead of persisting zeros."""
if isinstance(exc, github.GitHubTransientError):
db.bump_fetch_metric("rate_limited")
log.warning("github fetch transient failure for %s (kept last-good): %s", username, exc)
else:
db.bump_fetch_metric("error")
log.exception("github fetch failed for %s", username)
def main():
db.init_db()
app.run(host="0.0.0.0", port=config.PORT)
+8
View File
@@ -18,9 +18,17 @@ def tick(hours: int, active_within_days: int, gc_days: int) -> dict:
user = data.get("user")
if user is None or (isinstance(user, dict) and user.get("message") == "Not Found"):
data = {"error": "not_found"}
db.bump_fetch_metric("not_found")
else:
db.bump_fetch_metric("ok")
db.upsert_user(username, data)
refreshed += 1
except github.GitHubTransientError as e:
db.bump_fetch_metric("rate_limited")
log.warning("refresh rate-limited for %s (kept last-good): %s", username, e)
failed += 1
except Exception as e:
db.bump_fetch_metric("error")
log.warning("refresh failed for %s: %s", username, e)
failed += 1
gc_removed = db.delete_stale(days=gc_days)
+44
View File
@@ -25,8 +25,20 @@ CREATE TABLE IF NOT EXISTS users (
);
CREATE INDEX IF NOT EXISTS idx_users_fetched_at ON users(fetched_at);
CREATE INDEX IF NOT EXISTS idx_users_last_requested_at ON users(last_requested_at);
-- Monotonic fetch-outcome counters, shared across the web workers and the
-- cron container (both mount the same fetcher.db). Scraped via /metrics so
-- rate limits surface in the monitoring stack instead of dying silently.
CREATE TABLE IF NOT EXISTS fetch_metrics (
outcome TEXT PRIMARY KEY,
count INTEGER NOT NULL DEFAULT 0
);
"""
# The full label set is emitted even at zero so the counter exists in the
# scrape target from the first request (rate() needs a prior sample to work).
FETCH_OUTCOMES = ("ok", "not_found", "rate_limited", "error")
def _now() -> str:
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
@@ -119,3 +131,35 @@ def users_due_for_refresh(hours: int, active_within_days: int) -> list[str]:
def list_usernames() -> list[str]:
with _connect() as c:
return [r["username"] for r in c.execute("SELECT username FROM users ORDER BY username").fetchall()]
def bump_fetch_metric(outcome: str, n: int = 1) -> None:
"""Increment the counter for a fetch outcome (one of FETCH_OUTCOMES).
Best-effort telemetry: a metrics write must never break a fetch, so
failures are swallowed."""
if outcome not in FETCH_OUTCOMES:
outcome = "error"
try:
with _connect() as c:
c.execute(
"""INSERT INTO fetch_metrics(outcome, count) VALUES (?, ?)
ON CONFLICT(outcome) DO UPDATE SET count = count + excluded.count""",
(outcome, n),
)
c.commit()
except sqlite3.Error:
pass
def read_fetch_metrics() -> dict:
"""Return {outcome: count} for every outcome in FETCH_OUTCOMES (zero-filled)."""
counts = {o: 0 for o in FETCH_OUTCOMES}
try:
with _connect() as c:
for row in c.execute("SELECT outcome, count FROM fetch_metrics"):
if row["outcome"] in counts:
counts[row["outcome"]] = row["count"]
except sqlite3.Error:
pass
return counts
+48
View File
@@ -36,6 +36,39 @@ def _assert_repo_full_name(name: str) -> str:
return name
class GitHubTransientError(Exception):
"""A GitHub call failed transiently (rate limit, 5xx, or a network error)
rather than returning real data.
This MUST NOT be swallowed into a zero/empty count. A contribution count
computed from a rate-limited response is 0, and persisting that 0 silently
overwrites the last good value in fetcher.db — which is exactly how a
traffic spike turns into permanently-wrong "0 commits" cards until the
next successful fetch. Propagate it instead so the caller aborts the fetch
and keeps the previously-cached record."""
def _raise_if_transient(resp) -> None:
"""Raise GitHubTransientError if `resp` looks like a rate limit or server
error. A genuine NOT_FOUND (unknown user) is left alone — that is a real,
persistable "this user has no data" answer, not a transient failure."""
if resp.status_code in (429, 500, 502, 503, 504):
raise GitHubTransientError(f"HTTP {resp.status_code}")
# Primary/secondary REST rate limits come back as 403 with the remaining
# budget at 0 (or a "secondary rate limit" message).
if resp.status_code == 403 and resp.headers.get("X-RateLimit-Remaining") == "0":
raise GitHubTransientError("REST rate limit exhausted")
# 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.
try:
body = resp.json()
except ValueError:
return
for err in (body.get("errors") or []):
if err.get("type") in ("RATE_LIMITED", "SERVICE_UNAVAILABLE"):
raise GitHubTransientError(err.get("message") or err.get("type"))
class GitHubDataSource(Protocol):
"""Protocol for GitHub data sources - allows swapping implementations."""
@@ -294,6 +327,13 @@ class DirectAPISource:
return self._fetch_commit_count_graphql_range(username, since_date)
else:
return self._fetch_commit_count_graphql_alltime(username)
except GitHubTransientError:
# Rate limit / 5xx: abort the fetch so the caller keeps the last
# good count instead of persisting a spurious 0.
raise
except requests.RequestException as e:
# A network-level failure is transient too.
raise GitHubTransientError(str(e))
except Exception as e:
print(f" Error fetching contribution count: {e}")
return 0
@@ -327,6 +367,7 @@ class DirectAPISource:
timeout=config.API_TIMEOUT
)
_raise_if_transient(resp)
if not resp.ok or 'data' not in resp.json():
print(f" GraphQL error: {resp.status_code}")
return 0
@@ -367,6 +408,7 @@ class DirectAPISource:
headers=headers,
timeout=config.API_TIMEOUT,
)
_raise_if_transient(year_resp)
if not year_resp.ok:
print(f" {year}: HTTP {year_resp.status_code}")
return year, 0
@@ -424,6 +466,7 @@ class DirectAPISource:
timeout=config.API_TIMEOUT,
)
_raise_if_transient(resp)
if resp.ok:
data = resp.json()
if 'data' in data and data['data'].get('user'):
@@ -454,9 +497,14 @@ class DirectAPISource:
timeout=config.API_TIMEOUT
)
_raise_if_transient(resp)
if resp.ok:
data = resp.json()
return data.get("total_count", 0)
except GitHubTransientError:
raise
except requests.RequestException as e:
raise GitHubTransientError(str(e))
except Exception as e:
print(f"Warning: Failed to fetch PR count via search API: {e}")