Skip to content
Merged
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 @@ -1595,7 +1595,7 @@ def _wait_for_merge(config: Config, pr: github.PR, timeout: float) -> str | None
for _ in _poll_until(started, timeout):
if sha := _landed(config, pr, closed):
return sha
if not github.merge_pending(config.repo, pr.number):
if not github.merge_pending(config.repo, pr.number, pr.head_sha):
if sha := _landed(config, pr, closed):
return sha
if not closed:
Expand Down
18 changes: 12 additions & 6 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1423,7 +1423,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 @@ -1454,7 +1454,7 @@ def merged_sha(
raise error(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)."""
args = _pull_query(repo, number, _QUEUE_QUERY)
Expand All @@ -1469,6 +1469,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", *args), "PR head changed or unavailable during queue verification")
return queued or bool(auto)


Expand All @@ -1485,16 +1487,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: The admission check before writing only runs for strategy == "queue"

merge_pending also returns True for an accepted auto-merge request. The squash, merge and rebase strategies reach that state on a queue-protected base, and test_merge_queued_returns_none covers that case. A retry after a lost reply under those strategies still sends a second gh pr merge. That second write is probably harmless, because gh rejects it or treats it as a no-op and the queue check afterwards returns None. Still, it falls short of the stated goal that a retry observes admission before writing. Consider either running the check for every strategy, or documenting that only queue is protected this way.

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:
write_error = exc
sha = merged_sha(repo, number, expected_head=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: The write error is lost when the follow-up read raises

write_error is only added to the message when all three reads finish without an error. If gh pr merge fails and merged_sha then raises, the caller sees only the read error and never the real reason the merge was rejected. This happens when the head has moved ("PR head changed before merge verification" hides gh's "head commit mismatch"), on invalid evidence, or on ClosedUnmerged. The same applies when merge_pending raises queue_error (line 1415). The run still fails closed and keeps the worktree, so this is not a correctness bug, but the diagnosis is harder. Smallest fix: wrap the reads after the write so that a GhError raised while write_error is set is re-raised as MergeFailed, with the write error added to its tail and chained with from.

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 @@ -1504,7 +1509,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
32 changes: 25 additions & 7 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3263,15 +3263,30 @@ def test_open_finding_blocks_delivery(wt, gh, capsys, head, command, conclusion,
assert all(c["argv"][:2] != ["pr", command] for c in gh.calls)


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", [
*((branch, False) for branch in TASK_BRANCHES), ("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_squash_merge(gh, head, wt, merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='c' * 40), branch=branch)
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 @@ -3839,13 +3854,16 @@ def test_merge_of_externally_merged_pr_verifies_sha_and_cleans_up(
assert not err and f"PR #7 was already merged as {'e' * 12}" in out and out.endswith("e" * 40 + "\n")


def native_queue(queued):
return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued}}}}
def native_queue(queued, head):
return {"data": {"repository": {"pullRequest": {"isInMergeQueue": queued, "headRefOid": head}}}}


def test_merge_queued_prints_and_keeps_worktree(wt: Path, gh: FakeGh, capsys, head) -> None:
arm_squash_merge(gh, head, wt, merge_json(state='OPEN', head=head_of(wt), sha=None))
gh.respond("api graphql", threads_json(), native_queue(True))
@pytest.mark.parametrize("lost_reply", [False, True])
def test_merge_queued_prints_and_keeps_worktree(wt, gh, capsys, head, monkeypatch, lost_reply):
arm_squash_merge(gh, head, wt, merge_json(state='OPEN', head=head, sha=None))
gh.respond("api graphql", threads_json(), native_queue(True, head))
if lost_reply:
lose_native_merge_reply(monkeypatch)
expect_cli(capsys, 0, "merge", stderr="", stdout_contains=("queued for merge into main",),
stdout_endswith="next: loopzero merge --wait follows the queue, verifies and cleans up\n")
assert wt.exists()
Expand Down Expand Up @@ -3975,7 +3993,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)
ejected = outcome in {"ejected", "landed-on-ejection"}
gh.respond("api graphql", threads_json(), native_queue(True), native_queue(not ejected))
gh.respond("api graphql", threads_json(), native_queue(True, head), native_queue(not ejected, head))
gh.respond("api -X", "")
poll_clock(monkeypatch, jitter=1.0)
wait = 0 if ejected else 60
Expand Down
15 changes: 11 additions & 4 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -1114,6 +1114,8 @@ def test_merge_success_verifies_rest_landing(gh: FakeGh) -> None:

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 Down Expand Up @@ -1147,7 +1149,7 @@ def test_delete_remote_branch_scopes_operator_tokens(gh: FakeGh, fake_tool, monk


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

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: No test for a missing or changed headRefOid in the queue check

The new head check in merge_pending (github.py:1376) is part of the acceptance criteria ('moved head or missing evidence ... reports failure'). Every updated fixture supplies a matching headRefOid, so no test fails if the check is removed. Add a test_github case where headRefOid is missing or different, for both the check before writing and the check after writing. It should assert that MergeFailed is raised and that no pr merge write is sent when the check before writing fails.



def arm_merge(gh: FakeGh, queue: dict, *details: dict) -> None:
Expand Down Expand Up @@ -1178,10 +1180,15 @@ def test_merge_reports_queue_admission_or_landing(gh, strategy, queue_state):
if landed:
snapshots.append(merge_json(state="MERGED", sha="d" * 40))
arm_merge(gh, accepted, *snapshots)
if strategy == "queue":
gh.respond("api graphql", _queue_json(False), accepted)

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 queue branch silently replaces the GraphQL responses that arm_merge sets

arm_merge already calls gh.respond("api graphql", accepted). FakeGh.respond replaces the responses for a key rather than adding to them, so for strategy == "queue" the extra gh.respond("api graphql", _queue_json(False), accepted) throws away what arm_merge set. The test is correct, but a reader has to know that replace behaviour to see why. Smallest fix: call arm_merge(gh, _queue_json(False) if strategy == "queue" else accepted, *snapshots) and use gh.append("api graphql", accepted) for the queue case, or add a short comment saying the call overrides the earlier one.

assert github.merge(REPO, 7, strategy, HEAD) == ("d" * 40 if landed else None)
if not landed:
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_merged_sha_only_for_merged_state(gh: FakeGh) -> None:
Expand Down
Loading