Skip to content
Merged
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
45 changes: 23 additions & 22 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1723,29 +1723,30 @@ def _merge_with_mergify(
assert queue is not None
if not readiness.ready:
return _follow_blocked_mergify(config, pr, readiness, queue, deadline)
requested, confirmed_marker = mergify.markers(
config.repo, pr.number, pr.head_sha, queue
)
state = mergify.membership(config.repo, pr.number, queue, deadline)
if sha := github.merged_sha(
config.repo, pr.number, expected_head=pr.head_sha, check_hold=not requested and state is None,
):
return sha
confirmed = state is not None
if confirmed and not confirmed_marker:
_require_receipt(wt, config, pr.head_sha)
mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue)
if not confirmed and confirmed_marker:
closed: list[github.GhError] = []
if sha := _mergify_departure(config, pr, queue, closed, confirmed=True):
with worktree.lock_local_state(wt):

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 admission lock covers slow work, waits a fixed 60s and ignores admit_by

lock_local_state waits a fixed 60 seconds and then raises TimeoutError('task state is busy'). Merge now holds this lock for the whole admission phase: GitHub reads, _mergify_departure, and _prequeue_size_budget. The size budget clones, fetches and runs up to two scripts, each with GIT_TIMEOUT=60s. cmd_check also holds the same lock for an entire check run. As a result, a second merge --wait can fail with 'busy' instead of following the queue the first invocation already joined. A merge started during a check also fails after 60s, where it previously went ahead. The 60s wait also ignores admit_by, so a positive --wait can run past its admission budget. This stays safe (no duplicate POST), but users have to retry. Consider one of these: run _prequeue_size_budget before taking the lock, then recheck markers under the lock; or make the lock wait respect admit_by/deadline when one is set.

requested, confirmed_marker = mergify.markers(
config.repo, pr.number, pr.head_sha, queue
)
state = mergify.membership(config.repo, pr.number, queue, deadline)
if sha := github.merged_sha(
config.repo, pr.number, expected_head=pr.head_sha, check_hold=not requested and state is None,
):
return sha
raise closed[0]
if not confirmed and not requested:
_prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None)
if admit_by is not None and time.monotonic() > admit_by:
raise _AdmissionDeadline
_require_receipt(wt, config, pr.head_sha)
mergify.request(config.repo, pr.number, pr.head_sha, queue)
confirmed = state is not None
if confirmed and not confirmed_marker:
_require_receipt(wt, config, pr.head_sha)
mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue)
if not confirmed and confirmed_marker:
closed: list[github.GhError] = []
if sha := _mergify_departure(config, pr, queue, closed, confirmed=True):
return sha
raise closed[0]
if not confirmed and not requested:
_prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None)
if admit_by is not None and time.monotonic() > admit_by:
raise _AdmissionDeadline
_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)
state_name = "confirmed in" if confirmed else "requested from"
Expand Down
6 changes: 4 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,10 @@

class GhError(Exception):
def __init__(self, command: tuple[str, ...], tail: str, *,
token: str = "", guidance: str = "") -> None:
token: str = "", guidance: str = "", confirmed_rate_limit: bool = False) -> None:
self.command = tuple(_redact_tokens(arg, token) for arg in command)
self.tail = _redact_tokens(tail, token) + guidance
self.confirmed_rate_limit = confirmed_rate_limit
command_text = _redact_tokens(" ".join(command), token)
super().__init__(f"{command_text} failed: {self.tail.strip()[-600:]}")

Expand Down Expand Up @@ -411,7 +412,8 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120,
raise GhAuth(error_command, detail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}")
guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None))
error = GhUnavailable if transient else GhError
raise error(error_command, detail, token=selected, guidance=guidance)
raise error(error_command, detail, token=selected, guidance=guidance,
confirmed_rate_limit=rate_limited and status in {"403", "429"})


def _rest_rate_limit(headers: dict[str, str]) -> str:
Expand Down
6 changes: 5 additions & 1 deletion src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,11 @@ def markers(repo: str, number: int, head: str, queue: str) -> tuple[bool, bool]:

def request(repo: str, number: int, head: str, queue: str) -> None:
body = f"@mergifyio queue\n\n{_marker(REQUEST, head, queue)}" # Mergify deprecates naming the queue
github._api(f"repos/{repo}/issues/{number}/comments", {"body": body})
try:
github._api(f"repos/{repo}/issues/{number}/comments", {"body": body})
except (github.GhError, github.ProcTimeout, OSError) as exc:
if getattr(exc, "confirmed_rate_limit", False) or not markers(repo, number, head, queue)[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: A failed reconciliation read hides the original POST error

If the POST fails without a confirmed rate limit (a 5xx, ProcTimeout or OSError) and the follow-up markers() read also fails (for example, it is rate-limited or times out), the read's exception replaces the POST's. The POST error only survives as __context__, and the CLI prints str(exc), so the user sees a GET comments failure instead of the failed queue command. Smallest fix: wrap the reconciliation read in try/except (github.GhError, github.ProcTimeout, OSError): raise exc from None. That way an unverifiable reconciliation re-raises the original POST diagnostic.

raise


def mark_confirmed(repo: str, number: int, head: str, queue: str) -> None:
Expand Down
45 changes: 45 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3919,6 +3919,51 @@ def test_mergify_merge_requests_once_for_behind_head(
else:
assert "queue configuration is unverified" in err

@pytest.mark.parametrize(("accepted", "transient"), [(True, False), (False, False), (True, 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: No test covers releasing the lock before queue polling

The new concurrency test only runs merge without --wait, so _wait_for_mergify is never reached. The acceptance item 'Release the existing worktree lock before queue polling' has no test: a later change that moves the with block around the wait would still pass. Add a --wait case that checks the local-state lock can be acquired (for example, with a non-blocking flock) while _wait_for_mergify runs.

def test_overlapping_mergify_command_after_lost_reply(wt, gh, monkeypatch, accepted, transient):
head = arm_mergify_pr(wt, gh)
pr = github.PR(7, URL, head, "main", False, "OPEN", "MERGEABLE")
settings = config.load_trusted(wt)
monkeypatch.setattr(cli, "_context", lambda *_args, **_kwargs: (wt, settings))
monkeypatch.setattr(cli, "_pr_readiness", lambda *_args, **_kwargs: (pr, github.Readiness(True, ())))
monkeypatch.setattr(mergify, "membership", lambda *_: None)
monkeypatch.setattr(github, "merged_sha", lambda *_args, **_kwargs: None)
endpoint = f"repos/{REPO}/issues/7/comments"
gh.respond(f"api {endpoint}", [])
gh.respond(f"api {endpoint} --method POST", {})
writing, overlap = Event(), Event()
original_api, flock = github._api, cli.fcntl.flock

def lock(fd, operation):
if writing.is_set():
overlap.set()
return flock(fd, operation)

def transport(path, payload, **kwargs):
if path != endpoint:
return original_api(path, payload, **kwargs)
if not writing.is_set():
writing.set()
assert overlap.wait(10), "second merge did not reach admission"
if accepted:
original_api(path, payload, **kwargs)
gh.respond(f"api {path}", [{"user": {"login": LOGIN}, "body": payload["body"]}])
if transient:
raise github.GhUnavailable(("GitHub API request",), "HTTP 502")
raise github.ProcTimeout("lost Mergify command reply")
return original_api(path, payload, **kwargs)

monkeypatch.setattr(cli.fcntl, "flock", lock)
monkeypatch.setattr(github, "_api", transport)
with ThreadPoolExecutor(max_workers=2) as pool:
first = pool.submit(cli.main, ["merge"])
assert writing.wait(10), "first merge did not reach the command POST"
second = pool.submit(cli.main, ["merge"])
assert first.result(timeout=15) == (0 if accepted else 1)
assert second.result(timeout=15) == 0
assert len([c for c in gh.calls if "--input" in c and c["argv"][1] == endpoint]) == 1



@pytest.mark.parametrize("command", ["ready", "status"])
@pytest.mark.parametrize("merge_state", ["CLEAN", "BEHIND"])
Expand Down
17 changes: 16 additions & 1 deletion tests/test_mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import pytest

from loopzero import mergify
from loopzero import github, mergify


def response(payload: object) -> io.BytesIO:
Expand Down Expand Up @@ -273,3 +273,18 @@ def arm(timer, seconds):
signal.raise_signal(signal.SIGALRM)
assert signal.getsignal(signal.SIGALRM) is handler
assert signal.getitimer(signal.ITIMER_REAL) == (0, 0)


@pytest.mark.parametrize("response", [
'HTTP/2 429 Too Many Requests\n\n{}',
'HTTP/2 403 Forbidden\nX-RateLimit-Remaining: 0\n\n{}',
'HTTP/2 403 Forbidden\n\n{"message":"API rate limit exceeded"}',
])
def test_rate_limited_queue_post_does_not_reconcile(monkeypatch, response):
monkeypatch.setattr(github, "run", lambda *_a, **_k: SimpleNamespace(
exit_code=1, stdout=response, stderr="",
))
monkeypatch.setattr(mergify, "markers", lambda *_: pytest.fail("read markers after rate-limited POST"))
with pytest.raises(github.GhUnavailable) as exc:
mergify.request("acme/widgets", 7, "a" * 40, "main")
assert exc.value.confirmed_rate_limit
Loading