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
144 changes: 94 additions & 50 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import tempfile
import time
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from contextlib import contextmanager, suppress
Comment thread
eowca marked this conversation as resolved.
Resolved
from datetime import UTC, datetime
from functools import partial, wraps
from pathlib import Path
Expand Down Expand Up @@ -1367,15 +1367,40 @@ 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)
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:

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 Mergify timeout hit during a read loses the queue detail already observed

If a read crosses the deadline, _queue_wait prints only the timeout_notice. The "still queued in {queue}. <candidate/dashboard URL>. Unmet candidate conditions: …" detail is dropped, even when state came back from an earlier membership read. That detail needs no further network call.

This is likely in the final bounded tick: it runs _landed, configured (which makes several Mergify and GitHub reads) and membership within remaining/2. It is also likely for short waits; the new test hits exactly this path. The task asks to keep diagnostics that can be built from observations already received.

Fix: have _wait_for_mergify record the last state somewhere _queue_wait's handler can reach (a holder object or a callback). On ReadDeadline, render _mergify_timeout_detail(..., query_report=False) from that state instead of the bare notice.

if timeout_notice and not reported_timeout:
print(timeout_notice)
return None
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."""
github.read_timeout(0)
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


Expand All @@ -1384,30 +1409,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):
sha = _landed(config, pr, closed)
if sha:
return sha
if not github.merge_pending(config.repo, pr.number):
with suppress(github.ReadDeadline):
for _ in _poll_until(started, timeout, bounded=bool(timeout)):
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]
if not github.merge_pending(config.repo, pr.number):
sha = _landed(config, pr, closed)
if sha:
return sha
if closed:
continue
raise CliError(f"PR #{pr.number} left the merge queue unmerged")
_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:
try:
_, _, report = mergify.request_status(config.repo, pr.number, pr.head_sha, queue)
except github.GhError:
report = None
report = None
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 @@ -1448,32 +1495,28 @@ 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")
for _ in _poll_until(started, timeout):
sha = _landed(config, pr, closed)
if sha:
return sha
if not mergify.configured(config.repo, config.base_branch, queue):
raise CliError("Mergify queue configuration became unsafe or unavailable while waiting")
state = mergify.membership(config.repo, pr.number, queue)
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 and confirmed:
if sha := _mergify_departure(config, pr, queue, closed):
with suppress(github.ReadDeadline):
for _ in _poll_until(started, timeout, bounded=bool(timeout)):
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):
raise CliError("Mergify queue configuration became unsafe or unavailable while waiting")
state = mergify.membership(config.repo, pr.number, queue)
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 and confirmed:
if sha := _mergify_departure(config, pr, queue, closed):
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 Down Expand Up @@ -1516,7 +1559,10 @@ def _merge_with_mergify(
mergify.request(config.repo, pr.number, pr.head_sha, queue)
requested = True
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}; "
Expand Down Expand Up @@ -1575,12 +1621,10 @@ def cmd_merge(args: argparse.Namespace) -> int:
if admit_by is not None and time.monotonic() > admit_by:
print(f"timed out before merging PR #{pr.number}")
return 3
sha = github.merge(config.repo, pr.number, config.merge_strategy, pr.head_sha)
if sha is None and args.wait is not None:
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
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:
print(
f"PR #{pr.number} is queued for merge into {config.base_branch}; "
Expand Down
32 changes: 22 additions & 10 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import shlex
import tempfile
import time
from contextlib import contextmanager, suppress
from contextlib import contextmanager, nullcontext, suppress
from contextvars import ContextVar
from dataclasses import dataclass
from datetime import UTC, datetime
Expand Down Expand Up @@ -131,12 +131,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) -> float:
def read_timeout(limit: float) -> float:
"""Cap an I/O timeout or retry delay to the active read budget."""
scope = _read_scope.get()
if scope is None:
return limit
Expand Down Expand Up @@ -269,7 +270,7 @@ def app_token() -> str:
return ""
minted = time.time() # before the helper runs: a suspend mid-call still ages the token
try:
result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_ENV, timeout=_read_timeout(10))
result = run([str(APP_TOKEN_HELPER)], cwd=Path("/"), env_allowlist=GH_ENV, timeout=read_timeout(10))
except (ToolMissing, ProcTimeout, ReadDeadline, OSError):
return ""
if result.exit_code or not result.stdout.strip():
Expand Down Expand Up @@ -316,19 +317,19 @@ 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) if scope else timeout)
timeout=read_timeout(timeout) if scope else timeout)
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:
if scope and scope[2]:
_read_timeout(timeout)
read_timeout(timeout)
if delay is None or not retryable:
raise ProcTimeout(
_redact_tokens(str(exc), selected), _redact_tokens(exc.stdout, selected),
stderr=_redact_tokens(exc.stderr, selected), duration_s=exc.duration_s,
) from None
_retry_sleep(_read_timeout(delay) if scope else delay)
_retry_sleep(read_timeout(delay) if scope else delay)
continue
status, headers, body = (_included_response(done.stdout) if rest_api or diagnostic_api
else (None, {}, done.stdout))
Expand All @@ -344,7 +345,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120,
raise GhError(argv, tail, token=selected, guidance=guidance)
if done.exit_code == 0 or delay is None or not retryable or not _transient_error(tail, retry_idempotent):
break
_retry_sleep(_read_timeout(delay) if scope else delay)
_retry_sleep(read_timeout(delay) if scope else delay)
if done.exit_code != 0:
error_command = ("GitHub API request",) if diagnostic_api or patch_error else argv
error_tail = (_api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected,
Expand Down Expand Up @@ -412,7 +413,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)
Expand Down Expand Up @@ -1328,14 +1329,18 @@ def merge_pending(repo: str, number: int) -> 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. "
f"Check the PR's queue or merge state before retrying.\n{str(exc)[-300:]}") from exc
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
Expand All @@ -1352,6 +1357,13 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None:
_gh(*argv, timeout=300)
except GhError as exc:
raise MergeFailed(exc.command, exc.tail) from exc
budget = (bounded_reads(observation_deadline, token=None, retry=True)

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: observation_deadline adds a parameter and a helper that the caller could replace with one with block

_gh reads _read_scope only for read-only argv (scope = _read_scope.get() if read_only else None, github.py:313). Now that the write uses a fixed timeout=300, wrapping the whole github.merge(...) call in github.bounded_reads(admit_by, token=None, retry=True) inside _merge_and_follow behaves the same way. The write stays uncapped, the verification reads are capped, and a late verification still raises ReadDeadline when the scope exits. So the keyword-only observation_deadline parameter, the nullcontext branch and the _verify_merge_request split are not needed. They also put cli deadline policy inside github.merge. Smallest fix: drop the parameter and the split, and scope the call in _merge_and_follow when admit_by is not None.

if observation_deadline is not None else nullcontext())
with budget:
return _verify_merge_request(repo, number, head_sha, argv)


def _verify_merge_request(repo: str, number: int, head_sha: str, argv: tuple[str, ...]) -> str | None:
sha = merged_sha(repo, number, expected_head=head_sha)
if sha:
return sha
Expand Down
8 changes: 5 additions & 3 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def redirect_request(self, *_args, **_kwargs):


def _open(request: urllib.request.Request):
return urllib.request.build_opener(_NoRedirect).open(request, timeout=30)
return urllib.request.build_opener(_NoRedirect).open(request, timeout=github.read_timeout(30))


def api_get(repo: str, suffix: str) -> object | None:
Expand All @@ -89,7 +89,9 @@ def api_get(repo: str, suffix: str) -> object | None:
for delay in (2.0, 5.0, None): # reads retry server errors, throttling and dropped reads
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
Expand All @@ -98,7 +100,7 @@ def api_get(repo: str, suffix: str) -> object | None:
except (OSError, ValueError, http.client.IncompleteRead) as exc:
if delay is None:
raise MergifyError("Mergify queue lookup returned no valid JSON") from exc
_retry_sleep(delay)
_retry_sleep(github.read_timeout(delay))
return None


Expand Down
Loading
Loading