diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c22c54d7..59fbb446 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -389,8 +389,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 6d8b20c9..57c3ef1c 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -310,6 +310,7 @@ def _readiness_precheck(wt: Path, config: Config, pr: github.PR, head: str, diag def _readiness( wt: Path, config: Config, pr: github.PR, head: str, reviews: list[dict] | None = None, *, workflow_wait: bool = False, announce_receipt: bool = False, diagnostics: bool = False, + mergify_deadline: float | None = None, ) -> github.Readiness: if problem := _readiness_precheck(wt, config, pr, head, diagnostics): return github.Readiness(False, (problem,)) @@ -342,7 +343,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") @@ -1189,7 +1190,8 @@ def _load_review( def _pr_readiness( - wt: Path, config: Config, branch: str, *, allow_merged: bool = False, workflow_wait: bool = False + wt: Path, config: Config, branch: str, *, 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).""" head = worktree.head(wt) @@ -1197,7 +1199,9 @@ def _pr_readiness( pr = _require_pr(config, branch, allow_merged=allow_merged, list_only=True) _require_pushed(pr, head) readiness = None if pr.state == "MERGED" else _readiness( - wt, config, pr, head, workflow_wait=workflow_wait, announce_receipt=True) + wt, config, pr, head, workflow_wait=workflow_wait, announce_receipt=True, + mergify_deadline=mergify_deadline, + ) return pr, readiness @@ -1497,7 +1501,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): _require_receipt(wt, config, current.head_sha) github.mark_ready(config.repo, pr.number) @@ -1648,9 +1653,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 @@ -1705,7 +1710,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, ): @@ -1744,12 +1749,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 - read_started = time.monotonic() - pr, readiness = _pr_readiness( - wt, config, branch, 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, branch, 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): @@ -1757,7 +1761,7 @@ def cmd_merge(args: argparse.Namespace) -> int: # by the ready transition must not end the turn between `ready` and the queue. waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=False, started=started, args=args, allow_merged=True, initial=readiness, - initial_read_time=started - read_started) + initial_read_time=time.monotonic() - started) if waited is None: return 3 pr, readiness, _ = waited diff --git a/src/loopzero/github.py b/src/loopzero/github.py index a8d56ccb..47e37bdf 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -333,15 +333,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 623d669b..cf5dd66b 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -109,31 +109,46 @@ def _api_request(repo: str, suffix: str, method: str | None = None) -> urllib.re ) -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") request = _api_request(repo, suffix) - 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 () @@ -144,8 +159,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: @@ -251,12 +266,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 093a7355..3700b42d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2623,7 +2623,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"}, @@ -4367,7 +4367,7 @@ def membership(*_): assert cli._wait_for_mergify(config, pr, 60 if confirmed else 360, confirmed=confirmed) == "e" * 40 assert clock.sleeps == ([30, 30] if confirmed else [30, 60, 120, 30]) - assert configurations == [(REPO, "main", "main")] * (3 if confirmed else 4) + assert configurations == [(REPO, "main", "main", 60 if confirmed else 360)] * (3 if confirmed else 4) assert reads_at_membership == ([1, 2, 3] if confirmed else [1, 4, 7, 10]) assert sum(c["argv"][:2] == detail for c in gh.calls) == (4 if confirmed else 9) assert len(gh.calls) == (4 if confirmed else 12) @@ -4418,9 +4418,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") @@ -4469,6 +4468,7 @@ def remove_worktree_then_poll(*args, **kwargs): 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 all(deadline == (250 if outcome == "timeout" else 0) for deadline in configurations) if outcome.startswith("incompatible_"): assert reads == [True] * (2 if landed else 1) if not landed: diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 59eb950b..be4356d6 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -95,7 +95,7 @@ def test_dequeue_posts_to_documented_endpoint(request_log): def queue_api(monkeypatch): def github_config(text, *, default="main", changed=False, file_overrides=None, queues=True, inplace=True): rows = [{"name": "main", "config": {"allow_inplace_checks": inplace}}] if queues else [] - 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": rows} )) @@ -214,17 +214,14 @@ def test_hosted_import_does_not_load_yaml(): assert result.returncode == 0, result.stderr -@pytest.mark.parametrize("failure,expected_sleeps", [ - ("http503", [2.0]), ("dropped_read", [2.0]), ("truncated", [2.0]), - ("DNS lookup failed", [2.0, 5.0]), - (ssl.SSLCertVerificationError("certificate verification failed"), []), +@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), + ("DNS lookup failed", None, None, 2), (ssl.SSLCertVerificationError("certificate verification failed"), None, None, None), ]) -def test_api_get_retries_and_classifies_failures(monkeypatch, failure, expected_sleeps): +def test_api_get_retries_and_classifies_failures(monkeypatch, failure, status, budget, wait): calls, sleeps = [], [] - body_errors = { - "dropped_read": ConnectionResetError(), - "truncated": http.client.IncompleteRead(b"{"), - } + body_errors = {"reset": ConnectionResetError(), "truncated": http.client.IncompleteRead(b"{")} class Body(io.BytesIO): def read(self, *args): @@ -233,24 +230,27 @@ def read(self, *args): return super().read(*args) 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) - if failure != "http503" and failure not in body_errors: + calls.append((request.get_method(), sum(sleeps))) + if status in {403, 429} or (status == 503 and len(calls) == 1): + raise urllib.error.HTTPError(request.full_url, status, "x", {"Retry-After": "40"} if status < 500 else {}, None) + if not status and failure not in body_errors: raise urllib.error.URLError(failure) return Body(b"{}") monkeypatch.setattr(mergify, "_open", fake_open) monkeypatch.setattr(mergify, "_retry_sleep", sleeps.append) monkeypatch.setattr(mergify, "_credential", lambda: "k") - if failure == "http503" or failure in body_errors: + 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) + elif status == 503 or failure in body_errors: assert mergify.api_get("acme/widgets", "/merge-queue/status") == {} - assert calls == ["GET", "GET"] else: with pytest.raises(mergify.MergifyError, match="transport failed") as info: mergify.api_get("acme/widgets", "/merge-queue/status") assert str(failure) in str(info.value) - assert sleeps == expected_sleeps + assert calls == ([("GET", 0)] if wait is None else [("GET", 0), ("GET", wait)]) + assert sleeps == ([] if wait is None else [wait]) @pytest.mark.parametrize("phase", ["headers", "body", "cleanup"])