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 @@ -1525,7 +1525,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 @@ -1534,28 +1534,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: Worktree lock is held across several GitHub round-trips that other task-state writers share

_lock_task_state is the same flock that _save_report (cli.py:374) and the other task-state writers (cli.py:544, 675, 860) use. Admission now holds it while it pages issue comments (markers), reads membership, calls merged_sha, may post mark_confirmed, may build a departure report, and on a lost reply runs a second markers page read. Each of these can take up to the gh timeout, so a concurrent loopzero check can block for several timeouts before it publishes its receipt. This is correct, since it is released before _wait_for_mergify as the acceptance requires, but it is broader than needed. If contention matters, a smaller fix is to move the lock-free reads (merged_sha and the confirmed/departure handling) outside the lock. The lock would then cover only re-reading markers/membership and the request POST. Alternatively, add a comment explaining why the wider scope is intentional.

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 @@ -1603,7 +1603,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:

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: Lost-reply recovery in request is only correct when the caller holds the admission lock

The fallback treats any existing REQUEST marker for this head and queue as proof that this POST was accepted. That holds only because the caller re-read the markers under _lock_task_state and found none. request is a public module function with no such precondition in its signature, so a future unlocked caller could take a marker from an earlier run as its own success. A one-line docstring would document the precondition: the caller must have seen no marker under the worktree lock.

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:
Expand Down
53 changes: 53 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -3953,6 +3955,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 github.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