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
2 changes: 1 addition & 1 deletion src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1411,7 +1411,7 @@ def _wait_for_merge(config: Config, pr: github.PR, timeout: float) -> str | None
sha = _landed(config, pr, closed)
if sha:
return sha
if not github.merge_pending(config.repo, pr.number):
if not github.merge_pending(config.repo, pr.number, pr.head_sha):
sha = _landed(config, pr, closed)
if sha:
return sha
Expand Down
18 changes: 12 additions & 6 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1322,7 +1322,7 @@ def mark_ready(repo: str, number: int) -> None:

_QUEUE_QUERY = (
"query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name)"
"{pullRequest(number:$number){isInMergeQueue autoMergeRequest{enabledAt}}}}"
"{pullRequest(number:$number){headRefOid isInMergeQueue autoMergeRequest{enabledAt}}}}"
)


Expand Down Expand Up @@ -1354,7 +1354,7 @@ def merged_sha(
raise GhError(argv, "PR closed without a verified merge or invalid merge evidence")


def merge_pending(repo: str, number: int) -> bool:
def merge_pending(repo: str, number: int, head_sha: str) -> bool:
"""True when GitHub holds the PR for merging: queued, or accepted as an auto-merge
request that it moves into the queue shortly after (observed ~1 minute, #180)."""
owner, name = repo.split("/", 1)
Expand All @@ -1373,6 +1373,8 @@ def merge_pending(repo: str, number: int) -> bool:
raise MergeFailed(("gh", "api", "graphql"),
f"GitHub queue lookup for PR #{number}: queue status could not be verified. "
f"Check the PR's queue or merge state before retrying.\n{str(exc)[-300:]}") from exc
if pr.get("headRefOid") != head_sha:
raise MergeFailed(("gh", *argv), "PR head changed or unavailable during queue verification")
return queued or bool(auto)


Expand All @@ -1389,16 +1391,19 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None:
argv = (
"pr", "merge", str(number), "--repo", repo, *method, "--match-head-commit", head_sha,
)
if strategy == "queue" and merge_pending(repo, number, head_sha):

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: Only the queue strategy checks for admission before writing; squash/merge/rebase retries still send a second write

The check before the write (if strategy == "queue" and merge_pending(...)) only runs for strategy == "queue". merge() also treats a squash/merge/rebase request as accepted when GitHub queues it or turns it into an auto-merge request (test_merge_queued_returns_none with strategy=squash, auto=True). Example: a squash request is accepted as auto-merge, the reply is lost, and the run fails or is interrupted before the second read. The retry then sends another gh pr merge --squash. This retry case is the one the acceptance criterion "a retry observes admission before writing" describes. The second write is usually harmless because the read after it still finds the PR pending, but it is the same defect. Smallest fix: run the admission check for every strategy, which costs one GraphQL read, or explain in a comment why non-queue strategies are excluded. Then add the squash+auto case to the retry assertion in test_merge_queued_returns_none.

return None
write_error = None
try:
_gh(*argv, timeout=300)
except GhError as exc:
raise MergeFailed(exc.command, exc.tail) from exc
except (GhError, ProcTimeout, OSError) as exc:

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 write error is dropped when a later verification step raises

write_error only appears in the final "neither merged nor queued" message. In two cases the write failure never reaches the user:

  • merged_sha(..., expected_head=...) raises "PR head changed before merge verification". This is the usual result of a --match-head-commit rejection.
  • queue_error is re-raised, for example when gh pr merge was rejected for a failing required check and the queue lookup then had a transient error.

Before this change, the user always saw gh's rejection text. Smallest fix: attach write_error to the verification error. Either chain it (raise queue_error from write_error) or add its text to the message, and wrap the merged_sha calls the same way.

write_error = exc
sha = merged_sha(repo, number, expected_head=head_sha)
if sha:
return sha
queue_error = None
try:
if merge_pending(repo, number):
if merge_pending(repo, number, head_sha):
return None
except MergeFailed as exc:
queue_error = exc
Expand All @@ -1408,7 +1413,8 @@ def merge(repo: str, number: int, strategy: str, head_sha: str) -> str | None:
return sha
if queue_error:
raise queue_error
raise MergeFailed(("gh", *argv), f"PR #{number} neither merged nor queued")
detail = f": {write_error}" if write_error else ""
raise MergeFailed(("gh", *argv), f"PR #{number} neither merged nor queued{detail}")


def _remote_branch_head(endpoint: str) -> str | None:
Expand Down
26 changes: 22 additions & 4 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3223,6 +3223,19 @@ def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> Non
assert wt.exists()


def lose_native_merge_reply(monkeypatch):
original = github._gh

def transport(*args, **kwargs):
result = original(*args, **kwargs)
if args[:2] == ("pr", "merge"):
raise github.ProcTimeout("lost native merge reply", "")
return result

monkeypatch.setattr(github, "_gh", transport)


@pytest.mark.parametrize("lost_reply", [False, True])
@pytest.mark.parametrize("branch,changed", [
("lz/t1", False),
("t3/archive-review-receipts", False),
Expand All @@ -3231,13 +3244,15 @@ def test_merge_refuses_when_not_ready(wt: Path, gh: FakeGh, capsys, head) -> Non
("lz/t1", True),
])
def test_merge_prints_sha_and_cleans_up(
wt: Path, repo: Path, gh: FakeGh, capsys, changed, head, branch
wt: Path, repo: Path, gh: FakeGh, capsys, changed, head, branch, monkeypatch, lost_reply
) -> None:
git(wt, "branch", "-m", branch)
arm_approved_ready_pr(gh, head, wt, isDraft=False, branch=branch)
gh.respond("pr merge", "")
gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='c' * 40))
gh.respond("api -X", "")
if lost_reply:
lose_native_merge_reply(monkeypatch)
code, out, err = run(capsys, "merge")
out = without_accepted_receipt(out)
if changed:
Expand Down Expand Up @@ -3914,12 +3929,15 @@ def test_merge_of_externally_merged_pr_verifies_sha_and_cleans_up(
assert all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls)


def test_merge_queued_prints_and_keeps_worktree(wt: Path, gh: FakeGh, capsys, head) -> None:
@pytest.mark.parametrize("lost_reply", [False, True])
def test_merge_queued_prints_and_keeps_worktree(wt, gh, capsys, head, monkeypatch, lost_reply):
arm_approved_ready_pr(gh, head, wt, isDraft=False)
gh.respond("pr merge", "")
gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='OPEN', head=head_of(wt), sha=None))
gh.respond("api graphql", threads_json(),
{"data": {"repository": {"pullRequest": {"isInMergeQueue": True}}}})
{"data": {"repository": {"pullRequest": {"isInMergeQueue": True, "headRefOid": head}}}})
if lost_reply:
lose_native_merge_reply(monkeypatch)
code, out, err = run(capsys, "merge")
assert (code, err) == (0, "")
assert "queued for merge into main" in out and out.endswith(
Expand Down Expand Up @@ -4045,7 +4063,7 @@ def test_merge_wait_preserves_reviewed_head_and_cleans_only_landed_work(
merge_json(state="MERGED", head=head, sha="e" * 40) if landed else open_pr]
gh.append(f"api repos/{REPO}/pulls/7", *snapshots)
def queue(value: bool) -> dict:
return {"data": {"repository": {"pullRequest": {"isInMergeQueue": value}}}}
return {"data": {"repository": {"pullRequest": {"isInMergeQueue": value, "headRefOid": head}}}}
ejected = outcome in {"ejected", "landed-on-ejection"}
gh.respond("api graphql", threads_json(), queue(True), queue(not ejected))
gh.respond("api -X", "")
Expand Down
14 changes: 10 additions & 4 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1221,6 +1221,8 @@ def test_merge_success_verifies_rest_landing(

def test_merge_command_failure(gh: FakeGh) -> None:
gh.fail("pr merge", "head commit mismatch")
gh.respond(f"api repos/{REPO}/pulls/7", merge_json())
gh.respond("api graphql", _queue_json(False))
with pytest.raises(github.MergeFailed) as info:
github.merge(REPO, 7, "rebase", HEAD)
assert "--rebase" in info.value.command and "mismatch" in info.value.tail
Expand All @@ -1239,7 +1241,7 @@ def test_delete_remote_branch_checks_encoded_ref(gh: FakeGh, remote_head: str |


def _queue_json(queued: bool) -> dict:
return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued}}}}
return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued, "headRefOid": HEAD}}}}


@pytest.mark.parametrize("missing", [False, True])
Expand All @@ -1262,10 +1264,14 @@ def test_merge_queued_returns_none(gh: FakeGh, strategy, auto) -> None:
accepted = _queue_json(not auto)
if auto:
accepted["data"]["repository"]["pullRequest"]["autoMergeRequest"] = {"enabledAt": "t"}
gh.respond("api graphql", accepted)
gh.respond("api graphql", *([_queue_json(False)] if strategy == "queue" else []), accepted)
assert github.merge(REPO, 7, strategy, HEAD) is None
assert ("--squash" in gh.argv(0)) == (strategy == "squash")
assert "--queue" not in gh.argv(0)
if strategy == "queue":
assert github.merge(REPO, 7, strategy, HEAD) is None
writes = [c["argv"] for c in gh.calls if c["argv"][:2] == ["pr", "merge"]]
assert len(writes) == 1
assert ("--squash" in writes[0]) == (strategy == "squash")
assert "--queue" not in writes[0]


def test_merge_landed_between_reads_is_reported_merged(gh: FakeGh) -> None:
Expand Down
Loading