From bf8215ba4fa7ef0073221631505cfc051cd1182a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:21:06 +0100 Subject: [PATCH] Honor Retry-After on Mergify queue observations Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 5 ++-- src/loopzero/cli.py | 24 ++++++++++--------- src/loopzero/github.py | 18 ++++++++++----- src/loopzero/mergify.py | 51 ++++++++++++++++++++++++++--------------- tests/test_cli.py | 11 ++++----- tests/test_mergify.py | 42 ++++++++++++++++----------------- 6 files changed, 87 insertions(+), 64 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 49620cba..48fe9dbf 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -354,8 +354,9 @@ one state transition should not become repeated writes that trigger policy CI. GitHub reads and the idempotent thread resolution mutation retry transient 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 +queue reads retry once after two seconds, subject to Retry-After and the +remaining queue wait budget. Calls without a deadline allow less than five +seconds of backoff. See the [contract's waiter and polling rules](../core/CONTRACT.md#failure). The optional host ai-accounts helper owns managed credential selection and exact-model eligibility under its existing lock. Its Claude exec reserve guard (including pinned diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index f1645fb8..2069a1d3 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -277,7 +277,7 @@ def _decide_kind(markers: list[Marker], head: str) -> tuple[str, str | None]: def _readiness( wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None, - *, workflow_wait: bool = False, announce_receipt: bool = False, + *, workflow_wait: bool = False, announce_receipt: bool = False, mergify_deadline: float | None = None, ) -> github.Readiness: if hold := github.merge_hold(pr.number, pr.labels): return github.Readiness(False, (hold,)) @@ -316,7 +316,7 @@ def _readiness( if config.merge_strategy == "mergify" and pr.state == "OPEN": behind = github.behind_reason(pr, head if review else None) reasons = result.reasons - if mergify.configured(config.repo, config.base_branch, config.mergify_queue or ""): + if mergify.configured(config.repo, config.base_branch, config.mergify_queue or "", mergify_deadline): reasons = tuple(reason for reason in reasons if reason != behind) else: reasons = (*reasons, "Mergify queue configuration is unverified or permits in-place head updates") @@ -1184,7 +1184,8 @@ def _load_review(wt: Path, head: str, kind: str) -> ReviewResult: def _pr_readiness( - wt: Path, config: Config, *, allow_merged: bool = False, workflow_wait: bool = False + wt: Path, config: Config, *, allow_merged: bool = False, workflow_wait: bool = False, + mergify_deadline: float | None = None, ) -> tuple[github.PR, github.Readiness | None]: """PR plus readiness; readiness is None only for an already merged PR (allow_merged).""" branch, head = worktree.branch(wt), worktree.head(wt) @@ -1194,7 +1195,7 @@ def _pr_readiness( if pr.state == "MERGED": return pr, None return pr, _readiness(wt, config, pr, head, workflow_wait=workflow_wait, - announce_receipt=True) + announce_receipt=True, mergify_deadline=mergify_deadline) CLEANUP_RETRY = "; fix the cause, then rerun `loopzero merge` in this worktree to finish cleanup" @@ -1405,7 +1406,8 @@ def _wait_for_checks( previous = _verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha, previous) if allow_merged and current.state == "MERGED": return current, None, kicked - readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True) + readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True, + mergify_deadline=started + timeout) if not kicked and _draft_checks_waiting(config, current, readiness): github.mark_ready(config.repo, pr.number) print("marked ready; " + "; ".join(readiness.reasons)) @@ -1561,9 +1563,9 @@ def _wait_for_mergify( sha = _landed(config, pr, closed) if sha: return sha - if not mergify.configured(config.repo, config.base_branch, queue): + if not mergify.configured(config.repo, config.base_branch, queue, started + timeout): raise CliError("Mergify queue configuration became unsafe or unavailable while waiting") - state = mergify.membership(config.repo, pr.number, queue) + state = mergify.membership(config.repo, pr.number, queue, started + timeout) deferred_landing_read = confirmed and state is not None and not closed if not deferred_landing_read and (sha := _landed(config, pr, closed)): return sha @@ -1601,7 +1603,7 @@ def _merge_with_mergify( requested, confirmed_marker = mergify.markers( config.repo, pr.number, pr.head_sha, queue ) - state = mergify.membership(config.repo, pr.number, queue) + state = mergify.membership(config.repo, pr.number, queue, deadline) if sha := github.merged_sha( config.repo, pr.number, expected_head=pr.head_sha, check_hold=not requested and state is None, ): @@ -1642,11 +1644,11 @@ def cmd_merge(args: argparse.Namespace) -> int: mergify.dequeue(config.repo, pr.number) print(f"requested removal of PR #{pr.number} from Mergify") return 0 - pr, readiness = _pr_readiness( - wt, config, allow_merged=True, workflow_wait=args.wait is not None - ) started = time.monotonic() deadline = None if args.wait is None else started + args.wait + pr, readiness = _pr_readiness( + wt, config, allow_merged=True, workflow_wait=args.wait is not None, mergify_deadline=deadline, + ) # --wait=0 observes once; a positive budget also bounds merge or queue admission. admit_by = deadline if args.wait else None if readiness is not None and args.wait is not None and _pending_checks(config, pr, readiness): diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 23200686..29e5acb2 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -334,15 +334,21 @@ def _retry_pause(delay: float | None, limit: float, *, scoped: bool = True) -> b 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", "") +def retry_after(value: str) -> float | None: try: - wait = int(value) if re.fullmatch(r"[0-9]{1,18}", value) else parsedate_to_datetime(value).timestamp() - time.time() + if re.fullmatch(r"[0-9]{1,18}", value): + return float(value) + date = parsedate_to_datetime(value) + return max(0.0, date.timestamp() - time.time()) if date.tzinfo is not None else None except (OverflowError, OSError, ValueError): return None - return max(delay, wait) + + +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 + wait = retry_after(headers.get("retry-after", "")) + return None if wait is None else max(delay, wait) def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 347ea599..7a202d87 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -81,7 +81,22 @@ def _open(request: urllib.request.Request): raise MergifyError("Mergify API request has an invalid URL or header") from None -def api_get(repo: str, suffix: str) -> object | None: +def _wait_to_retry(delay: float, deadline: float | None) -> bool: + remaining = 5.0 if deadline is None else deadline - time.monotonic() + if delay >= remaining: + return False + _retry_sleep(delay) + return deadline is None or time.monotonic() < deadline + + +def _queue_read_failure(exc: Exception) -> tuple[str, bool]: + if isinstance(exc, (json.JSONDecodeError, UnicodeDecodeError)): + return "Mergify queue lookup returned no valid JSON", True + reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc + return f"Mergify queue transport failed: {reason}", not isinstance(reason, ssl.SSLCertVerificationError) + + +def api_get(repo: str, suffix: str, deadline: float | None = None) -> object | None: """GET one documented endpoint below this repository's fixed Mergify API path.""" if not suffix.startswith("/") or "://" in suffix or ".." in suffix: raise ValueError("Mergify API suffix must be a repository-relative absolute path") @@ -92,26 +107,26 @@ def api_get(repo: str, suffix: str) -> object | None: headers={"Accept": "application/json", "User-Agent": "loopzero", "Authorization": f"Bearer {_credential()}"}, ) - for delay in (2.0, 5.0, None): # reads retry server errors, throttling and dropped reads + for retry in (True, False): + delay = 2.0 try: with _open(request) as response: return json.load(response) except urllib.error.HTTPError as exc: if exc.code == 404: return None - if delay is None or not (exc.code >= 500 or exc.code == 429): - raise MergifyError(f"Mergify queue lookup failed with HTTP {exc.code}") from exc - except (OSError, http.client.IncompleteRead) as exc: - reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc - if delay is None or isinstance(reason, ssl.SSLCertVerificationError): - raise MergifyError(f"Mergify queue transport failed: {reason}") from exc - except (json.JSONDecodeError, UnicodeDecodeError) as exc: - if delay is None: - raise MergifyError("Mergify queue lookup returned no valid JSON") from exc - _retry_sleep(delay) + wait = github.retry_after(exc.headers.get("Retry-After", "")) if exc.headers else None + delay = max(delay, wait or 0.0) + detail = f"Mergify queue lookup failed with HTTP {exc.code}" + (f"; Retry-After: {wait:g}s" if wait is not None else "") + transient = exc.code >= 500 or exc.code == 429 or (exc.code == 403 and wait is not None) + except (OSError, json.JSONDecodeError, UnicodeDecodeError, http.client.IncompleteRead) as exc: + detail, transient = _queue_read_failure(exc) + if not retry or not transient: + raise MergifyError(detail) + if not _wait_to_retry(delay, deadline): + raise MergifyError(f"{detail}; retry delay exceeds the wait budget") return None - def _unmet_conditions(node: object) -> tuple[str, ...]: if not isinstance(node, dict) or node.get("match") is not False: return () @@ -122,8 +137,8 @@ def _unmet_conditions(node: object) -> tuple[str, ...]: return (label,) if isinstance(label, str) and label.isprintable() else () -def membership(repo: str, number: int, queue: str) -> Membership | None: - data = api_get(repo, f"/merge-queue/pull/{number}") +def membership(repo: str, number: int, queue: str, deadline: float | None = None) -> Membership | None: + data = api_get(repo, f"/merge-queue/pull/{number}", deadline) if data is None: return None try: @@ -192,12 +207,12 @@ def construct_mapping(self, node, deep=False): and isinstance(metadata, dict) and metadata.get("default_branch") == branch) -def configured(repo: str, branch: str, queue: str) -> bool: +def configured(repo: str, branch: str, queue: str, deadline: float | None = None) -> bool: """Require live queue identity and stable canonical speculative configuration.""" - status_data = api_get(repo, f"/merge-queue/status?branch={quote(branch, safe='')}") + status_data = api_get(repo, f"/merge-queue/status?branch={quote(branch, safe='')}", deadline) if status_data is None: return False - rules_data = api_get(repo, "/queues/configuration") + rules_data = api_get(repo, "/queues/configuration", deadline) if not isinstance(status_data, dict) or not isinstance(rules_data, dict): return False if not isinstance(status_data.get("batches"), list): diff --git a/tests/test_cli.py b/tests/test_cli.py index 5c136d5d..41704958 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2423,7 +2423,7 @@ def source_queue_api(gh, monkeypatch): }) vendor_calls = [] - def get(_repo, path): + def get(_repo, path, *_): vendor_calls.append(path) return { "/merge-queue/status?branch=main": {"batches": [], "mode": "serial"}, @@ -4156,7 +4156,7 @@ def configured(*args): assert cli._wait_for_mergify(config, pr, 60, confirmed=True) == "e" * 40 assert clock.sleeps == [30, 30] - assert configurations == [(REPO, "main", "main")] * 3 + assert configurations == [(REPO, "main", "main", 60)] * 3 assert reads_at_membership == [1, 2, 3] assert [c["argv"][:2] for c in gh.calls] == [detail] * 4 @@ -4200,9 +4200,8 @@ def test_mergify_wait_outcomes_preserve_unmerged_work(wt, repo, gh, capsys, monk snapshots.extend((merge_json(head=head), merge_json(state="MERGED", head="f" * 40, sha="e" * 40))) gh.append(f"api repos/{REPO}/pulls/7", *snapshots) configurations = [] - - def configured(*_): - configurations.append(True) + def configured(*args): + configurations.append(args[-1]) if len(configurations) > 1: if outcome == "config_error": raise mergify.MergifyError("configuration HTTP 503") @@ -4246,7 +4245,7 @@ def remove_worktree_then_poll(*args): assert clock.sleeps == ([30, 60, 120, 40] if jitter == 1 else [27, 54, 108, 61]) assert sum(c["argv"][:2] == PR_LIST_READ for c in gh.calls) == 1 assert sum(c["argv"][:2] == ["api", "graphql"] for c in gh.calls) == 2 - assert requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) + assert requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) and all(deadline == (250 if outcome == "timeout" else 0) for deadline in configurations) if outcome in {"merged", "already_merged", "worktree_removed"}: assert code == 0 and "e" * 40 in out and not wt.exists(), err if outcome == "worktree_removed": diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 4381b961..bcf384b5 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -97,7 +97,7 @@ def open_(request): # a transient failure must not repeat the write @pytest.fixture def queue_api(monkeypatch): - monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( + monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix, *_: ( {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else {"configuration": [{"name": "main", "config": {"allow_inplace_checks": True}}]} )) @@ -155,7 +155,7 @@ def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch) def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch): queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1")) - monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( + monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix, *_: ( {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else {"configuration": [{"name": "main", "config": {"allow_inplace_checks": False}}]} )) @@ -230,30 +230,30 @@ def test_hosted_import_does_not_load_yaml(): assert result.returncode == 0, result.stderr -@pytest.mark.parametrize("failure", ["http503", "dropped_read", "truncated"]) -def test_api_get_retries_transient_reads(monkeypatch, failure): - calls = [] - - class Body(io.BytesIO): - def read(self, *args): - if len(calls) == 1 and failure != "http503": # body read fails once - raise {"dropped_read": ConnectionResetError(), "truncated": mergify.http.client.IncompleteRead(b"{")}[failure] - return super().read(*args) - +@pytest.mark.parametrize("failure,status,budget,wait", [ + ("http", 503, None, 2), ("reset", None, None, 2), ("truncated", None, None, 2), + ("http", 429, 100, 40), ("http", 429, None, None), ("http", 403, 20, None), ("http", 429, 20, None)]) +def test_api_get_retries_transient_reads(monkeypatch, failure, status, budget, wait): + calls, sleeps = [], [] def fake_open(request): - calls.append(request.get_method()) - if failure == "http503" and len(calls) == 1: - raise urllib.error.HTTPError(request.full_url, 503, "x", {}, None) - return Body(b"{}") - + calls.append((request.get_method(), sum(sleeps))) + if status in {403, 429} or len(calls) == 1: + if status: + raise urllib.error.HTTPError(request.full_url, status, "x", {"Retry-After": "40"} if status < 500 else {}, None) + raise ConnectionResetError() if failure == "reset" else mergify.http.client.IncompleteRead(b"{") + return io.BytesIO(b"{}") monkeypatch.setattr(mergify, "_open", fake_open) - monkeypatch.setattr(mergify, "_retry_sleep", lambda _: None) + monkeypatch.setattr(mergify, "_retry_sleep", sleeps.append) monkeypatch.setattr(mergify, "_credential", lambda: "k") - assert mergify.api_get("acme/widgets", "/merge-queue/status") == {} - assert calls == ["GET", "GET"] + if status in {403, 429}: + with pytest.raises(mergify.MergifyError, match="Retry-After: 40s" + ("; retry delay exceeds" if wait is None else "")): + mergify.api_get("acme/widgets", "/merge-queue/status", None if budget is None else mergify.time.monotonic() + budget) + else: + assert mergify.api_get("acme/widgets", "/merge-queue/status") == {} + assert calls == ([("GET", 0)] if wait is None else [("GET", 0), ("GET", wait)]) @pytest.mark.parametrize("reason, expected_sleeps", [ - ("DNS lookup failed", [2.0, 5.0]), + ("DNS lookup failed", [2.0]), (ssl.SSLCertVerificationError("certificate verification failed"), []), ]) def test_api_get_classifies_terminal_transport_failure(monkeypatch, reason, expected_sleeps):