From 0586f83a3336e21b11d4b5c8a2a42102a70da42d Mon Sep 17 00:00:00 2001 From: shay Date: Sat, 18 Jul 2026 11:45:42 -0700 Subject: [PATCH] fix(fetcher): keep last-good counts on GitHub rate limits + expose fetch metrics MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- fetcher/src/api.py | 42 ++++++++++++++++++++++++++++--- fetcher/src/cron.py | 8 ++++++ fetcher/src/db.py | 44 +++++++++++++++++++++++++++++++++ fetcher/src/github.py | 48 ++++++++++++++++++++++++++++++++++++ fetcher/tests/test_api.py | 14 +++++++++++ fetcher/tests/test_cron.py | 17 +++++++++++++ fetcher/tests/test_db.py | 17 +++++++++++++ fetcher/tests/test_github.py | 41 ++++++++++++++++++++++++++++++ 8 files changed, 227 insertions(+), 4 deletions(-) diff --git a/fetcher/src/api.py b/fetcher/src/api.py index 3a011c9..88df6e0 100644 --- a/fetcher/src/api.py +++ b/fetcher/src/api.py @@ -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/", 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) diff --git a/fetcher/src/cron.py b/fetcher/src/cron.py index da29363..a2f425b 100644 --- a/fetcher/src/cron.py +++ b/fetcher/src/cron.py @@ -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) diff --git a/fetcher/src/db.py b/fetcher/src/db.py index 4806a59..c8e13f2 100644 --- a/fetcher/src/db.py +++ b/fetcher/src/db.py @@ -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 diff --git a/fetcher/src/github.py b/fetcher/src/github.py index 29108e9..cbc25c4 100644 --- a/fetcher/src/github.py +++ b/fetcher/src/github.py @@ -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}") diff --git a/fetcher/tests/test_api.py b/fetcher/tests/test_api.py index b44ecaa..5617258 100644 --- a/fetcher/tests/test_api.py +++ b/fetcher/tests/test_api.py @@ -30,6 +30,20 @@ def test_endpoints_require_internal_token(client): assert r.status_code == 401 +def test_metrics_endpoint_no_auth_and_prometheus_format(client): + from src import db as dbmod + dbmod.bump_fetch_metric("ok") + dbmod.bump_fetch_metric("rate_limited") + r = client.get("/metrics") + assert r.status_code == 200 + body = r.get_data(as_text=True) + assert "# TYPE ghstats_fetch_total counter" in body + assert 'ghstats_fetch_total{outcome="ok"} 1' in body + assert 'ghstats_fetch_total{outcome="rate_limited"} 1' in body + # Every outcome is emitted even at zero so rate() has a baseline sample. + assert 'ghstats_fetch_total{outcome="not_found"} 0' in body + + @resp_lib.activate def test_data_auto_fetches_on_miss(client, monkeypatch): # The fetcher fires the independent GitHub calls in parallel, so we diff --git a/fetcher/tests/test_cron.py b/fetcher/tests/test_cron.py index bde179e..15aab7c 100644 --- a/fetcher/tests/test_cron.py +++ b/fetcher/tests/test_cron.py @@ -4,6 +4,7 @@ import pytest from unittest.mock import patch from src import db as dbmod from src import cron as cronmod +from src import github as ghmod @pytest.fixture @@ -26,6 +27,22 @@ def test_refresh_tick_calls_github_for_due_users(tmp_db): assert stats["refreshed"] == 1 +def test_refresh_rate_limit_keeps_last_good_and_counts_metric(tmp_db): + # A rate-limited refresh must NOT overwrite the cached row, and must be + # counted as rate_limited so the monitoring stack can see it. + dbmod.upsert_user("alice", {"user": {"login": "alice"}, "total_commits": 1841}) + with dbmod._connect() as c: + c.execute("UPDATE users SET fetched_at='2020-01-01T00:00:00Z', last_requested_at=? WHERE username='alice'", + (dbmod._now(),)) + with patch("src.cron.github.fetch_github_data", + side_effect=ghmod.GitHubTransientError("rate limited")): + stats = cronmod.tick(hours=24, active_within_days=7, gc_days=7) + assert stats["failed"] == 1 and stats["refreshed"] == 0 + # Last-good data retained. + assert dbmod.get_user("alice")["data"]["total_commits"] == 1841 + assert dbmod.read_fetch_metrics()["rate_limited"] == 1 + + def test_tick_runs_gc_for_abandoned_trial_users(tmp_db): dbmod.upsert_user("ghost", {"user": {"login": "ghost"}}) with dbmod._connect() as c: diff --git a/fetcher/tests/test_db.py b/fetcher/tests/test_db.py index 0368735..929ef7b 100644 --- a/fetcher/tests/test_db.py +++ b/fetcher/tests/test_db.py @@ -30,6 +30,23 @@ def test_upsert_and_get_round_trip(tmp_db): assert row["fetched_at"] +def test_fetch_metrics_round_trip(tmp_db): + # Zero-filled for every known outcome before anything is recorded. + assert dbmod.read_fetch_metrics() == {o: 0 for o in dbmod.FETCH_OUTCOMES} + dbmod.bump_fetch_metric("ok") + dbmod.bump_fetch_metric("ok") + dbmod.bump_fetch_metric("rate_limited") + counts = dbmod.read_fetch_metrics() + assert counts["ok"] == 2 + assert counts["rate_limited"] == 1 + assert counts["not_found"] == 0 + + +def test_fetch_metric_unknown_outcome_buckets_to_error(tmp_db): + dbmod.bump_fetch_metric("bogus") + assert dbmod.read_fetch_metrics()["error"] == 1 + + def test_payload_hash_is_deterministic_and_changes_on_diff(): h1 = dbmod.payload_hash({"a": 1, "b": 2}) h2 = dbmod.payload_hash({"b": 2, "a": 1}) diff --git a/fetcher/tests/test_github.py b/fetcher/tests/test_github.py index 88346ae..fff8d98 100644 --- a/fetcher/tests/test_github.py +++ b/fetcher/tests/test_github.py @@ -73,3 +73,44 @@ def test_fetch_handles_404(): ) data = github.fetch_github_data("nope", token="t") assert data["user"].get("message") == "Not Found" or data["user"] is None + + +@responses.activate +def test_commit_count_raises_on_graphql_rate_limit(): + # GraphQL reports a rate limit as HTTP 200 with an `errors` array — the + # exact shape a valid response uses. It must NOT be swallowed into a 0 + # that would overwrite the last good count in fetcher.db. + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": None}, + "errors": [{"type": "RATE_LIMITED", "message": "API rate limit exceeded"}]}, + status=200, + ) + src = github.DirectAPISource(token="t") + with pytest.raises(github.GitHubTransientError): + src.fetch_commit_count("alice", []) + + +@responses.activate +def test_commit_count_raises_on_rest_rate_limit(): + # A 403 with the remaining budget at 0 is a rate limit, not a real answer. + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"message": "rate limited"}, status=403, + headers={"X-RateLimit-Remaining": "0"}, + ) + src = github.DirectAPISource(token="t") + with pytest.raises(github.GitHubTransientError): + src.fetch_commit_count("alice", []) + + +@responses.activate +def test_commit_count_zero_on_not_found_is_not_transient(): + # A genuinely unknown user (NOT_FOUND, no rate-limit error) is a real, + # persistable "no data" answer — return 0, don't raise. + responses.add( + responses.POST, "https://api.github.com/graphql", + json={"data": {"user": None}}, status=200, + ) + src = github.DirectAPISource(token="t") + assert src.fetch_commit_count("ghost", []) == 0