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: 95 additions & 49 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewer location scripts/ai-accounts/ai-accounts:1067 is not in the diff; anchored here.

important: Unrelated revert brings back the ai-accounts stderr hang and deletes its regression test

This delta changes t.join(timeout=1) plus the early return code back to a bare t.join(). It also deletes test_run_returns_after_leader_exits_with_inherited_stderr from tests/test_ai_accounts.py. That brings back the hang the test guarded against. When the wrapped command starts a descendant that inherits the stderr pipe and then exits, proc.stderr.read1 does not return EOF until the descendant exits. The bare join then blocks ai-accounts run for as long as the descendant lives, even though the leader has already returned its exit code. None of this relates to #1155, which covers merge queue polling, and the task text does not mention it. It looks like a bad merge resolution of the main fix. Smallest fix: drop the ai-accounts and test_ai_accounts.py hunks from this branch so main's version stays.

import os
import shlex
import random
Expand Down Expand Up @@ -1372,6 +1373,7 @@ def _wait_with_deadline(
if time.monotonic() >= deadline:
_print_check_wait_timeout(pr, args)
return None
sha = None

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: Unused sha = None in _wait_with_deadline

_wait_with_deadline never reads or assigns sha. It uses waited, and the ReadDeadline handler returns None without looking at sha. The line seems to have been copied from the _queue_wait change. Remove it so readers don't assume this function also keeps an observation across scope exit.

reported_timeout = False
try:
with github.bounded_reads(deadline, token=None, retry=True):
Expand Down Expand Up @@ -1477,15 +1479,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)
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."""
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 @@ -1494,30 +1521,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:

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 persistent closed-unmerged PR is now always exit 3 for positive waits, and the raise branch is effectively unreachable from the CLI

In the bounded path, the _poll_until loop ends only after the deadline, either normally or through a suppressed ReadDeadline. So _report_closed_observation always takes the ReadDeadline branch and prints "last queue observation". It never raises closed[0]. Before this change, a PR that stayed closed-unmerged until the deadline was a hard error; now merge --wait=N reports it as a timeout (exit 3), which can lead automation to retry a PR that is actually closed. The existing _closed_unmerged_wait tests call _wait_for_merge with no read scope, so they only cover the unbounded path and no longer reflect production behavior. If the downgrade is intended, state it in the docstring and make the existing tests cover the scoped path. If it isn't, re-raise closed[0] when the closed observation arrived before the deadline.

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 @@ -1587,32 +1636,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:
if sha := _mergify_departure(config, pr, queue, closed, confirmed):
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)

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 mark_confirmed write inside the bounded Mergify loop can overrun the budget

mergify.mark_confirmed posts a PR comment. Writes are not scoped by bounded_reads, so the default 120s gh timeout applies even when only milliseconds of --wait remain. Reads are capped, but this write can still push a short --wait well past its budget before the loop sees the deadline. Consider checking github.read_timeout(0) before the write and capping its timeout to the remaining budget, or accept and document the overrun.

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 Down Expand Up @@ -1653,7 +1698,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 @@ -1712,12 +1760,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
51 changes: 39 additions & 12 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,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
Expand Down Expand Up @@ -139,12 +139,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
Expand Down Expand Up @@ -294,7 +295,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_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 @@ -328,7 +329,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
Expand Down Expand Up @@ -373,12 +374,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))
timeout=read_timeout(timeout, scoped=read_only))
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),
Expand Down Expand Up @@ -468,7 +469,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 @@ -1449,14 +1450,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 @@ -1473,9 +1478,30 @@ 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
sha = merged_sha(repo, number, expected_head=head_sha)
if sha:
return sha
if strategy != "queue":
# A synchronous merge already in flight still needs verification and cleanup.
if sha := merged_sha(repo, number, expected_head=head_sha):

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: Direct-merge fallback is still budget-bound when the first unbounded read misses the landing

For non-queue strategies, the first merged_sha now runs outside the budget. If it returns None, for example because GitHub has not yet shown the synchronous merge or because protection turned the request into auto-merge, _verify_merge_request then runs merge_pending inside bounded_reads. If gh pr merge used up the wait (as in the new test, where 2s pass against --wait=1), that read raises ReadDeadline straight away. _merge_and_follow then returns None and the command exits 3, even though the direct merge may have succeeded. The new test only covers the case where the first read already shows MERGED. Consider a test for a first read that returns OPEN, and decide whether direct merges should get one more unbounded check before timing out.

return sha
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.

important: A completed direct merge is reported as a merge-queue timeout when its verification runs past the deadline

merge() now runs _verify_merge_request inside bounded_reads(admit_by, retry=True). The pr merge write itself is unbounded (timeout=300), and cmd_merge admits it while now <= admit_by. This breaks in two cases. First, the merge is admitted with little budget left. Second, the write itself runs past admit_by, which is likely when source-check waiting used most of --wait. In either case the first merged_sha read raises ReadDeadline, or bounded_reads.__exit__'s read_timeout(0) raises after a SHA was already verified. _merge_and_follow (cli.py:1554) turns that into None, and cmd_merge prints "timed out waiting for the merge queue to land PR #N" and exits 3. That happens even for a squash/merge/rebase strategy with no queue, where GitHub merged the PR synchronously. Cleanup is skipped and the message is wrong. A rerun recovers, but the merge is misreported.

_queue_wait has the same flaw (cli.py:1489-1501): if the poll returns a SHA that _landed has already checked against the deadline, the exit check in bounded_reads can still throw it away in the window between the return and the scope exit. That contradicts "a landing verified before the deadline proceeds to cleanup".

Smallest fix: keep the first post-write merged_sha unbounded, or apply observation_deadline only after it returns None (to merge_pending and the follow-up read). In _merge_and_follow and _queue_wait, never discard a SHA that is already in hand: return it before the scope's exit check, or catch ReadDeadline only around the poll call.

if observation_deadline is not None else nullcontext())
sha = None
try:
with budget:
sha = _verify_merge_request(repo, number, head_sha, argv, 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, ...], *, 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):
Expand All @@ -1484,6 +1510,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:
Expand Down
8 changes: 5 additions & 3 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def redirect_request(self, *_args, **_kwargs):

def _open(request: urllib.request.Request):
try:
return urllib.request.build_opener(_NoRedirect).open(request, timeout=30)
return urllib.request.build_opener(_NoRedirect).open(request, timeout=github.read_timeout(30))
except ValueError:
# The HTTP client can include the Authorization value in a header error.
raise MergifyError("Mergify API request has an invalid URL or header") from None
Expand All @@ -95,7 +95,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 @@ -108,7 +110,7 @@ def api_get(repo: str, suffix: str) -> object | None:
except (json.JSONDecodeError, UnicodeDecodeError) 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