From 54133033946ed2557081f547fc4e0f2fedd0b993 Mon Sep 17 00:00:00 2001 From: itvi-1234 Date: Wed, 2 Dec 2026 22:18:23 +0530 Subject: [PATCH] Ask GitHub again when it fails for a moment while starting publish workflows A publish run failed for Go and PyPI because GitHub answered 502 Bad Gateway to the request that starts their workflows; npm and Maven in the same run were fine. One such answer stopped the whole language. Reads from the GitHub API (run listings and run status) are now asked again, up to four times with a growing pause, on 429 and 5xx. Starting a workflow is not simply sent again, because GitHub can start the run and still answer with an error, and a second request would start a second run. After such an error the script first looks for the run it started, and sends the request again only when there is none. Other errors, such as 422, still stop at once. --- tooling/extension-bindings/ci/publish_all.py | 49 ++++++++++--- .../extension-bindings/ci/test_publish_all.py | 72 +++++++++++++++++++ 2 files changed, 112 insertions(+), 9 deletions(-) diff --git a/tooling/extension-bindings/ci/publish_all.py b/tooling/extension-bindings/ci/publish_all.py index 16cadbf..ebdfde5 100644 --- a/tooling/extension-bindings/ci/publish_all.py +++ b/tooling/extension-bindings/ci/publish_all.py @@ -33,6 +33,7 @@ import subprocess import sys import time +import urllib.error import urllib.request import xml.etree.ElementTree as ET from concurrent.futures import ThreadPoolExecutor @@ -266,6 +267,11 @@ def report(findings: list[Finding], execute: bool) -> str: return "\n".join(lines) +# GitHub's API sometimes answers 502 or 503 for a moment. +GITHUB_ATTEMPTS = 4 +GITHUB_RETRY_SECONDS = 10 + + class GitHub: """The few Actions REST calls dispatch needs, authenticated with the job's token.""" @@ -279,9 +285,19 @@ def request(self, method: str, path: str, body: dict | None = None) -> dict: headers={"Authorization": f"Bearer {self.token}", "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "Content-Type": "application/json"}, ) - with urllib.request.urlopen(request, timeout=60) as response: - payload = response.read() - return json.loads(payload) if payload else {} + # A read is asked again when GitHub fails for a moment. A dispatch is not, because asking twice could start + # two runs; dispatch() checks for its run before it asks again. + attempts = GITHUB_ATTEMPTS if method == "GET" else 1 + for attempt in range(1, attempts + 1): + try: + with urllib.request.urlopen(request, timeout=60) as response: + payload = response.read() + return json.loads(payload) if payload else {} + except urllib.error.HTTPError as error: + if error.code not in publish_setup.RETRY_CODES or attempt == attempts: + raise + time.sleep(GITHUB_RETRY_SECONDS * attempt) + raise AssertionError("unreachable") def dispatch( @@ -291,18 +307,33 @@ def dispatch( ) -> dict: """Start a workflow_dispatch run and wait for it to finish. Returns the finished run.""" started = now() - timedelta(seconds=5) - github.request("POST", f"actions/workflows/{workflow}/dispatches", {"ref": ref, "inputs": inputs}) - deadline = now() + timedelta(seconds=timeout) - run = None - while run is None: + + def started_run() -> dict | None: listing = github.request("GET", f"actions/workflows/{workflow}/runs?event=workflow_dispatch&branch={ref}&per_page=20") mine = [ item for item in listing.get("workflow_runs", []) if datetime.fromisoformat(item["created_at"].replace("Z", "+00:00")) >= started and item.get("triggering_actor", {}).get("login") == "github-actions[bot]" ] - if mine: - run = min(mine, key=lambda item: item["created_at"]) + return min(mine, key=lambda item: item["created_at"]) if mine else None + + run = None + for attempt in range(1, GITHUB_ATTEMPTS + 1): + try: + github.request("POST", f"actions/workflows/{workflow}/dispatches", {"ref": ref, "inputs": inputs}) + break + except urllib.error.HTTPError as error: + if error.code not in publish_setup.RETRY_CODES or attempt == GITHUB_ATTEMPTS: + raise + # A failed answer can still have started the run; only ask again when it did not. + sleep(GITHUB_RETRY_SECONDS * attempt) + if run := started_run(): + break + print(f"{workflow}: GitHub answered HTTP {error.code}; asking again.", flush=True) + deadline = now() + timedelta(seconds=timeout) + while run is None: + run = started_run() + if run: break if now() > deadline: raise TimeoutError(f"{workflow} did not start a run") diff --git a/tooling/extension-bindings/ci/test_publish_all.py b/tooling/extension-bindings/ci/test_publish_all.py index 72f01b7..fa24eb2 100644 --- a/tooling/extension-bindings/ci/test_publish_all.py +++ b/tooling/extension-bindings/ci/test_publish_all.py @@ -8,6 +8,7 @@ from pathlib import Path from tempfile import TemporaryDirectory from unittest.mock import patch +import unittest.mock import yaml @@ -180,6 +181,77 @@ def test_a_run_that_never_starts_times_out(self) -> None: now=lambda: next(clock), sleep=lambda _: None) + def bad_gateway(self) -> Exception: + return script.urllib.error.HTTPError("https://api.github.invalid", 502, "Bad Gateway", None, None) + + def test_a_dispatch_that_github_failed_is_asked_again(self) -> None: + start = datetime(2026, 12, 2, 15, 0, tzinfo=timezone.utc) + clock = iter(start + timedelta(seconds=step) for step in range(100)) + bot = {"login": "github-actions[bot]"} + mine = {"id": 7, "created_at": "2026-12-02T15:00:30Z", "triggering_actor": bot, "status": "completed", + "conclusion": "success", "html_url": "mine"} + posts = [] + + class Flaky(FakeGitHub): + def request(inner, method, path, body=None): + if method == "POST": + posts.append(path) + if len(posts) == 1: + raise self.bad_gateway() + inner.runs = [mine] + return super().request(method, path, body) + + run = script.dispatch(Flaky([], []), "binding-promote.yml", "main", {}, timeout=3600, + now=lambda: next(clock), sleep=lambda _: None) + self.assertEqual(run["id"], 7) + self.assertEqual(len(posts), 2) + + def test_a_dispatch_that_started_despite_the_error_is_not_sent_twice(self) -> None: + start = datetime(2026, 12, 2, 15, 0, tzinfo=timezone.utc) + clock = iter(start + timedelta(seconds=step) for step in range(100)) + mine = {"id": 8, "created_at": "2026-12-02T15:00:02Z", "triggering_actor": {"login": "github-actions[bot]"}, + "status": "completed", "conclusion": "success", "html_url": "mine"} + posts = [] + + class StartedAnyway(FakeGitHub): + def request(inner, method, path, body=None): + if method == "POST": + posts.append(path) + inner.runs = [mine] # GitHub started the run, then answered 502 + raise self.bad_gateway() + return super().request(method, path, body) + + run = script.dispatch(StartedAnyway([], []), "binding-publish-pypi.yml", "main", {}, timeout=3600, + now=lambda: next(clock), sleep=lambda _: None) + self.assertEqual(run["id"], 8) + self.assertEqual(len(posts), 1) + + def test_reads_are_asked_again_and_dispatches_are_not(self) -> None: + answer = unittest.mock.MagicMock() + answer.__enter__.return_value.read.return_value = b'{"ok": true}' + github = script.GitHub("example/repo", "token") + with unittest.mock.patch.object(script.urllib.request, "urlopen", + side_effect=[self.bad_gateway(), answer]), \ + unittest.mock.patch.object(script.time, "sleep"): + self.assertEqual(github.request("GET", "actions/runs/1"), {"ok": True}) + with unittest.mock.patch.object(script.urllib.request, "urlopen", side_effect=[self.bad_gateway()]), \ + self.assertRaises(script.urllib.error.HTTPError): + github.request("POST", "actions/workflows/x.yml/dispatches", {}) + + def test_other_dispatch_errors_stop_at_once(self) -> None: + refused = script.urllib.error.HTTPError("https://api.github.invalid", 422, "Unprocessable", None, None) + + class Refusing(FakeGitHub): + def request(inner, method, path, body=None): + if method == "POST": + raise refused + return super().request(method, path, body) + + with self.assertRaises(script.urllib.error.HTTPError): + script.dispatch(Refusing([], []), "binding-promote.yml", "main", {}, timeout=60, + now=lambda: datetime(2026, 12, 2, tzinfo=timezone.utc), sleep=lambda _: None) + + class SetupCardTests(unittest.TestCase): def finding(self, key: str, language: str, coordinate: str, status: str) -> script.Finding: return script.Finding(script.Package(key, language, coordinate, "0.2.0"), status)