fix(launch): back off build retries on GitHub limits, dedupe fetcher misses, no ad hoc render before first build

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shay
2026-11-30 09:11:03 -08:00
co-authored by Claude Opus 5.5
parent d907815f19
commit d4b4a8bc52
8 changed files with 147 additions and 4 deletions
+4 -1
View File
@@ -911,7 +911,10 @@ def _serve(username: str, widget_name: str) -> Response:
overrides = sanitize_settings_query(request.args)
if widget_name != "composite":
overrides = {k: v for k, v in overrides.items() if k == "theme"}
if overrides and current_hash != "not_found":
# No current widget means no build has landed yet, so the fetcher likely
# has no data either; an ad hoc render would trigger a GitHub fetch per
# request. Fall through to the building placeholder instead.
if overrides and current_hash is not None and current_hash != "not_found":
# Honor the possibly-overridden theme for error placeholders.
override_theme = overrides.get("theme") if isinstance(overrides.get("theme"), str) else None
effective_theme = override_theme or theme
+9 -3
View File
@@ -493,8 +493,11 @@ def pending_job_count() -> int:
def claim_next_job() -> Optional[dict]:
now = _now()
with _settings_conn() as c:
# A pending job whose updated_at is in the future is backing off
# (see fail_job's delay_s) and is not claimable yet.
row = c.execute(
"SELECT * FROM jobs WHERE status='pending' ORDER BY created_at LIMIT 1"
"SELECT * FROM jobs WHERE status='pending' AND updated_at <= ? ORDER BY created_at LIMIT 1",
(now,),
).fetchone()
if row is None:
return None
@@ -511,11 +514,14 @@ def complete_job(job_id: int) -> None:
c.commit()
def fail_job(job_id: int, err: str, retry: bool) -> None:
def fail_job(job_id: int, err: str, retry: bool, delay_s: float = 0) -> None:
status = "pending" if retry else "failed"
when = _now()
if retry and delay_s > 0:
when = (datetime.utcnow() + timedelta(seconds=delay_s)).isoformat(timespec="seconds") + "Z"
with _settings_conn() as c:
c.execute("UPDATE jobs SET status=?, last_error=?, updated_at=? WHERE id=?",
(status, err, _now(), job_id))
(status, err, when, job_id))
c.commit()
+23
View File
@@ -10,6 +10,7 @@ re-renders triggered by the Generate button.
Run as its own container: CMD python -m src.worker
"""
import logging
import random
import time
from dataclasses import asdict
@@ -18,6 +19,22 @@ from .widgets import compose_widget
log = logging.getLogger("generator.worker")
MAX_ATTEMPTS = 3
# A fetcher 503 means GitHub's quota is spent. Retrying in seconds burns all
# attempts before the hourly reset, so back off exponentially (1, 2, 4, ...
# minutes, jittered, capped at an hour) and allow enough attempts to span
# a full quota window.
RATE_LIMIT_MAX_ATTEMPTS = 8
RATE_LIMIT_BACKOFF_CAP_S = 3600
def _rate_limit_delay(e: Exception, attempts: int) -> float:
resp = getattr(e, "response", None)
try:
retry_after = float(resp.headers.get("Retry-After"))
except (AttributeError, TypeError, ValueError):
retry_after = 0
delay = max(retry_after, 60 * 2 ** (attempts - 1))
return min(delay * random.uniform(0.8, 1.2), RATE_LIMIT_BACKOFF_CAP_S)
def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
@@ -133,6 +150,12 @@ def process_one() -> bool:
log.info("prefetched + rendered widgets for %s", username)
return True
except Exception as e:
if getattr(getattr(e, "response", None), "status_code", None) == 503:
retry = job["attempts"] < RATE_LIMIT_MAX_ATTEMPTS
db.fail_job(job["id"], str(e)[:500], retry=retry,
delay_s=_rate_limit_delay(e, job["attempts"]))
log.warning("prefetch rate-limited for %s (retry=%s): %s", username, retry, e)
return True
retry = job["attempts"] < MAX_ATTEMPTS
db.fail_job(job["id"], str(e)[:500], retry=retry)
log.warning("prefetch failed for %s (retry=%s): %s", username, retry, e)
+14
View File
@@ -719,6 +719,20 @@ def test_query_override_without_params_uses_cached_composite(client):
assert b"<svg>cached</svg>" in r.data
def test_query_override_skips_adhoc_render_before_first_build(client):
"""With no build landed yet the fetcher likely has no data, so an ad hoc
render would start a GitHub fetch per request. Serve the building
placeholder instead."""
dbmod.enroll("alice", {"theme": "midnight"})
with patch("src.worker.render_composite_adhoc") as adhoc:
r = client.get("/api/alice?theme=onyx&widgets=name,grade")
assert adhoc.call_count == 0
assert r.status_code == 200
assert r.headers["X-Widget-Status"] == "building"
def test_query_override_ignores_unknown_params(client):
"""Keys not in the allow-list are dropped by sanitize_settings_query so
bogus query strings don't trigger the expensive ad-hoc path."""
+50
View File
@@ -83,6 +83,56 @@ def test_worker_marks_failed_after_max_attempts(tmp_dbs):
assert row["attempts"] >= 3
def _http_503(retry_after=None):
import requests
resp = requests.Response()
resp.status_code = 503
if retry_after is not None:
resp.headers["Retry-After"] = str(retry_after)
return requests.HTTPError("503 Server Error", response=resp)
def test_worker_backs_off_on_rate_limit(tmp_dbs):
"""A fetcher 503 (GitHub quota spent) delays the retry instead of
burning all attempts in seconds; the job is not claimable until then."""
dbmod.enroll("alice", {"theme": "dark"})
with patch("src.worker.fetcher_client.get_data", side_effect=_http_503()):
worker.process_one()
assert worker.process_one() is False # backing off, nothing claimable
with dbmod._settings_conn() as c:
row = c.execute("SELECT status, attempts, updated_at FROM jobs WHERE username='alice'").fetchone()
assert row["status"] == "pending"
assert row["attempts"] == 1
assert row["updated_at"] > dbmod._now()
# Once the delay has passed the job is claimed again.
with dbmod._settings_conn() as c:
c.execute("UPDATE jobs SET updated_at='2020-01-01T00:00:00Z'")
c.commit()
assert dbmod.claim_next_job()["username"] == "alice"
def test_rate_limit_delay_grows_honors_retry_after_and_caps():
with patch("src.worker.random.uniform", return_value=1.0):
assert worker._rate_limit_delay(_http_503(), 1) == 60
assert worker._rate_limit_delay(_http_503(), 3) == 240
assert worker._rate_limit_delay(_http_503(retry_after=600), 1) == 600
assert worker._rate_limit_delay(_http_503(), 10) == worker.RATE_LIMIT_BACKOFF_CAP_S
def test_worker_rate_limit_allows_more_attempts(tmp_dbs):
dbmod.enroll("alice", {"theme": "dark"})
with patch("src.worker.fetcher_client.get_data", side_effect=_http_503()):
for _ in range(worker.RATE_LIMIT_MAX_ATTEMPTS):
with dbmod._settings_conn() as c:
c.execute("UPDATE jobs SET updated_at='2020-01-01T00:00:00Z' WHERE status='pending'")
c.commit()
worker.process_one()
with dbmod._settings_conn() as c:
row = c.execute("SELECT status, attempts FROM jobs WHERE username='alice'").fetchone()
assert row["status"] == "failed"
assert row["attempts"] == worker.RATE_LIMIT_MAX_ATTEMPTS
def test_process_one_persists_streak(tmp_dbs):
"""Phase 1 worker must compute and persist the user's streak so max survives
future settings changes."""