diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 24a62b50..b1cead5b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -13,6 +13,7 @@ import fcntl import hashlib import json +import math import os import random import re @@ -128,7 +129,7 @@ def _load_config( print("checks are unpinned because --config was provided") return config_mod.load(args.config or root / "workflow.toml", require_ci=require_ci) config = config_mod.load_trusted(root, previous=previous, refresh=refresh, - require_ci=require_ci, read_timeout=github._read_timeout) + require_ci=require_ci, read_timeout=github.read_timeout) if args.command == "check": if not config.checks: raise config_mod.ConfigError( @@ -1523,7 +1524,7 @@ def _wait_for_checks( if allow_merged and current.state == "MERGED": return current, None, kicked readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True, - mergify_deadline=started + timeout) + mergify_deadline=started + timeout if bounded else None) if not kicked and _draft_checks_waiting(config, current, readiness): _mark_ready(wt, config, pr.number, current.head_sha) print("marked ready; " + "; ".join(readiness.reasons)) @@ -1563,15 +1564,39 @@ def _wait_for_checks( return None +def _queue_wait( + deadline: float, poll: Callable[[float], str | None], *, + bounded: bool, timeout_notice: str = "", +) -> str | None: + if not bounded: # Explicit --wait=0 still observes once. + return poll(0) + sha = None + reported_timeout = False + try: + with github.bounded_reads(deadline, token=None, retry=True): + remaining = github.read_timeout(math.inf) + try: + sha = poll(remaining) + reported_timeout = sha is None + except (LoopZeroError, github.GhError, _proc.ProcTimeout): + github.read_timeout(0) + raise + except github.ReadDeadline: + if sha is None and timeout_notice and not reported_timeout: + print(timeout_notice) + return sha + + def _landed(config: Config, pr: github.PR, closed: list[github.GhError]) -> str | None: - """Merge SHA if landed; a closed-unmerged read is held as not final (GitHub lags a - queue merge) and re-raised by the caller only if it persists to the deadline.""" + """Merge SHA if landed; a closed-unmerged read is held as not final.""" try: sha = github.merged_sha(config.repo, pr.number, expected_head=pr.head_sha) except github.ClosedUnmerged as exc: closed[:] = [exc] - return None - closed.clear() + sha = None + else: + closed.clear() + github.read_timeout(0) return sha @@ -1580,26 +1605,52 @@ def _wait_for_merge(config: Config, pr: github.PR, timeout: float) -> str | None started = time.monotonic() closed: list[github.GhError] = [] print(f"PR #{pr.number} is queued for merge into {config.base_branch}; waiting") - for _ in _poll_until(started, timeout): - if sha := _landed(config, pr, closed): - return sha - if not github.merge_pending(config.repo, pr.number, pr.head_sha): - if sha := _landed(config, pr, closed): + with suppress(github.ReadDeadline): + for _ in _poll_until(started, timeout, bounded=bool(timeout)): + sha = _landed(config, pr, closed) + if sha: return sha - if not closed: + if not github.merge_pending(config.repo, pr.number, pr.head_sha): + sha = _landed(config, pr, closed) + if sha: + return sha + if closed: + continue raise CliError(f"PR #{pr.number} left the merge queue unmerged") - if closed: - raise closed[0] + _report_closed_observation(closed) return None +def _report_closed_observation(closed: list[github.GhError]) -> None: + if closed: + try: + github.read_timeout(0) + except github.ReadDeadline: + print(f"last queue observation: {closed[0]}") + else: + raise closed[0] + + +def _merge_and_follow( + config: Config, pr: github.PR, deadline: float | None, admit_by: float | None, +) -> str | None: + try: + sha = github.merge(config.repo, pr.number, config.merge_strategy, pr.head_sha, observation_deadline=admit_by) + except github.ReadDeadline: + return None + if sha is None and deadline is not None: + return _queue_wait(deadline, partial(_wait_for_merge, config, pr), bounded=admit_by is not None) + return sha + + def _mergify_timeout_detail( - config: Config, pr: github.PR, queue: str, state: mergify.Membership | None, + config: Config, pr: github.PR, queue: str, state: mergify.Membership | None, *, query_report: bool, ) -> str: if state is None: report = None - with suppress(github.GhError): - _, _, report = mergify.request_status(config.repo, pr.number, pr.head_sha, queue) + if query_report: + with suppress(github.GhError): + _, _, report = mergify.request_status(config.repo, pr.number, pr.head_sha, queue) return f"waiting for admission to Mergify queue {queue}. " + ( f"Mergify report: {report}" if report else "Check the PR for Mergify's admission report." ) @@ -1666,33 +1717,30 @@ def _wait_for_mergify( queue = config.mergify_queue assert queue is not None state = None - deferred_landing_read = False print(f"PR #{pr.number} following Mergify queue {queue}; head {pr.head_sha[:12]}; waiting up to {timeout:g}s") - polls = _poll_until(started, timeout, admitted=lambda: confirmed) - for _ in polls: - sha = _landed(config, pr, closed) - if sha: - return sha - 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, 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 - if state is not None and not confirmed: - mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) - confirmed = True - print(f"PR #{pr.number} confirmed in Mergify queue {queue}; waiting") - elif state is None: - if sha := _mergify_departure(config, pr, queue, closed, confirmed): + deadline = started + timeout if timeout else None + polls = _poll_until(started, timeout, bounded=bool(timeout), admitted=lambda: confirmed) + with suppress(github.ReadDeadline): + for _ in polls: + sha = _landed(config, pr, closed) + if sha: return sha - # A queued, open PR normally gets its next landing read on the next tick. - if deferred_landing_read and (sha := _landed(config, pr, closed)): - return sha - if closed: - raise closed[0] + if not mergify.configured(config.repo, config.base_branch, queue, deadline): + raise CliError("Mergify queue configuration became unsafe or unavailable while waiting") + state = mergify.membership(config.repo, pr.number, queue, deadline) + defer_landing = timeout and confirmed and state is not None and not closed + if not defer_landing and (sha := _landed(config, pr, closed)): + return sha + if state is not None and not confirmed: + mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) + confirmed = True + print(f"PR #{pr.number} confirmed in Mergify queue {queue}; waiting") + elif state is None: + if sha := _mergify_departure(config, pr, queue, closed, confirmed): + return sha + _report_closed_observation(closed) print(f"timed out waiting for Mergify to land PR #{pr.number}") - print(_mergify_timeout_detail(config, pr, queue, state)) + print(_mergify_timeout_detail(config, pr, queue, state, query_report=not timeout)) return None @@ -1704,17 +1752,20 @@ class _AdmissionDeadline(Exception): def _follow_blocked_mergify( - config: Config, pr: github.PR, readiness: github.Readiness, queue: str, deadline: float | None, + config: Config, pr: github.PR, readiness: github.Readiness, queue: str, deadline: float | None, *, bounded: bool, ) -> str | None: hint = _merge_check_hint(config, pr, readiness) try: confirmed = (deadline is not None and pr.base_ref == config.base_branch - and mergify.membership(config.repo, pr.number, queue) is not None) + and mergify.membership(config.repo, pr.number, queue, deadline if bounded else None) is not None) + except github.ReadDeadline: + print(f"timed out waiting for Mergify to land PR #{pr.number}") + return None except mergify.MergifyError as exc: confirmed = False hint += f"; Mergify membership unverified: {exc}" if confirmed: - return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), True) + return _queue_wait(deadline, partial(_wait_for_mergify, config, pr, confirmed=True), bounded=bounded) raise CliError("not ready to request Mergify: " + "; ".join(_readiness_messages(pr, readiness)) + hint) @@ -1726,12 +1777,12 @@ def _merge_with_mergify( queue = config.mergify_queue assert queue is not None if not readiness.ready: - return _follow_blocked_mergify(config, pr, readiness, queue, deadline) + return _follow_blocked_mergify(config, pr, readiness, queue, deadline, bounded=admit_by is not None) with worktree.lock_local_state(wt): requested, confirmed_marker = mergify.markers( config.repo, pr.number, pr.head_sha, queue ) - state = mergify.membership(config.repo, pr.number, queue, deadline) + state = mergify.membership(config.repo, pr.number, queue, admit_by) if sha := github.merged_sha( config.repo, pr.number, expected_head=pr.head_sha, check_hold=not requested and state is None, ): @@ -1752,7 +1803,10 @@ def _merge_with_mergify( _require_receipt(wt, config, pr.head_sha) mergify.request(config.repo, pr.number, pr.head_sha, queue) if deadline is not None: - return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), confirmed) + return _queue_wait( + deadline, lambda remaining: _wait_for_mergify(config, pr, remaining, confirmed), + bounded=admit_by is not None, timeout_notice=f"timed out waiting for Mergify to land PR #{pr.number}", + ) state_name = "confirmed in" if confirmed else "requested from" print(f"PR #{pr.number} {state_name} Mergify queue {queue}; {_FOLLOW_QUEUE}") return None @@ -1772,11 +1826,15 @@ def cmd_merge(args: argparse.Namespace) -> int: return 0 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 + try: + pr, readiness = _pr_readiness( + wt, config, branch, allow_merged=True, workflow_wait=args.wait is not None, mergify_deadline=admit_by, + ) + except github.ReadDeadline: + print("timed out while checking merge readiness") + return 3 if readiness is not None and args.wait is not None and _pending_checks(config, pr, readiness): # One waiter and one deadline span source checks and landing: a check created # by the ready transition must not end the turn between `ready` and the queue. @@ -1794,8 +1852,9 @@ def cmd_merge(args: argparse.Namespace) -> int: elif config.merge_strategy == "mergify": try: sha = _merge_with_mergify(wt, config, pr, readiness, deadline, admit_by) - except _AdmissionDeadline: - print(f"timed out before requesting Mergify for PR #{pr.number}") + except (_AdmissionDeadline, github.ReadDeadline) as exc: + action = "before requesting Mergify for" if isinstance(exc, _AdmissionDeadline) else "waiting for Mergify to land" + print(f"timed out {action} PR #{pr.number}") return 3 if sha is None: return 3 if args.wait is not None else 0 @@ -1807,15 +1866,15 @@ def cmd_merge(args: argparse.Namespace) -> int: print(f"timed out before merging PR #{pr.number}") return 3 _require_receipt(wt, config, pr.head_sha) - sha = github.merge(config.repo, pr.number, config.merge_strategy, pr.head_sha) + sha = _merge_and_follow(config, pr, deadline, admit_by) + if sha is None and deadline is not None: + print(f"timed out waiting for the merge queue to land PR #{pr.number}") + return 3 if sha is None: - if args.wait is None: - print(f"PR #{pr.number} is queued for merge into {config.base_branch}; {_FOLLOW_QUEUE}") - return 0 - sha = _wait_for_merge(config, pr, max(0.0, deadline - time.monotonic())) - if sha is None: - print(f"timed out waiting for the merge queue to land PR #{pr.number}") - return 3 + print( + f"PR #{pr.number} is queued for merge into {config.base_branch}; {_FOLLOW_QUEUE}" + ) + return 0 _cleanup_remote_refs(wt, config, branch, pr.head_sha) _cleanup(wt, pr) print(sha) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 1713ce20..a69f47ae 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -11,7 +11,7 @@ import tempfile import time from collections.abc import Iterator -from contextlib import contextmanager, suppress +from contextlib import contextmanager, nullcontext, suppress from contextvars import ContextVar from dataclasses import dataclass from datetime import UTC, datetime @@ -148,12 +148,13 @@ def bounded_reads(deadline: float, token: str | None = "", *, retry: bool = Fals scope = _read_scope.set((deadline, token, retry)) try: yield - _read_timeout(0) + read_timeout(0) finally: _read_scope.reset(scope) -def _read_timeout(limit: float, *, scoped: bool = True) -> float: +def read_timeout(limit: float, *, scoped: bool = True) -> float: + """Cap an I/O timeout or retry delay to the active read budget.""" scope = _read_scope.get() if scoped else None if scope is None: return limit @@ -295,7 +296,7 @@ def app_token() -> str: return "" minted = _app_token_clock() # before minting so a suspend mid-call ages the token try: - result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_BASE_ENV, timeout=_read_timeout(10)) + result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_BASE_ENV, timeout=read_timeout(10)) except (ToolMissing, ProcTimeout, ReadDeadline, OSError): return "" if result.exit_code or not result.stdout.strip(): @@ -325,7 +326,7 @@ def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> boo def _retry_pause(delay: float | None, limit: float, *, scoped: bool = True) -> bool: - if delay is None or delay >= _read_timeout(limit, scoped=scoped): + if delay is None or delay >= read_timeout(limit, scoped=scoped): return False _retry_sleep(delay) return True @@ -375,12 +376,12 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, try: done = run(list(argv), cwd=cwd, env_allowlist=GH_ENV, extra_env={"GH_TOKEN": selected} if selected else None, - timeout=_read_timeout(timeout, scoped=read_only), encoding="utf-8") + timeout=read_timeout(timeout, scoped=read_only), encoding="utf-8") 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: - _read_timeout(timeout, scoped=bool(scope and scope[2])) + 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), @@ -465,7 +466,7 @@ def _graphql_reset(args: tuple[str, ...], tail: str, cwd: Path, token: str = "") query = "query { rateLimit { remaining resetAt } }" result = run(["gh", "api", "graphql", "-f", f"query={query}"], cwd=cwd, env_allowlist=GH_ENV, extra_env={"GH_TOKEN": token} if token else None, - timeout=_read_timeout(10)) + timeout=read_timeout(10)) if result.exit_code: return "" data = json.loads(result.stdout) @@ -1446,6 +1447,8 @@ def merge_pending(repo: str, number: int, head_sha: str) -> bool: auto = pr.get("autoMergeRequest") if type(queued) is not bool or (auto is not None and not isinstance(auto, dict)): raise ValueError("invalid queue fields") + except ReadDeadline: + raise except (GhError, ProcTimeout, KeyError, TypeError, ValueError) as exc: raise MergeFailed(("gh", "api", "graphql"), f"GitHub queue lookup for PR #{number}: queue status could not be verified. " @@ -1455,7 +1458,9 @@ def merge_pending(repo: str, number: int, head_sha: str) -> bool: return queued or bool(auto) -def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: +def merge( + repo: str, number: int, strategy: str, head_sha: str, *, observation_deadline: float | None = None, +) -> str | None: """Merge PR `number` at exactly `head_sha` and return the verified merge SHA. Returns None when the base branch uses a merge queue and GitHub accepted the PR @@ -1468,16 +1473,41 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: argv = ( "pr", "merge", str(number), "--repo", repo, *method, "--match-head-commit", head_sha, ) - if strategy == "queue" and merge_pending(repo, number, head_sha): - return None + def observation(): + return (bounded_reads(observation_deadline, token=None, retry=True) + if observation_deadline is not None else nullcontext()) + + if strategy == "queue": + with observation(): + if merge_pending(repo, number, head_sha): + return None write_error = None try: _gh(*argv, timeout=300) except (GhError, ProcTimeout, OSError) as exc: write_error = exc - sha = merged_sha(repo, number, expected_head=head_sha) - if sha: + # A synchronous merge already in flight still needs verification and cleanup. + if strategy != "queue" and (sha := merged_sha(repo, number, expected_head=head_sha)): return sha + sha = None + try: + with observation(): + sha = _verify_merge_request(repo, number, head_sha, argv, write_error, observe_landing=strategy == "queue") + except ReadDeadline: + if sha is None: + raise + return sha + + +def _verify_merge_request( + repo: str, number: int, head_sha: str, argv: tuple[str, ...], write_error: Exception | None, *, + observe_landing: bool, +) -> str | None: + if observe_landing: + sha = merged_sha(repo, number, expected_head=head_sha) + read_timeout(0) + if sha: + return sha queue_error = None try: if merge_pending(repo, number, head_sha): @@ -1486,6 +1516,7 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None: queue_error = exc # The queue may have landed the PR between the two reads; look once more. sha = merged_sha(repo, number, expected_head=head_sha) + read_timeout(0) if sha: return sha if queue_error: diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 3aa8c60a..d8db29c3 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -5,6 +5,7 @@ import base64 import http.client import json +import math import os import re import signal @@ -13,7 +14,7 @@ import time import urllib.error import urllib.request -from contextlib import ExitStack, contextmanager, suppress +from contextlib import ExitStack, contextmanager, nullcontext, suppress from dataclasses import dataclass from pathlib import Path from urllib.parse import quote @@ -81,6 +82,7 @@ class _RequestDeadline(Exception): @contextmanager def _open(request: urllib.request.Request, timeout: float = 30): + timeout = github.read_timeout(timeout) def expire(_signum, _frame): raise _RequestDeadline() @@ -121,13 +123,19 @@ def api_get(repo: str, suffix: str, deadline: float | None = None) -> object | N """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) + with github.bounded_reads(deadline, token=None, retry=True) if deadline is not None else nullcontext(): + return _read_queue(_api_request(repo, suffix), deadline) + + +def _read_queue(request: urllib.request.Request, deadline: float | None) -> object | None: retry = True while True: wait = None try: with _open(request) as response: - return json.load(response) + payload = json.load(response) + github.read_timeout(0) + return payload except urllib.error.HTTPError as exc: if exc.code == 404: return None @@ -142,7 +150,12 @@ def api_get(repo: str, suffix: str, deadline: float | None = None) -> object | N transient = not isinstance(reason, ssl.SSLCertVerificationError) if not retry or not transient: raise MergifyError(detail) - if not _wait_to_retry(max(2.0, wait or 0.0), deadline): + delay = max(2.0, wait or 0.0) + remaining = github.read_timeout(math.inf) + if wait is None and delay >= remaining: + _retry_sleep(remaining) + github.read_timeout(0) + if delay >= remaining or not _wait_to_retry(delay, deadline): raise MergifyError(f"{detail}; retry delay exceeds the wait budget") retry = False diff --git a/tests/test_cli.py b/tests/test_cli.py index 44240c54..4499e394 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -413,7 +413,7 @@ def test_wait_reports_only_check_changes(wt, gh, head, capsys, monkeypatch, comm arm_check_runs(gh, head, *runs) poll_clock(monkeypatch) if command == "merge": - monkeypatch.setattr(github, "merge", lambda *a: "c" * 40) + monkeypatch.setattr(github, "merge", lambda *a, **k: "c" * 40) monkeypatch.setattr(cli, "_cleanup_remote_refs", lambda *a: None) monkeypatch.setattr(cli, "_cleanup", lambda *a: None) code, out, err = run(capsys, command, "--wait=1800") @@ -4122,7 +4122,7 @@ def test_merge_wait_preserves_reviewed_head_and_cleans_only_landed_work( assert code == 1 and "PR head changed" in err assert wt.exists(), "no cleanup after an unreviewed head" elif outcome == "still-closed": - assert code == 1 and "closed without a verified merge" in err and wt.exists() + assert code == 3 and "closed without a verified merge" in out and wt.exists() elif ejected: assert (code, wt.exists()) == ((0, False) if landed else (1, True)) assert ("e" * 40 if landed else "left the merge queue unmerged") in out + err @@ -4429,7 +4429,7 @@ def test_mergify_confirmed_wait_reads_pr_once_per_steady_poll(wt, gh, monkeypatc def membership(*_): reads_at_membership.append(len(gh.calls)) - if confirmed and clock.now == 60: + if confirmed and clock.now == 30: gh.respond(" ".join(detail), merge_json(state="MERGED", head=head, sha="e" * 40)) return mergify.Membership() if confirmed or clock.now >= 210 else None @@ -4438,12 +4438,12 @@ def membership(*_): " ".join(detail), merge_json(state="MERGED", head=head, sha="e" * 40))) monkeypatch.setattr(mergify, "membership", 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", 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) + assert cli._wait_for_mergify(config, pr, 90 if confirmed else 360, confirmed=confirmed) == "e" * 40 + assert clock.sleeps == ([30, 55] if confirmed else [30, 60, 120, 30]) + assert configurations == [(REPO, "main", "main", 90 if confirmed else 360)] * (2 if confirmed else 4) + assert reads_at_membership == ([1, 2] if confirmed else [1, 4, 7, 10]) + assert sum(c["argv"][:2] == detail for c in gh.calls) == (3 if confirmed else 9) + assert len(gh.calls) == (3 if confirmed else 12) @pytest.mark.parametrize("outcome,jitter", [ @@ -4535,11 +4535,11 @@ def remove_worktree_then_poll(*args, **kwargs): monkeypatch.chdir(repo) if outcome == "timeout": assert f"following Mergify queue main; head {head[:12]}; waiting up to 250s" in out - assert clock.sleeps == ([30, 60, 120, 40] if jitter == 1 else [27, 54, 108, 61]) + assert clock.sleeps == ([30, 60, 120, 36, 4] if jitter == 1 else [27, 54, 108, 56, 5]) 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 queue_requests == ([(REPO, 7, head, "main")] if outcome == "requested_head_changed" else []) - assert all(deadline == (250 if outcome == "timeout" else 0) for deadline in configurations) + assert all(deadline == (250 if outcome == "timeout" else None) for deadline in configurations) if outcome.startswith("incompatible_"): assert reads == [True] * (2 if landed else 1) if not landed: @@ -4864,6 +4864,145 @@ def test_generated_pr_body_limit(wt, gh, capsys, monkeypatch, create, extra): assert json.loads(writes[0]["--input"])["body"] == prose + suffix +@pytest.mark.parametrize("wait, latency, state, expected", [ + (1, 3.0, "MERGED", 3), (1, 0.25, "MERGED", 0), (0, 0.0, "MERGED", 0), (1, 0.0, "CLOSED", 3), +]) +def test_merge_queue_landing_within_budget( + wt, gh, capsys, monkeypatch, head, replay_gh, wait, latency, state, expected, +): + publish_workflow(wt, WORKFLOW.replace('merge = "squash"', 'merge = "queue"')) + arm_approved_ready_pr(gh, head, wt, isDraft=False) + clock = [1000.0] + budgets = [] + cleaned = [] + write_timeouts = [] + in_queue = False + run_gh = github.run + monkeypatch.setattr(cli.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr(cli, "_sleep", lambda seconds: clock.__setitem__(0, clock[0] + seconds)) + gh.respond("pr merge", "") + gh.respond("api graphql", threads_json(), native_queue(False, head), native_queue(True, head)) + + def landing(argv, *, timeout, **kwargs): + nonlocal in_queue + if argv[1:3] == ["pr", "merge"]: + in_queue = True + write_timeouts.append(timeout) + if in_queue and argv[1:3] == ["api", f"repos/{REPO}/pulls/7"]: + budgets.append(timeout) + if len(budgets) == 1: + return Completed(0, json.dumps(merge_json(state="OPEN", head=head)), "", 0.0) + clock[0] += latency + sha = "e" * 40 if state == "MERGED" else None + return Completed(0, json.dumps(merge_json(state=state, head=head, sha=sha)), "", latency) + return run_gh(argv, timeout=timeout, **kwargs) + + monkeypatch.setattr(github, "run", landing) + monkeypatch.setattr(cli, "_cleanup_remote_refs", lambda *_: None) + monkeypatch.setattr(cli, "_cleanup", lambda *_: cleaned.append(True)) + + code, out, err = run(capsys, "merge", f"--wait={wait}") + + assert (code, err, bool(cleaned)) == (expected, "", expected == 0) + assert write_timeouts == [300] + assert budgets == ([1.0, 1.0, 0.5] if state == "CLOSED" else [1.0 if wait else 120.0] * 2) + assert ("closed without a verified merge" in out) is (state == "CLOSED") + assert ("timed out waiting for the merge queue" in out) is (expected == 3) + + +def test_direct_merge_verifies_after_queue_wait_deadline(wt, gh, capsys, monkeypatch, head, replay_gh): + arm_approved_ready_pr(gh, head, wt, isDraft=False) + clock = poll_clock(monkeypatch) + run_gh = github.run + cleaned = [] + + def merge_then_verify(argv, *, timeout, **kwargs): + if argv[1:3] == ["pr", "merge"]: + clock.now += 2 + gh.respond(f"api repos/{REPO}/pulls/7", merge_json(state="MERGED", head=head, sha="e" * 40)) + return Completed(0, "", "", 2) + return run_gh(argv, timeout=timeout, **kwargs) + + monkeypatch.setattr(github, "run", merge_then_verify) + monkeypatch.setattr(cli, "_cleanup_remote_refs", lambda *_: None) + monkeypatch.setattr(cli, "_cleanup", lambda *_: cleaned.append(True)) + + code, out, err = run(capsys, "merge", "--wait=1") + assert (code, err, cleaned) == (0, "", [True]) + assert out.splitlines()[-1] == "e" * 40 + + +def test_queue_wait_keeps_landing_verified_before_scope_exit(monkeypatch): + clock = poll_clock(monkeypatch) + + def poll(_remaining): + github.read_timeout(0) + clock.now = 1 + return "e" * 40 + + assert cli._queue_wait(1, poll, bounded=True) == "e" * 40 + + +def test_mergify_resume_bounds_first_membership_read(monkeypatch, capsys): + clock = poll_clock(monkeypatch) + budgets = [] + + def open_request(request, *, timeout): + budgets.append(timeout) + clock.now += 2 + raise TimeoutError("membership response exceeded the budget") + + monkeypatch.setattr(mergify, "_credential", lambda: "test-key") + monkeypatch.setattr(mergify.urllib.request, "build_opener", lambda *_: SimpleNamespace(open=open_request)) + monkeypatch.setattr(cli, "_merge_check_hint", lambda *_: "") + monkeypatch.setattr(cli, "_wait_for_mergify", Mock(side_effect=AssertionError("polled after deadline"))) + cfg = SimpleNamespace(repo=REPO, base_branch="main") + pr = SimpleNamespace(number=7, base_ref="main") + assert cli._follow_blocked_mergify(cfg, pr, None, "main", 1, bounded=True) is None + assert budgets == [1] and "timed out" in capsys.readouterr().out + + +def test_mergify_queue_retries_stop_at_merge_deadline(wt, gh, capsys, monkeypatch, replay_gh): + commit_mergify_configuration(wt) + head = head_of(wt) + arm_approved_ready_pr(gh, head, wt, isDraft=False) + clock = [1000.0] + budgets = [] + sleeps = [] + admitted = False + monkeypatch.setattr(cli.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr(mergify, "markers", lambda *_: (True, True)) + monkeypatch.setattr(mergify, "_credential", lambda: "test-key") + + def membership(*_args): + nonlocal admitted + admitted = True + return mergify.Membership() + + def configured(repo, *_args): + return not admitted or mergify.api_get(repo, "/merge-queue/status") is not None + + def open_request(request, *, timeout): + budgets.append(timeout) + raise mergify.urllib.error.HTTPError(request.full_url, 503, "unavailable", {}, None) + + def sleep(seconds): + sleeps.append(seconds) + clock[0] += seconds + + monkeypatch.setattr(mergify, "membership", membership) + monkeypatch.setattr(mergify, "configured", configured) + monkeypatch.setattr(mergify.urllib.request, "build_opener", lambda *_: SimpleNamespace(open=open_request)) + monkeypatch.setattr(mergify, "_retry_sleep", sleep) + + code, out, err = run(capsys, "merge", "--wait=1") + + assert (code, err) == (3, "") + assert budgets == [1.0] and sleeps == [1.0] + assert "timed out waiting for Mergify to land PR #7" in out + assert not any(call["argv"][:2] == ["api", f"repos/{REPO}/issues/7/comments"] for call in gh.calls) + + @pytest.mark.parametrize("refresh", ["resync", "automatic"]) def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys, refresh): head = head_of(wt)