From 3aef68208cd733ca7be5c7a4eaf2a3ae43f8a131 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:50:22 +0100 Subject: [PATCH] Serialize Mergify request admission within a worktree Architecture-Review: unchanged; Mergify still uses head-and-queue markers and the existing worktree lock is released before queue polling. 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 a18c4994..5831005c 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1479,7 +1479,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.""" @@ -1488,28 +1488,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: - sha = github.merged_sha(config.repo, pr.number, expected_head=pr.head_sha) - if sha: + 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 CliError(f"PR #{pr.number} left Mergify queue {queue} unmerged. {MERGIFY_DEQUEUE_HINT}") - 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: + sha = github.merged_sha(config.repo, pr.number, expected_head=pr.head_sha) + if sha: + return sha + raise CliError(f"PR #{pr.number} left Mergify queue {queue} unmerged. {MERGIFY_DEQUEUE_HINT}") + 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" @@ -1557,7 +1557,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 2bcc90f1..5179f4a8 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -262,7 +262,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 5e14f8c1..82cfab6e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -10,7 +10,9 @@ import subprocess import sys from dataclasses import replace +from concurrent.futures import ThreadPoolExecutor from pathlib import Path +from threading import Event from types import SimpleNamespace from unittest.mock import Mock from urllib.parse import quote @@ -18,7 +20,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 @@ -3785,6 +3787,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