diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index d396193f..c94c0f07 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1309,6 +1309,54 @@ def _prequeue_size_budget( raise CliError("current target size budget failed:\n" + result.stdout.rstrip()) +def _activate_draft(wt: Path, config: Config, pr: github.PR, deadline: float | None, + args: argparse.Namespace | None) -> None: + try: + github.mark_ready(config.repo, pr.number) + return + except (github.GhUnavailable, _proc.ProcTimeout) as exc: + if deadline is None: + raise + failure = f"Draft activation unconfirmed for PR #{pr.number}: {exc}" + retryable = isinstance(exc, _proc.ProcTimeout) or github._transient_error(exc.tail, False) + try: + _recover_draft_activation(wt, config, pr, deadline, args, retryable) + except (CliError, github.GhError, _proc.ProcTimeout, OSError) as exc: + if retryable and isinstance(exc, github.ReadDeadline): + raise + raise CliError(f"{failure} | recovery: {exc}") from exc + + +def _recover_draft_activation(wt: Path, config: Config, pr: github.PR, deadline: float, + args: argparse.Namespace | None, retryable: bool) -> None: + def observe() -> github.PR: + current = github.pr_view(config.repo, pr.number) + _verify_wait_snapshot(args, wt, config, pr.head_sha, current.head_sha) + if current.state != "OPEN" or current.number != pr.number: + raise CliError(f"no open PR #{pr.number} to activate") + return current + + single_observation = args is not None and args.wait == 0 + observation_deadline = time.monotonic() + 5 if single_observation else deadline + with github.bounded_reads(observation_deadline, token=None): + if not observe().is_draft: + return + if not retryable: + raise CliError("GitHub has not confirmed draft activation") + if single_observation: + raise github.ReadDeadline(("gh", "pr", "ready"), "draft activation is still unconfirmed") + if not github._retry_pause(github.RETRY_DELAY, 120): + raise CliError("retry is unavailable in this ready wait") + current = observe() + if not current.is_draft: + return + readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True) + if not (readiness.ready or _draft_checks_waiting(config, current, readiness)): + raise CliError("; ".join(readiness.reasons)) + _prequeue_size_budget(wt, config, current, readiness) + github.mark_ready(config.repo, pr.number, github._read_timeout(120)) + + def cmd_ready(args: argparse.Namespace) -> int: wt, config = _context(args, pin_checks=True) pr, readiness = _pr_readiness(wt, config, worktree.branch(wt), workflow_wait=args.wait is not None) @@ -1316,37 +1364,46 @@ def cmd_ready(args: argparse.Namespace) -> int: waiting = _draft_checks_waiting(config, pr, readiness) kicked = bool(waiting) started = time.monotonic() - if waiting: - github.mark_ready(config.repo, pr.number) - if args.wait is None: - pending = f"; {MERGEABILITY_PENDING}" if pr.mergeable == "UNKNOWN" else "" - print(f"marked ready; waiting for required checks: {', '.join(waiting)}{pending}; {NEXT_WAIT}") - return 3 - print("marked ready; " + "; ".join(readiness.reasons)) - if args.wait is not None and ( - waiting or _pending_checks(config, pr, readiness, allow_skipped=not pr.is_draft) - ): - waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=kicked, started=started, - shown=readiness.reasons if kicked else (), args=args, - allow_skipped=True, initial=None if kicked else readiness) - if waited is None: - return 3 - pr, readiness, kicked = waited - assert readiness is not None - _prequeue_size_budget(wt, config, pr, readiness) - if readiness.ready and pr.is_draft and not kicked: - github.mark_ready(config.repo, pr.number) - if args.wait is not None: - waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started, - args=args, allow_skipped=True) + deadline = None if args.wait is None else started + args.wait + try: + if waiting: + _activate_draft(wt, config, pr, deadline, args) + if args.wait is None: + pending = f"; {MERGEABILITY_PENDING}" if pr.mergeable == "UNKNOWN" else "" + print(f"marked ready; waiting for required checks: {', '.join(waiting)}{pending}; {NEXT_WAIT}") + return 3 + print("marked ready; " + "; ".join(readiness.reasons)) + if args.wait is not None and ( + waiting or _pending_checks(config, pr, readiness, allow_skipped=not pr.is_draft) + ): + waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=kicked, started=started, + shown=readiness.reasons if kicked else (), args=args, + allow_skipped=True, initial=None if kicked else readiness) if waited is None: return 3 pr, readiness, kicked = waited - assert readiness is not None + assert readiness is not None + _prequeue_size_budget(wt, config, pr, readiness) + if readiness.ready and pr.is_draft and not kicked: + _activate_draft(wt, config, pr, deadline, args) + if args.wait is not None: + waited = _wait_with_deadline(wt, config, pr, args.wait, kicked=True, started=started, + args=args, allow_skipped=True) + if waited is None: + return 3 + pr, readiness, kicked = waited + assert readiness is not None + except github.ReadDeadline: + _print_check_wait_timeout(pr, args) + return 3 + return _report_ready(pr, readiness, config, args.wait) + + +def _report_ready(pr: github.PR, readiness: github.Readiness, config: Config, wait: float | None) -> int: for reason in _readiness_messages(pr, readiness): print(f"not ready: {reason}") if not readiness.ready: - if args.wait is None and _pending_checks(config, pr, readiness): + if wait is None and _pending_checks(config, pr, readiness): print(NEXT_WAIT) return 1 print(f"ready: {pr.url}") @@ -1429,16 +1486,16 @@ def _wait_with_deadline( allow_merged: bool = False, allow_skipped: bool = False, initial: github.Readiness | None = None, ) -> tuple[github.PR, github.Readiness | None, bool] | None: started = time.monotonic() if started is None else started - if timeout == 0: - return _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started, - shown=shown, args=args, allow_merged=allow_merged, - allow_skipped=allow_skipped, initial=initial) deadline = started + timeout - if time.monotonic() >= deadline: + if timeout and time.monotonic() >= deadline: _print_check_wait_timeout(pr, args) return None reported_timeout = False try: + if timeout == 0: + return _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started, + shown=shown, args=args, allow_merged=allow_merged, + allow_skipped=allow_skipped, initial=initial) with github.bounded_reads(deadline, token=None, retry=True): waited = _wait_for_checks(wt, config, pr, timeout, kicked=kicked, started=started, shown=shown, args=args, bounded=True, allow_merged=allow_merged, @@ -1514,7 +1571,7 @@ def _wait_for_checks( return current, None, kicked readiness = _readiness(wt, config, current, pr.head_sha, workflow_wait=True) if not kicked and _draft_checks_waiting(config, current, readiness): - github.mark_ready(config.repo, pr.number) + _activate_draft(wt, config, current, started + timeout, args) print("marked ready; " + "; ".join(readiness.reasons)) return _wait_for_checks(wt, config, pr, timeout, kicked=True, started=started, shown=readiness.reasons, args=args, bounded=bounded, diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 23200686..adfd9554 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1396,8 +1396,8 @@ def readiness( ) -def mark_ready(repo: str, number: int) -> None: - _gh("pr", "ready", str(number), "--repo", repo) +def mark_ready(repo: str, number: int, timeout: float = 120) -> None: + _gh("pr", "ready", str(number), "--repo", repo, timeout=timeout) _QUEUE_QUERY = ( diff --git a/tests/test_cli.py b/tests/test_cli.py index 8c5a895b..c5911615 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2525,32 +2525,32 @@ def test_ready_wait_reports_initial_draft_blocker_once(wt, gh, capsys, monkeypat ] -@pytest.mark.parametrize("settles", [True, False]) -def test_ready_wait_resumes_after_draft_transition(wt, gh, capsys, monkeypatch, head, settles): +@pytest.mark.parametrize("settles,fault,error", [(True, "interrupt", ""), (False, "interrupt", ""), (True, "lost", ""), (False, "lost_zero", ""), (True, "retry", ""), (False, "moved", "head changed"), (False, "throttle", "HTTP 403")]) +def test_ready_wait_resumes_after_draft_transition(wt, gh, capsys, monkeypatch, head, settles, fault, error): arm_approved_pr_with_check_result(gh, head, wt, "skipped", isDraft=True) gh.respond("pr ready", "") - original_mark_ready = github.mark_ready - - def interrupt_after_mark_ready(*args): - original_mark_ready(*args) - arm_pr(gh, head, isDraft=False) - raise KeyboardInterrupt - - monkeypatch.setattr(github, "mark_ready", interrupt_after_mark_ready) - snapshots = ("skipped", "skipped", "skipped", "pending", "success") if settles else ("skipped",) - arm_check_progress(gh, head, *snapshots) + original, attempts, pauses = github.mark_ready, [], [] + def activate(*args): + original(*args) + attempts.append(args) + if fault not in {"retry", "throttle"} or len(attempts) == 2: + arm_pr(gh, "b" * 40 if fault == "moved" else head, isDraft=False) + if len(attempts) == 1: + raise {"interrupt": KeyboardInterrupt(), "throttle": github.GhUnavailable(("gh", "pr", "ready"), "HTTP 403 rate limit")}.get(fault, github.ProcTimeout("lost activation reply")) + monkeypatch.setattr(github, "mark_ready", activate) + monkeypatch.setattr(github, "_retry_sleep", pauses.append) + arm_check_progress(gh, head, *(("skipped", "skipped", "skipped", "pending", "success") if settles else ("skipped",))) monkeypatch.setattr(cli, "WAIT_INTERVAL", 1.0) monkeypatch.setattr(cli, "_sleep", lambda _: None) - wait = "--wait=30" if settles else "--wait=0" - - assert run(capsys, "ready", wait)[0] == 130 + wait = "--wait=30" if settles or fault == "moved" else "--wait=0" + if fault == "interrupt": + assert run(capsys, "ready", wait)[0] == 130 code, out, err = run(capsys, "ready", wait) - - assert err == "" - assert code == (0 if settles else 3) + assert code == (1 if error else (0 if settles else 3)) and error in err assert ("waiting: required check 'checks' is pending" in out) == settles - assert ("timed out waiting for required checks" in out) != settles - assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == 1 + assert ("timed out waiting for required checks" in out) == (not settles and fault in {"interrupt", "lost_zero"}) + assert sum(c["argv"][:2] == ["pr", "ready"] for c in gh.calls) == len(attempts) == (2 if fault == "retry" else 1) + assert pauses == ([5] if fault == "retry" else []) @pytest.mark.parametrize("settled", ["success", "skipped"])