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
46 changes: 23 additions & 23 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand All @@ -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):

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: Admission lock waits with no bound and ignores the --wait budget

_lock_task_state calls a blocking flock(LOCK_EX). A second merge --wait N stays blocked for as long as the first invocation takes in its admission network calls: markers, membership, merged_sha, mark_confirmed and request, each with its own gh timeout. The second invocation only checks admit_by after it gets the lock. These calls have timeouts, so the wait is bounded in practice and the admission check still runs. However, the time spent waiting for the lock can use up most of the --wait budget without any message to the user. This is a non-blocking note. If it matters, you could print a line when the lock is contended, or use LOCK_NB in a poll loop bounded by admit_by.

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"
Expand Down Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

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 lost-reply re-read still allows a duplicate request if the comment shows up late

After _api raises ProcTimeout, request() reads the comments again right away. If GitHub accepted the POST but the comment isn't in the list yet (for example, the gh process was killed while GitHub was still committing the write), markers() returns False. The first invocation then raises and releases the lock, and the next invocation posts a second @mergifyio queue comment. The acceptance criteria allow this, since a missing marker counts as a failed POST, and Mergify mostly ignores a duplicate queue command. So this doesn't block the change. It is still the one race that remains. The smallest fix is a short bounded retry of the re-read, done only on ProcTimeout, before re-raising. It is also fine to leave this as is and document it.

if not markers(repo, number, head, queue)[0]:
raise


def mark_confirmed(repo: str, number: int, head: str, queue: str) -> None:
Expand Down
55 changes: 54 additions & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@
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

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
Expand Down Expand Up @@ -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
Expand Down
Loading