diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index e740b328..eca19872 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1427,19 +1427,39 @@ def _mergify_timeout_detail( return detail -MERGIFY_DEQUEUE_HINT = ( - 'Read Mergify\'s "Left the queue" comment on the PR for the reason. ' - "Address it before requeueing. To requeue, post `@mergifyio queue` as the whole PR comment " +MERGIFY_REQUEUE = ( + "To requeue, post `@mergifyio queue` as the whole PR comment " "(same login), then rerun `loopzero merge --wait`." ) +MERGIFY_DEQUEUE_HINT = ( + 'Read Mergify\'s "Left the queue" comment on the PR for the reason. Address it before requeueing.' +) + + +def _mergify_departure_hint(report: mergify.Departure | None) -> str: + if report is None: + return f"{MERGIFY_DEQUEUE_HINT} {MERGIFY_REQUEUE}" + detail = f"Mergify report: {report.url}." + if report.checks: + detail += " Failing checks: " + ", ".join(repr(check) for check in report.checks) + "." + guidance = { + "stacked": "Mergify tested a stack and could not attribute the failure. Inspect the candidate in the report or requeue after the earlier PRs clear.", + "isolated": "Mergify tested this PR alone. Inspect or fix the failed check before requeueing unless it is a known flake.", + } + return f"{detail} {guidance.get(report.attribution, MERGIFY_DEQUEUE_HINT)} {MERGIFY_REQUEUE}" def _mergify_departure( - config: Config, pr: github.PR, queue: str, closed: list[github.GhError], + config: Config, pr: github.PR, queue: str, closed: list[github.GhError], confirmed: bool, ) -> str | None: + report = mergify.departure_report(config.repo, pr.number, pr.head_sha, queue) + if not confirmed and report is None: + return None sha = _landed(config, pr, closed) if not sha and not closed: - raise CliError(f"PR #{pr.number} left Mergify queue {queue} unmerged. {MERGIFY_DEQUEUE_HINT}") + raise CliError( + f"PR #{pr.number} left Mergify queue {queue} unmerged. {_mergify_departure_hint(report)}" + ) return sha @@ -1468,8 +1488,8 @@ def _wait_for_mergify( mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) confirmed = True print(f"PR #{pr.number} confirmed in Mergify queue {queue}; waiting") - elif state is None and confirmed: - if sha := _mergify_departure(config, pr, queue, closed): + elif state is None: + if sha := _mergify_departure(config, pr, queue, closed, confirmed): return sha # A queued, open PR normally gets its next landing read on the next tick. if deferred_landing_read and (sha := _landed(config, pr, closed)): @@ -1508,10 +1528,10 @@ def _merge_with_mergify( 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: + closed: list[github.GhError] = [] + if sha := _mergify_departure(config, pr, queue, closed, confirmed=True): return sha - raise CliError(f"PR #{pr.number} left Mergify queue {queue} unmerged. {MERGIFY_DEQUEUE_HINT}") + raise closed[0] if not confirmed and not requested: if admit_by is not None and time.monotonic() > admit_by: raise _AdmissionDeadline diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 2bcc90f1..eb21eef7 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -6,6 +6,7 @@ import http.client import json import os +import re import stat import time import urllib.error @@ -236,6 +237,72 @@ def _admission_report(comments: list[dict], requested_at: str) -> int | None: return None +def _queue_command(body: str, queue: str) -> bool: + words = body.partition("\n")[0].split() + return (len(words) in (2, 3) and words[0].lower() in ("@mergify", "@mergifyio") + and words[1].lower() in ("queue", "requeue") and words[2:] in ([], [queue])) + + +@dataclass(frozen=True) +class Departure: + url: str + checks: tuple[str, ...] + attribution: str + + +def _departure_payload(body: str, queue: str) -> dict: + _, _, text = body.partition("-*- Mergify Payload -*-\n") + try: + payload = json.loads(text.partition("\n-*- Mergify Payload End -*-")[0]) + except json.JSONDecodeError: + return {} + if (isinstance(payload, dict) and payload.get("version") == 1 + and payload.get("state") == "dequeued" and payload.get("queue_rule_name") == queue): + return payload + return {} + + +def departure_report(repo: str, number: int, head: str, queue: str) -> Departure | None: + """Use a bot report only when it identifies the latest command and current head.""" + try: + comments = github._paged(f"repos/{repo}/issues/{number}/comments") + except github.GhError: + return None + comments = [item for item in comments if type(item.get("id")) is int and item["id"] > 0] + command = max( + (item for item in comments if _queue_command(str(item.get("body") or ""), queue)), + key=lambda item: item["id"], default={}, + ) + latest = max( + (item for item in comments if isinstance(user := item.get("user"), dict) + and user.get("login") == "mergify[bot]"), + key=lambda item: (str(item.get("updated_at") or ""), item["id"]), default={}, + ) + body = str(latest.get("body") or "") + payload = _departure_payload(body, queue) + if not command or not payload: + return None + + url = f"https://github.com/{repo}/pull/{number}#issuecomment-" + entered = next((line for line in body.splitlines() if line.startswith("- ✅ **Entered the queue** ")), "") + source = re.search(r"^- 🚫 \*\*Left the queue\*\* [^\n]+ · `([0-9a-f]{7,40})`$", body, re.M) + if f"]({url}{command['id']})" not in entered or not source or not head.startswith(source[1]): + return None + markers = [line for line in str(command.get("body") or "").splitlines() + if line.startswith(f"", + "report": "\n\n### ❌ Left the queue · `checks` failed\n\n**So far**\n- ✅ **Entered the queue** Wed 25 Nov, 22:12 · rule `main` · triggered by @eowca with the [`@mergifyio queue` command](@url@#issuecomment-42)\n- ❌ **Checks failed** · draft [#965](/feder-positronics/loop-zero/pull/965)\n- 🚫 **Left the queue** 22:13 · `@sha@`\n\n", + "attribution": { + "stacked": "**Not proven to be this pull request's failure.** It failed on top of the pull requests ahead of it, and was not tested alone.", + "isolated": "**The failure is in this pull request.** It failed tested alone on top of `main`." + }, + "expected": { + "stacked": [ + "stack", + "earlier" + ], + "isolated": [ + "tested this PR alone", + "flake" + ], + "unknown": [ + "Address it before requeueing" + ] + }, + "admission": { + "current": "2026-11-25T19:01:00Z", + "stale": "2026-11-25T18:59:00Z", + "missing": null + }, + "admission_report": "### ⏳ Waiting for queue conditions\n\n- [ ] `check-success = Queue Preflight`", + "requeue_guidance": [ + "as the whole PR comment (same login)", + "`loopzero merge --wait`" + ], + "candidate_responses": { + "blocking": { + "number": 7, + "queue_rule_name": "main", + "queued_at": "now", + "position": 1, + "mergeability_check": { + "queue_pull_request_number": 42, + "checks": [ + { + "name": "checks", + "state": "success" + } + ], + "conditions_evaluation": { + "match": false, + "label": "all of", + "subconditions": [ + { + "match": false, + "label": "check-success = Queue Quality Gate", + "subconditions": [] + } + ] + } + } + }, + "neutral": { + "number": 7, + "queue_rule_name": "main", + "queued_at": "now", + "position": 1, + "mergeability_check": { + "queue_pull_request_number": 42, + "checks": [ + { + "name": "checks", + "state": "neutral" + } + ], + "conditions_evaluation": { + "match": true, + "label": "all of", + "subconditions": [ + { + "match": true, + "label": "any of", + "subconditions": [ + { + "match": false, + "label": "check-success = checks", + "subconditions": [] + }, + { + "match": true, + "label": "check-neutral = checks", + "subconditions": [] + } + ] + } + ] + } + } + }, + "skipped": { + "number": 7, + "queue_rule_name": "main", + "queued_at": "now", + "position": 1, + "mergeability_check": { + "queue_pull_request_number": 42, + "checks": [ + { + "name": "checks", + "state": "skipped" + } + ], + "conditions_evaluation": { + "match": true, + "label": "all of", + "subconditions": [ + { + "match": true, + "label": "any of", + "subconditions": [ + { + "match": false, + "label": "check-success = checks", + "subconditions": [] + }, + { + "match": true, + "label": "check-skipped = checks", + "subconditions": [] + } + ] + } + ] + } + } + }, + "missing": { + "number": 7, + "queue_rule_name": "main", + "queued_at": "now", + "position": 1, + "mergeability_check": { + "queue_pull_request_number": 42, + "checks": [ + { + "name": "checks", + "state": "success" + } + ], + "conditions_evaluation": null + } + } + }, + "candidate_condition": "check-success = Queue Quality Gate" +} diff --git a/tests/test_cli.py b/tests/test_cli.py index cb422f69..151444ec 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -45,6 +45,7 @@ REPO = "acme/widgets" URL = f"https://github.com/{REPO}/pull/7" +MERGIFY_QUEUE_FIXTURE = json.loads((Path(__file__).with_name("fixtures") / "mergify-queue.json").read_text()) BRANCH_READ = branch_head_key().split() PR_LIST_READ = pr_list_key().split() LOOKUP_CALLS = [BRANCH_READ, PR_LIST_READ, ["api", f"repos/{REPO}/pulls/7"]] @@ -4335,29 +4336,49 @@ def remove_worktree_then_poll(*args): assert message in out + err -@pytest.mark.parametrize("report", ["current", "stale", None]) -def test_mergify_reports_admission_wait(wt, gh, capsys, monkeypatch, report): +@pytest.mark.parametrize("confirmed,kind", [ + (False, "current"), (False, "stale"), (False, "missing"), + (False, "stacked"), (True, "stacked"), (True, "isolated"), (True, "unknown"), + (False, "head"), (False, "requeue"), (False, "author"), (False, "landed"), +]) +def test_mergify_reports_current_queue_attempt(wt, gh, capsys, monkeypatch, confirmed, kind): commit_mergify_configuration(wt) head = head_of(wt) arm_approved_ready_pr(gh, head, wt, isDraft=False) - comments = [{"user": {"login": LOGIN}, "created_at": "2026-11-25T19:00:00Z", - "body": f"@mergifyio queue\n\n"}] - if report: - comments.append({ - "id": 43, "user": {"login": "mergify[bot]"}, - "updated_at": "2026-11-25T19:01:00Z" if report == "current" else "2026-11-25T18:59:00Z", - "body": "### ⏳ Waiting for queue conditions\n\n- [ ] `check-success = Queue Preflight`", - }) + admission = kind in MERGIFY_QUEUE_FIXTURE["admission"] + comments = [{"id": 42, "user": {"login": LOGIN}, "created_at": "2026-11-25T19:00:00Z", + "body": MERGIFY_QUEUE_FIXTURE["request"].replace("@head@", head)}] + if kind != "missing": + template = MERGIFY_QUEUE_FIXTURE["admission_report"] if admission else MERGIFY_QUEUE_FIXTURE["report"] + body = template.replace("@url@", URL).replace("@sha@", "f" * 7 if kind == "head" else head[:7]) + comments.append({"id": 43, "user": {"login": "someone-else" if kind == "author" else "mergify[bot]"}, + "updated_at": MERGIFY_QUEUE_FIXTURE["admission"].get(kind), + "body": body + MERGIFY_QUEUE_FIXTURE["attribution"].get(kind, "")}) + if kind == "requeue": + comments.append({"id": 44, "user": {"login": LOGIN}, "body": "@mergifyio queue"}) gh.respond(f"api repos/{REPO}/issues/7/comments", comments) monkeypatch.setattr(mergify, "configured", lambda *_: True) - monkeypatch.setattr(mergify, "membership", lambda *_: None) + membership = iter([mergify.Membership()] if confirmed else []) + monkeypatch.setattr(mergify, "membership", lambda *_: next(membership, None)) + monkeypatch.setattr(mergify, "mark_confirmed", lambda *_: None) monkeypatch.setattr(mergify, "request", lambda *_: pytest.fail("already requested")) - - for args, expected_code in [(("status",), 0), (("merge", "--wait=0"), 3)]: - code, out, err = run(capsys, *args) - assert (code, err) == (expected_code, "") - assert "waiting for admission" in out - assert (f"{URL}#issuecomment-43" in out) is (report == "current") + if kind == "landed": + opened = rest_pr_json(pr_json(headRefOid=head, isDraft=False)) + gh.append(f"api repos/{REPO}/pulls/7", *([opened] * 3), merge_json(state="MERGED", head=head, sha="e" * 40)) + gh.respond("api -X", "") + if admission: + status, summary, error = run(capsys, "status") + assert (status, error) == (0, "") and "waiting for admission" in summary + assert (f"{URL}#issuecomment-43" in summary) is (kind == "current") + code, out, err = run(capsys, "merge", "--wait=0") + if kind == "landed": + assert (code, err) == (0, "") and not wt.exists() and out.splitlines()[-1] == "e" * 40 + elif kind in MERGIFY_QUEUE_FIXTURE["expected"]: + assert code == 1 and wt.exists() and f"{URL}#issuecomment-43" in err and "'checks'" in err + assert all(part in err for part in [*MERGIFY_QUEUE_FIXTURE["requeue_guidance"], *MERGIFY_QUEUE_FIXTURE["expected"][kind]]) + else: + assert code == 3 and wt.exists() and "waiting for admission" in out + assert (f"{URL}#issuecomment-43" in out) is (kind == "current") @pytest.mark.parametrize("result", ["blocking", "neutral", "skipped", None]) @@ -4368,35 +4389,14 @@ def test_mergify_timeout_reports_evaluated_candidate_conditions(wt, gh, capsys, monkeypatch.setattr(mergify, "configured", lambda *_: True) monkeypatch.setattr(mergify, "markers", lambda *_: (True, False)) monkeypatch.setattr(mergify, "mark_confirmed", lambda *_: None) - condition = "check-success = Queue Quality Gate" - evaluation = None if result is None else { - "match": result != "blocking", - "label": "all of", - "subconditions": [ - {"match": False, "label": condition, "subconditions": []} - if result == "blocking" else - {"match": True, "label": "any of", "subconditions": [ - {"match": False, "label": "check-success = checks", "subconditions": []}, - {"match": True, "label": f"check-{result} = checks", "subconditions": []}, - ]}, - ], - } - payload = { - "number": 7, "queue_rule_name": "main", "queued_at": "now", "position": 1, - "mergeability_check": { - "queue_pull_request_number": 42, - "checks": [{"name": "checks", "state": result if result in ("neutral", "skipped") else "success"}], - "conditions_evaluation": evaluation, - }, - } - responses = iter([None, payload]) + responses = iter([None, MERGIFY_QUEUE_FIXTURE["candidate_responses"][result or "missing"]]) monkeypatch.setattr(mergify, "api_get", lambda *_: next(responses)) code, out, err = run(capsys, "merge", "--wait=0") assert (code, err) == (3, "") assert f"https://github.com/{REPO}/pull/42" in out - assert (condition in out) is (result == "blocking") + assert (MERGIFY_QUEUE_FIXTURE["candidate_condition"] in out) is (result == "blocking") assert "failed" not in out and "check-success = checks" not in out