Skip to content
Draft
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
179 changes: 119 additions & 60 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import fcntl
import hashlib
import json
import math
import os
import random
import re
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -1563,15 +1564,39 @@ def _wait_for_checks(
return None


def _queue_wait(

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: _queue_wait duplicates the bounded-scope and timeout-notice logic of _wait_with_deadline

_queue_wait repeats the pattern from _wait_with_deadline (cli.py:1411-1426) almost line for line. Both open bounded_reads(deadline, token=None, retry=True), track reported_timeout, catch ReadDeadline and print a timeout notice only when the inner wait hasn't already reported one. _queue_wait adds two things: it re-checks the deadline when the poll raises an error, and it keeps a SHA that was verified before the scope check on exit. Because the two copies now differ, they can drift apart. For example, the source-check wait does not convert errors that arrive after the deadline into a timeout, but the queue wait does. Consider having _wait_with_deadline call _queue_wait (or one shared helper), so that both waits get the same rules for late responses.

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)

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: _landed can discard a verified landing SHA when the read finishes at the deadline

This delta removes the read-budget check before the read in _landed, leaving only github.read_timeout(0) after merged_sha. That check raises ReadDeadline even when merged_sha has just returned a verified SHA. If the landing read finishes as the budget expires, _wait_for_merge and _wait_for_mergify suppress the ReadDeadline. The command then reports a timeout and exits 3 without cleanup, even though the PR landed. This conflicts with the acceptance criterion 'preserve verified landings'. The behaviour predates this delta, but the function was edited here. Smallest fix: return early when a SHA is found (if sha: return sha) before calling github.read_timeout(0), so the post-read check only applies to non-landed observations.

return sha


Expand All @@ -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."
)
Expand Down Expand Up @@ -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


Expand All @@ -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:

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: Redundant ReadDeadline handler duplicates the one now in cmd_merge

This delta adds except (_AdmissionDeadline, github.ReadDeadline) to cmd_merge (line 1851). That handler prints the same timed out waiting for Mergify to land PR #N and returns 3. _follow_blocked_mergify also catches github.ReadDeadline, prints the same text and returns None, and cmd_merge then turns that None into exit 3 when --wait is set. The two handlers give the same result, so the message and exit path now live in two places that can drift apart. Smallest fix: delete the except github.ReadDeadline branch in _follow_blocked_mergify and let the exception reach cmd_merge. The new regression test would then call through cmd_merge, or assert with pytest.raises(github.ReadDeadline) that no poll follows.

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)


Expand All @@ -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,
):
Expand All @@ -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
Expand All @@ -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.
Expand All @@ -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"

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: A ReadDeadline before any Mergify request is reported as 'waiting for Mergify to land'

In _merge_with_mergify, mergify.membership(..., admit_by) at line 1781 runs before mergify.request. If the budget expires during that lookup, the new cmd_merge handler prints timed out waiting for Mergify to land PR #N, even though nothing was requested and the PR may not be in the queue. The admission-path timeout should say timed out before requesting Mergify for PR #N, as _AdmissionDeadline does. Smallest fix: in _merge_with_mergify, convert a ReadDeadline raised inside the pre-request block into _AdmissionDeadline when requested and confirmed are both false, or pick the message from whether a request or confirmation marker exists.

print(f"timed out {action} PR #{pr.number}")
return 3
if sha is None:
return 3 if args.wait is not None else 0
Expand All @@ -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)
Expand Down
Loading
Loading