: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ci): retry github 5xx when downloading the schema artifact (#107256)
Robbiebaa61cabcdd2
diff --git a/tools/hogli-commands/hogli_commands/db_schema.py b/tools/hogli-commands/hogli_commands/db_schema.pyindex 99ea1ee1a912..52164b2da745 100644--- a/tools/hogli-commands/hogli_commands/db_schema.py+++ b/tools/hogli-commands/hogli_commands/db_schema.py@@ -18,6 +18,8 @@ from typing import Literal, TypeVar, castimport yamlimport clickimport requests+from requests.adapters import HTTPAdapter+from urllib3.util.retry import Retryfrom hogli_commands.github_auth import github_headers, github_token@@ -35,6 +37,9 @@ DOCKER_COMPOSE = ["docker", "compose", "-f", "docker-compose.dev.yml"]DB_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")PRODUCT_DB_ROUTING_PATH = Path("products/db_routing.yaml")APP_LABEL_RE = re.compile(r"^[a-z][a-z0-9_]*$")+GITHUB_RETRY_TOTAL = 4+GITHUB_RETRY_BACKOFF_FACTOR = 2+GITHUB_RETRY_STATUSES = (500, 502, 503, 504)T = TypeVar("T")@@ -326,6 +331,21 @@ def select_newest_compatible_artifact(return candidates[0] if candidates else None+def _github_session() -> requests.Session:+ # The GitHub artifacts API sometimes returns a 5xx for one request. Without a+ # retry, that single response fails the CI step that restores the schema.+ retry = Retry(+ total=GITHUB_RETRY_TOTAL,+ backoff_factor=GITHUB_RETRY_BACKOFF_FACTOR,+ status_forcelist=GITHUB_RETRY_STATUSES,+ allowed_methods=frozenset({"GET"}),+ raise_on_status=False,+ )+ session = requests.Session()+ session.mount("https://", HTTPAdapter(max_retries=retry))+ return session++def find_newest_compatible_artifact(*,token: str | None,@@ -336,7 +356,7 @@ def find_newest_compatible_artifact(# The listing is newest-first, so the first page holding a candidate holds the# newest one and the walk stops there. max_pages caps the miss case at a fixed# number of requests instead of paging through the whole retention window.- http = session or requests.Session()+ http = session or _github_session()fetched: list[SchemaArtifact] = []for page in range(1, max_pages + 1):@@ -382,7 +402,7 @@ def download_schema_artifact(if token is None:raise SchemaRestoreUnavailable("no GitHub token found; run `gh auth login` or set GH_TOKEN")- http = session or requests.Session()+ http = session or _github_session()response = http.get(artifact.archive_download_url,headers=github_headers(token),@@ -447,6 +467,7 @@ def download_latest_compatible_schema(session: requests.Session | None = None,) -> SchemaArtifact:token = github_token()+ session = session or _github_session()artifact = find_newest_compatible_artifact(token=token, session=session, base_branch=base_branch)if artifact is None:raise SchemaRestoreUnavailable(diff --git a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py b/tools/hogli-commands/hogli_commands/tests/test_db_schema.pyindex 28cff74a6423..72f9aef1eb7b 100644--- a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py+++ b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py@@ -1,6 +1,9 @@from __future__ import annotationsimport gzip+import threading+from collections.abc import Iterator+from http.server import BaseHTTPRequestHandler, HTTPServerfrom pathlib import Pathfrom typing import Any@@ -164,6 +167,65 @@ def test_find_emits_diagnostics_on_no_compatible_artifact(capsys: pytest.Captureassert "After name/expiry/size/branch filters: 0 candidate(s)" in stderr+class _ScriptedStatusServer(HTTPServer):+ statuses: list[int]+ request_count: int+++class _ScriptedStatusHandler(BaseHTTPRequestHandler):+ server: _ScriptedStatusServer++ def do_GET(self) -> None:+ index = min(self.server.request_count, len(self.server.statuses) - 1)+ self.server.request_count += 1+ self.send_response(self.server.statuses[index])+ self.send_header("Content-Length", "2")+ self.end_headers()+ self.wfile.write(b"{}")++ def log_message(self, format: str, *args: Any) -> None:+ pass+++def scripted_status_server() -> Iterator[_ScriptedStatusServer]:+ server = _ScriptedStatusServer(("127.0.0.1", 0), _ScriptedStatusHandler)+ server.statuses = [200]+ server.request_count = 0+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ yield server+ server.shutdown()+ server.server_close()+++ "statuses,expected_status,expected_requests",+ [+ ([500, 502, 200], 200, 3),+ ([503], 503, db_schema.GITHUB_RETRY_TOTAL + 1),+ ([404, 200], 404, 1),+ ],+ ids=["transient_5xx_recovers", "persistent_5xx_returns_last_response", "4xx_not_retried"],+)+def test_github_session_retries_only_server_errors(+ scripted_status_server: _ScriptedStatusServer,+ monkeypatch: pytest.MonkeyPatch,+ statuses: list[int],+ expected_status: int,+ expected_requests: int,+) -> None:+ monkeypatch.setattr(db_schema, "GITHUB_RETRY_BACKOFF_FACTOR", 0)+ scripted_status_server.statuses = statuses+ session = db_schema._github_session()+ session.mount("http://", session.get_adapter("https://"))++ response = session.get(f"http://127.0.0.1:{scripted_status_server.server_port}/", timeout=5)++ assert response.status_code == expected_status+ assert scripted_status_server.request_count == expected_requests++def test_download_fails_when_no_compatible_artifact(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(db_schema, "github_token", lambda: "token")monkeypatch.setattr(db_schema, "find_newest_compatible_artifact", lambda **kwargs: None)