diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f5acbb17..3526208d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -345,7 +345,8 @@ The current CLI writes PR bodies only when content changes, excluding volatile check timing from the generated validation block. Keep refreshes idempotent: one state transition should not become repeated writes that trigger policy CI. GitHub reads and the idempotent thread resolution mutation retry transient -failures up to three times (5/20/60 seconds) and stop on rate limits. Mergify +failures once after five seconds. They stop on exhausted quota and honor a +secondary limit’s Retry-After when the delay fits the read budget. Mergify reads retry server errors, throttling and failed reads up to twice (2/5 seconds). Waits use bounded backoff. See the [contract's waiter and polling rules](../core/CONTRACT.md#failure). diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 29829078..ff706ed4 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -913,7 +913,7 @@ def _repost_prefix(result: ReviewResult) -> str: def _recover_review(wt: Path, config: Config, pr: github.PR, result: ReviewResult, publisher: str, token: str) -> tuple[bool, list[dict]]: - with github.bounded_reads(time.monotonic() + 30, token=token): + with github.bounded_reads(time.monotonic() + 30, token=token, retry=True): reviews = _pr_reviews(config.repo, pr.number) return _confirm_review(wt, config, pr, result, publisher, reviews), reviews diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 874b79fa..e085b13d 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -14,6 +14,7 @@ from contextvars import ContextVar from dataclasses import dataclass from datetime import UTC, datetime +from email.utils import parsedate_to_datetime from pathlib import Path from typing import Literal from urllib.parse import quote @@ -120,7 +121,7 @@ class Readiness: TRANSIENT_RE = re.compile(r"HTTP 5\d\d|timed out|TLS handshake timeout|i/o timeout|" r"connection reset|no server is currently|error connecting to api\.github\.com|" r"unexpected end of JSON input|Something went wrong while executing your query", re.IGNORECASE) -RETRY_DELAYS = (5.0, 20.0, 60.0) +RETRY_DELAY = 5.0 _retry_sleep = time.sleep _read_scope: ContextVar[tuple[float, str | None, bool] | None] = ContextVar("github_reads", default=None) _api_error_diagnostics: ContextVar[bool] = ContextVar("github_api_error_diagnostics", default=False) @@ -143,8 +144,8 @@ def bounded_reads(deadline: float, token: str | None = "", *, retry: bool = Fals _read_scope.reset(scope) -def _read_timeout(limit: float) -> float: - scope = _read_scope.get() +def _read_timeout(limit: float, *, scoped: bool = True) -> float: + scope = _read_scope.get() if scoped else None if scope is None: return limit remaining = scope[0] - time.monotonic() @@ -326,6 +327,24 @@ def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> boo or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) +def _retry_pause(delay: float | None, limit: float, *, scoped: bool = True) -> bool: + if delay is None or delay >= _read_timeout(limit, scoped=scoped): + return False + _retry_sleep(delay) + return True + + +def _rate_limit_delay(headers: dict[str, str], delay: float | None) -> float | None: + if delay is None or headers.get("x-ratelimit-remaining") == "0": + return None + value = headers.get("retry-after", "") + try: + wait = int(value) if re.fullmatch(r"[0-9]{1,18}", value) else parsedate_to_datetime(value).timestamp() - time.time() + except (OverflowError, OSError, ValueError): + return None + return max(delay, wait) + + def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -340,48 +359,48 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, rest_api = args[:1] == ("api",) and args[:2] != ("api", "graphql") patch_error = args[:1] == ("api",) and _api_method(args) == "PATCH" request_args = args - if (rest_api or diagnostic_api) and not {"--include", "-i"} & set(args): + api = args[:1] == ("api",) + if api and not {"--include", "-i"} & set(args): request_args = (*args, "--include") argv = ("gh", *request_args) cwd = cwd or Path("/") read_only = _read_only(args) retryable = read_only or retry_idempotent scope = _read_scope.get() if read_only else None - delays = (None,) if scope and not scope[2] else (*RETRY_DELAYS, None) + delays = (RETRY_DELAY, None) if retryable and (not scope or scope[2]) else (None,) for delay in delays: selected = _select_token(token, scope, read_only) # a retry backoff can outlive the app token try: done = run(list(argv), cwd=cwd, env_allowlist=GH_ENV, extra_env={"GH_TOKEN": selected} if selected else None, - timeout=_read_timeout(timeout) if scope else timeout) + timeout=_read_timeout(timeout, scoped=read_only)) except ToolMissing as exc: raise GhMissing(argv, str(exc), token=selected, guidance=f"\nInstall GitHub CLI, then {GH_AUTH_REMEDY}") from exc except ProcTimeout as exc: - if scope and scope[2]: - _read_timeout(timeout) - if delay is None or not retryable: + _read_timeout(timeout, scoped=bool(scope and scope[2])) + if not _retry_pause(delay, timeout, scoped=read_only): raise ProcTimeout( _redact_tokens(str(exc), selected), _redact_tokens(exc.stdout, selected), stderr=_redact_tokens(exc.stderr, selected), duration_s=exc.duration_s, ) from None - _retry_sleep(_read_timeout(delay) if scope else delay) continue - status, headers, body = (_included_response(done.stdout) if rest_api or diagnostic_api + status, headers, body = (_included_response(done.stdout) if api else (None, {}, done.stdout)) - tail = "\n".join(part for part in (done.stderr, body if rest_api else done.stdout) if part) + tail = "\n".join(part for part in (done.stderr, body) if part) if done.exit_code and _rate_limited(status, headers, tail): - guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api + if _retry_pause(_rate_limit_delay(headers, delay), timeout, scoped=read_only): + continue + guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api or headers else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) if diagnostic_api or patch_error: detail = _api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, message_tail=None if diagnostic_api else tail) raise GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhUnavailable(argv, tail, token=selected, guidance=guidance) + raise GhUnavailable(("gh", *args), tail, token=selected, guidance=guidance) transient = _transient_error(tail, retry_idempotent, status) - if done.exit_code == 0 or delay is None or not retryable or not transient: + if done.exit_code == 0 or not transient or not _retry_pause(delay, timeout, scoped=read_only): break - _retry_sleep(_read_timeout(delay) if scope else delay) if done.exit_code != 0: error_command = ("GitHub API request",) if diagnostic_api or patch_error else argv error_tail = (_api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, diff --git a/tests/test_cli.py b/tests/test_cli.py index 53b0e0ba..1f9e7bd0 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4183,7 +4183,7 @@ def test_resolve_reports_recovery_when_followup_read_fails(finding_pr, gh, capsy @pytest.mark.parametrize("recovers", [True, False]) def test_resolve_retries_only_thread_resolution(finding_pr, gh: FakeGh, capsys, monkeypatch, recovers) -> None: failure = {"stdout": "", "stderr": "gh: Something went wrong while executing your query", "exit_code": 1} - outcomes = [failure, THREAD_RESOLVED] if recovers else [failure] * 4 + outcomes = [failure, THREAD_RESOLVED] if recovers else [failure] * 2 gh.respond("api graphql", threads_json(finding_pr), REPLY_ACCEPTED, *outcomes) if recovers: gh.append("api graphql", threads_json()) diff --git a/tests/test_github.py b/tests/test_github.py index 3066bfb7..ecfccac1 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -1295,28 +1295,28 @@ def test_merge_rejects_unknown_strategy(gh: FakeGh) -> None: (("api", "repos/acme/widgets/pulls/1"), 2, ""), (("api", "repos/acme/widgets/commits/x/check-runs", "--method", "GET", "-F", "per_page=100"), 2, "dial tcp 140.82.121.5:443: i/o timeout"), (("api", "graphql", "-f", "query=query { viewer { login } }"), 2, "net/http: TLS handshake timeout"), - (("api", "repos/acme/widgets/pulls/7"), 2, "error connecting to api.github.com"), + (("api", "repos/acme/widgets/pulls/7"), 2, "connection reset by peer"), (("api", "repos/acme/widgets/pulls/7/reviews"), 2, "unexpected end of JSON input"), (("api", "graphql", "-f", "query=query { viewer { login } }"), 2, "gh: Something went wrong while executing your query"), (("api", "repos/acme/widgets/issues/1/comments", "-f", "body=x"), 1, "HTTP 503"), (("api", "graphql", "-f", "query=mutation { resolve }"), 1, "HTTP 503"), ]) def test_gh_retries_only_transient_reads(monkeypatch, args, attempts, error): - seen: list[list[str]] = [] + seen, sleeps = [], [] def run(argv, **_): seen.append(argv) - failed = len(seen) == 1 + failed = len(seen) == 1 or "connection reset" in error if failed and "pulls/1" in argv[2]: raise github.ProcTimeout("gh api timed out") return type("Done", (), {"exit_code": int(failed), "stdout": "ok", "stderr": error * failed}) monkeypatch.setattr(github, "run", run) - monkeypatch.setattr(github, "_retry_sleep", lambda _: None) - if attempts == 2: + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + if attempts == 2 and "connection reset" not in error: assert github._gh(*args) == "ok" else: with pytest.raises(github.GhError): github._gh(*args) - assert len(seen) == attempts + assert len(seen) == attempts and sleeps == ([5] if attempts == 2 else []) @pytest.mark.parametrize("error", ["API rate limit exceeded", "API rate limit already exceeded", @@ -1336,28 +1336,28 @@ def test_rest_rate_limit_is_not_retried_or_probed(gh, monkeypatch, tmp_path, err @pytest.mark.parametrize(("remaining", "retry_after", "hint"), [ - ("0", "", "hourly quota exhausted: retry after 2026-11-25T21:03:14+00:00"), + ("0", "90", "hourly quota exhausted: retry after 2026-11-25T21:03:14+00:00"), ("4676", "90", "short-window limit: retry after 90 s"), ("4676", "", "short-window limit: retry after ~60 s"), ("", "90", "short-window limit: retry after 90 s"), ("", "Wed, 25 Nov 2026 21:03:14 GMT", "short-window limit: retry after Wed, 25 Nov 2026 21:03:14 GMT"), ("", "", "Rate limited: retry after GitHub's reset or Retry-After; No automatic retry."), ]) -def test_rest_rate_limit_uses_failed_response_headers(gh, remaining, retry_after, hint): +def test_rest_rate_limit_uses_failed_response_headers(gh, monkeypatch, remaining, retry_after, hint): + sleeps = [] + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + monkeypatch.setattr(github.time, "time", lambda: 1795640554) headers = "HTTP/2.0 403 Forbidden\r\nX-Unrelated: never print this\r\n" if remaining: - headers += ( - f"X-RateLimit-Resource: core\r\nX-RateLimit-Remaining: {remaining}\r\n" - "X-RateLimit-Reset: 1795640594\r\n" - ) + headers += f"X-RateLimit-Resource: core\r\nX-RateLimit-Remaining: {remaining}\r\nX-RateLimit-Reset: 1795640594\r\n" if retry_after: headers += f"Retry-After: {retry_after}\r\n" gh.respond(pr_list_key("lz/x"), headers + '\r\n{"message":"API rate limit exceeded"}', exit=1, stderr="gh: API rate limit exceeded for installation ID 123 (HTTP 403)") - with pytest.raises(github.GhError) as info: + budget = 50 if remaining == "4676" else 100 + with github.bounded_reads(github.time.monotonic() + budget, retry=True), pytest.raises(github.GhError) as info: github.pr_for_branch(REPO, "lz/x") - error = str(info.value) assert hint in error if remaining: @@ -1367,10 +1367,9 @@ def test_rest_rate_limit_uses_failed_response_headers(gh, remaining, retry_after if retry_after: assert f"Retry-After: {retry_after}" in error assert "never print this" not in error - assert [call["argv"] for call in gh.calls] == [ - [*branch_head_key("lz/x").split(), "--include"], - [*pr_list_key("lz/x").split(), "--include"], - ] + assert sleeps == ([90 if retry_after.isdigit() else 40] if retry_after and not remaining else []) + assert [call["argv"] for call in gh.calls] == ( + [[*branch_head_key("lz/x").split(), "--include"]] + [[*pr_list_key("lz/x").split(), "--include"]] * (1 + len(sleeps))) @pytest.mark.parametrize(("diagnostic", "verified"), [ diff --git a/tests/test_hosted.py b/tests/test_hosted.py index fd6a9e26..1bd6cb3c 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -160,7 +160,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, ca else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") if error in {"api", "recover", "before"}: - assert hosted.main() == (1 if error == "before" else 0) and sleeps == ([5] if error == "recover" else list(github.RETRY_DELAYS)) + assert hosted.main() == (1 if error == "before" else 0) and sleeps == [5] assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error != "recover") else: with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): diff --git a/tests/test_review_recovery.py b/tests/test_review_recovery.py index 47202ff5..0ec3586e 100644 --- a/tests/test_review_recovery.py +++ b/tests/test_review_recovery.py @@ -226,20 +226,21 @@ def rejected(endpoint, payload, **kwargs): assert support.marker(head, "primary", "repost") in support.posted_review(gh)["body"] -@pytest.mark.parametrize("failure", ["timeout", "transient"]) -def test_recovery_transport_caps_request_time_and_does_not_retry(monkeypatch, failure): - timeouts = [] +@pytest.mark.parametrize("failure,budget", [("timeout", 0.5), ("transient", 0.5), ("transient", 10), ("write", 0.5)]) +def test_recovery_transport_retries_only_within_deadline(monkeypatch, failure, budget): + timeouts, sleeps = [], [] def request(argv, **kwargs): timeouts.append(kwargs["timeout"]) - if failure == "timeout": + if failure in {"timeout", "write"}: raise _proc.ProcTimeout("timeout") return _proc.Completed(1, "", "HTTP 503", 0) monkeypatch.setattr(github, "run", request) - monkeypatch.setattr(github, "app_token", lambda: "") - monkeypatch.setattr(github.time, "monotonic", lambda: 10.0) - with github.bounded_reads(github.time.monotonic() + 0.5), pytest.raises((github.GhError, _proc.ProcTimeout)): - github.api_get("repos/acme/widgets/pulls/7/reviews") - assert timeouts == [0.5] + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + monkeypatch.setattr(github.time, "monotonic", lambda: 10.0 + sum(sleeps) + int(failure == "write" and bool(timeouts))) + error = github.GhError if failure == "transient" else _proc.ProcTimeout + with pytest.raises(error), github.bounded_reads(10 + budget, retry=True): + github.mark_ready("acme/widgets", 7) if failure == "write" else github.api_get("repos/acme/widgets/pulls/7/reviews") + assert (timeouts, sleeps) == (([10, 5], [5]) if budget == 10 else ([120 if failure == "write" else 0.5], [])) @pytest.mark.parametrize("source", ["model", "repost"])