From e4eb71bede3db393ae00603fc0ade05d3eabf1f5 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:49:49 +0100 Subject: [PATCH 1/4] Merge origin/main and preserve queue-departure reporting under the worktree lock Architecture-Review: unchanged; admission still uses the existing marker and lock and queue waiting starts after the lock is released. Co-Authored-By: Codex --- src/loopzero/cli.py | 46 +++++++++++++++++----------------- src/loopzero/mergify.py | 6 ++++- tests/test_cli.py | 55 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 82 insertions(+), 25 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index df90da9c..69b3b62b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1526,7 +1526,7 @@ class _AdmissionDeadline(Exception): def _merge_with_mergify( - config: Config, pr: github.PR, + wt: Path, config: Config, pr: github.PR, readiness: github.Readiness, deadline: float | None, admit_by: float | None = None, ) -> str | None: """Request Mergify after readiness verifies the source gates and queue configuration.""" @@ -1535,28 +1535,28 @@ def _merge_with_mergify( raise CliError("not ready to request Mergify: " + "; ".join(readiness.reasons) + hint) queue = config.mergify_queue assert queue is not None - requested, confirmed_marker = mergify.markers( - config.repo, pr.number, pr.head_sha, queue - ) - state = mergify.membership(config.repo, pr.number, queue) - 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: - mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) - confirmed_marker = True - if not confirmed and confirmed_marker: - closed: list[github.GhError] = [] - if sha := _mergify_departure(config, pr, queue, closed, confirmed=True): + with _lock_task_state(wt): + requested, confirmed_marker = mergify.markers( + config.repo, pr.number, pr.head_sha, queue + ) + state = mergify.membership(config.repo, pr.number, queue) + 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: - if admit_by is not None and time.monotonic() > admit_by: - raise _AdmissionDeadline - mergify.request(config.repo, pr.number, pr.head_sha, queue) - requested = True + confirmed = state is not None + if confirmed and not confirmed_marker: + mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) + confirmed_marker = True + 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: + if admit_by is not None and time.monotonic() > admit_by: + raise _AdmissionDeadline + 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" @@ -1604,7 +1604,7 @@ def cmd_merge(args: argparse.Namespace) -> int: print(f"PR #{pr.number} was already merged as {sha[:12]}; cleaning up") elif config.merge_strategy == "mergify": try: - sha = _merge_with_mergify(config, pr, readiness, deadline, admit_by) + sha = _merge_with_mergify(wt, config, pr, readiness, deadline, admit_by) except _AdmissionDeadline: print(f"timed out before requesting Mergify for PR #{pr.number}") return 3 diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index eb21eef7..a2554a85 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -327,7 +327,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): + if not markers(repo, number, head, queue)[0]: + raise def mark_confirmed(repo: str, number: int, head: str, queue: str) -> None: diff --git a/tests/test_cli.py b/tests/test_cli.py index 9d44b146..7b80bb8c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -11,10 +11,12 @@ import signal import subprocess import sys +from concurrent.futures import ThreadPoolExecutor from contextlib import suppress from dataclasses import replace from pathlib import Path from select import select +from threading import Event from types import SimpleNamespace from unittest.mock import Mock from urllib.parse import quote @@ -22,7 +24,7 @@ import pytest from loopzero import cli, config, github, mergify -from loopzero._proc import Completed, build_env +from loopzero._proc import Completed, ProcTimeout, build_env from loopzero.types import CheckReport, CheckResult, Finding, ReviewResult from tests.conftest import git, init_git_repo from tests.fake_gh import replay @@ -3925,6 +3927,57 @@ def test_mergify_merge_requests_once_for_behind_head( assert code == 1 and "queue configuration is unverified" in err and not requested +@pytest.mark.parametrize("accepted", [True, False]) +def test_overlapping_mergify_command_after_lost_reply(wt, gh, monkeypatch, accepted): + commit_mergify_configuration(wt) + head = head_of(wt) + 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, original_markers, flock = github._api, mergify.markers, cli.fcntl.flock + + def lock(fd, operation): + if writing.is_set(): + overlap.set() + return flock(fd, operation) + + def markers(*args): + result = original_markers(*args) + if writing.is_set(): + overlap.set() + return result + + 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"]}]) + raise ProcTimeout("lost Mergify command reply") + return original_api(path, payload, **kwargs) + + monkeypatch.setattr(cli.fcntl, "flock", lock) + monkeypatch.setattr(mergify, "markers", markers) + 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("wait", [False, True]) def test_mergify_merge_waits_for_pending_checks_only_with_wait( wt: Path, gh: FakeGh, capsys, monkeypatch, wait From 98cf014b38ed88cb6f4045229b7c65b088ccc544 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:56:01 +0100 Subject: [PATCH 2/4] =?UTF-8?q?Reuse=20GitHub=E2=80=99s=20timeout=20type?= =?UTF-8?q?=20in=20the=20merge=20regression?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Codex --- tests/test_cli.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_cli.py b/tests/test_cli.py index 7b80bb8c..f3e5fe1f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -24,7 +24,7 @@ import pytest from loopzero import cli, config, github, mergify -from loopzero._proc import Completed, ProcTimeout, build_env +from loopzero._proc import Completed, build_env from loopzero.types import CheckReport, CheckResult, Finding, ReviewResult from tests.conftest import git, init_git_repo from tests.fake_gh import replay @@ -3963,7 +3963,7 @@ def transport(path, payload, **kwargs): if accepted: original_api(path, payload, **kwargs) gh.respond(f"api {path}", [{"user": {"login": LOGIN}, "body": payload["body"]}]) - raise ProcTimeout("lost Mergify command reply") + raise github.ProcTimeout("lost Mergify command reply") return original_api(path, payload, **kwargs) monkeypatch.setattr(cli.fcntl, "flock", lock) From a6be1673b4723978157be07e80f2fc7bcc40b6ee Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:31:37 +0100 Subject: [PATCH 3/4] Preserve explicit rate-limit guidance for Mergify requests Architecture-Review: unchanged; only ambiguous request failures read the existing queue markers. Co-Authored-By: Codex --- src/loopzero/mergify.py | 2 ++ tests/test_mergify.py | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 77e6d086..deffe55b 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -377,6 +377,8 @@ 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 try: github._api(f"repos/{repo}/issues/{number}/comments", {"body": body}) + except github.GhUnavailable: + raise except (github.GhError, github.ProcTimeout, OSError): if not markers(repo, number, head, queue)[0]: raise diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 7666e7a9..97976011 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -13,7 +13,7 @@ import pytest -from loopzero import mergify +from loopzero import github, mergify def response(payload: object) -> io.BytesIO: @@ -250,3 +250,16 @@ def fail(_request): with pytest.raises(mergify.MergifyError, match="transport failed") as info: mergify.api_get("acme/widgets", "/merge-queue/status") assert str(reason) in str(info.value) and sleeps == expected_sleeps + + +def test_rate_limited_queue_post_does_not_reconcile(monkeypatch): + rejected = github.GhUnavailable(("GitHub API request",), "HTTP 429") + + def submit(*args): + raise rejected + + monkeypatch.setattr(github, "_api", submit) + 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 is rejected From b85fd33c7d08bbca4f109fa05fc995706757e561 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 14:45:53 +0100 Subject: [PATCH 4/4] Reconcile transient Mergify POST failures Architecture-Review: unchanged; the GitHub transport distinguishes confirmed rate limits before the existing queue reconciliation. Co-Authored-By: Codex --- src/loopzero/github.py | 6 ++++-- src/loopzero/mergify.py | 6 ++---- tests/test_cli.py | 6 ++++-- tests/test_mergify.py | 18 ++++++++++-------- 4 files changed, 20 insertions(+), 16 deletions(-) diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 482764b6..aba983c0 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -67,9 +67,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:]}") @@ -426,7 +427,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: diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index aa0a7433..29b40a87 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -408,10 +408,8 @@ 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 try: github._api(f"repos/{repo}/issues/{number}/comments", {"body": body}) - except github.GhUnavailable: - raise - except (github.GhError, github.ProcTimeout, OSError): - if not markers(repo, number, head, queue)[0]: + except (github.GhError, github.ProcTimeout, OSError) as exc: + if getattr(exc, "confirmed_rate_limit", False) or not markers(repo, number, head, queue)[0]: raise diff --git a/tests/test_cli.py b/tests/test_cli.py index dfa658c5..2d9d8381 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3879,8 +3879,8 @@ def test_mergify_merge_requests_once_for_behind_head( else: assert "queue configuration is unverified" in err -@pytest.mark.parametrize("accepted", [True, False]) -def test_overlapping_mergify_command_after_lost_reply(wt, gh, monkeypatch, accepted): +@pytest.mark.parametrize(("accepted", "transient"), [(True, False), (False, False), (True, True)]) +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) @@ -3908,6 +3908,8 @@ def transport(path, payload, **kwargs): 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) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 06d4a2d9..38c2d18d 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -283,14 +283,16 @@ def arm(timer, seconds): assert signal.getitimer(signal.ITIMER_REAL) == (0, 0) -def test_rate_limited_queue_post_does_not_reconcile(monkeypatch): - rejected = github.GhUnavailable(("GitHub API request",), "HTTP 429") - - def submit(*args): - raise rejected - - monkeypatch.setattr(github, "_api", submit) +@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 is rejected + assert exc.value.confirmed_rate_limit