Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 88 additions & 31 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1309,44 +1309,101 @@ 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: CLI now depends on three private github helpers for retry policy

_activate_draft/_recover_draft_activation call github._transient_error, github._retry_pause and github._read_timeout. No other code in cli.py touches github's private helpers. This rebuilds part of _gh's retry policy (transient classification, scoped back-off, budget clamp) in the CLI, so the two copies can drift if one changes. Smallest fix: add one public helper in github.py, for example mark_ready(..., deadline=...) that returns whether a single retry is allowed, or retry_pause_within_scope(), and call that from cli.py.

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)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Mergeability briefly showing UNKNOWN blocks the single retry and exits 1

Before the second write, recovery requires readiness.ready or _draft_checks_waiting(...). _draft_checks_waiting drops MERGEABILITY_PENDING and then returns (). So if GitHub is still recomputing mergeability 5 s after the failed write, recovery raises a hard CliError (exit 1), when this is really a pending state that the wait loop already treats as waitable. If this case should be retried, also accept MERGEABILITY_PENDING as a non-blocker here. Otherwise, document that it counts as a 'new blocker'.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important: Require known mergeability before retrying activation

When mergeability is UNKNOWN and a required check is missing or skipped, _draft_checks_waiting removes MERGEABILITY_PENDING and returns the check name. Recovery therefore issues a second write while mergeability is still unknown. Add a retry-specific mergeability guard and cover this combination in the existing replay.

raise CliError("; ".join(readiness.reasons))
_prequeue_size_budget(wt, config, current, readiness)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important: Recheck retry eligibility after the size-budget check

The last PR observation precedes the clone, remote fetch and budget script. If the head moves, a hold is added, or activation takes effect during that work, mark_ready still writes by PR number using the earlier snapshot. After a budget check actually runs, observe the PR again and confirm the same head, draft status and retry eligibility immediately before writing.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

important: Bound recovery subprocesses by the remaining wait

Each Git command and the budget script gets its own 60-second timeout. With one second left in the wait, a slow fetch can keep recovery running for a minute before _read_timeout checks the deadline at the write. Pass the recovery deadline into the budget helper, cap each subprocess timeout by the remaining time, and use the existing wait-timeout path when it expires.

github.mark_ready(config.repo, pr.number, github._read_timeout(120))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: The retry write can get a very short timeout and then reports an unconfirmed write

github._read_timeout(120) clamps the second gh pr ready to whatever budget is left after the pause, two reads and a readiness evaluation. That can be under a second. The write may then still land on GitHub after ProcTimeout, and the command exits 1 with 'Draft activation unconfirmed' and no reconciliation. Consider requiring a minimum remaining budget, such as RETRY_DELAY, before sending the second write, and otherwise treating the case as a timeout (exit 3).



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)
assert readiness is not None
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Timeout message hides that draft activation is unconfirmed

With --wait=0, or when the deadline passes during recovery, _recover_draft_activation raises ReadDeadline. cmd_ready, or _wait_with_deadline on the wait/merge path, then prints only 'timed out waiting for required checks … resume'. The user is never told that gh pr ready failed and that the PR may still be a draft. Smallest fix: put the activation failure into the ReadDeadline tail and print it next to the timeout hint.

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}")
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down
40 changes: 20 additions & 20 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Replay test packs seven scenarios into hard-to-read one-liners

Keeping the line count the same was done by putting the parametrize, the exception-selection dict .get and the combined assertions on single long lines. When one case fails, it is hard to tell which expectation broke. Consider pytest.param(..., id=...) and splitting the compound assert ... and ... so failures point to the exact condition. Ruff's E501 is not enabled, so this is about readability only.

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"])
Expand Down
Loading