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
40 changes: 30 additions & 10 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


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

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: Every admission-wait tick now reads the full PR comment list

Before this change, a tick where state is None and not confirmed made no extra calls. Now each such tick calls mergify.departure_report, which reads every page of issues/{n}/comments through github._paged. That call comes on top of the merged_sha, configured and membership reads the tick already makes. On a long --wait with a PR that has many comments, this uses up GitHub rate limit while Mergify is only waiting on preflight checks. It is not wrong, since GhError falls back to None. Smallest fix: before fetching the comments, check something cheap that shows a departure could have happened, for example that the request marker exists and the latest Mergify comment's updated_at has changed. Or fetch comments every Nth tick and once before timing out.

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)):
Expand Down Expand Up @@ -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
Expand Down
71 changes: 68 additions & 3 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import http.client
import json
import os
import re
import stat
import time
import urllib.error
Expand Down Expand Up @@ -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"<!-- {REQUEST} ")]
if markers and _marker(REQUEST, head, queue) not in markers:
return None

reason = payload.get("dequeue_reason")
checks = reason.get("checks") if isinstance(reason, dict) else None
names = tuple(name for name in checks if isinstance(name, str) and name) if isinstance(checks, list) else ()
attribution = next((kind for prefix, kind in (
("**The failure is in this pull request.** It failed tested alone on top of ", "isolated"),
("**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.", "stacked"),
) if any(line.startswith(prefix) for line in body.splitlines())), "")
return Departure(f"{url}{latest['id']}", names, attribution)


def request_status(repo: str, number: int, head: str, queue: str) -> tuple[bool, bool, str | None]:
login, requested, confirmed = github.login(token=""), False, False
requested_at = ""
Expand All @@ -244,9 +311,7 @@ def request_status(repo: str, number: int, head: str, queue: str) -> tuple[bool,
user = item.get("user")
if isinstance(user, dict) and user.get("login") == login:
lines = str(item.get("body") or "").splitlines()
words = lines[0].split() if lines else []
requeue = (len(words) in (2, 3) and words[0].lower() in ("@mergify", "@mergifyio")
and words[1].lower() in ("queue", "requeue") and words[2:] in ([], [queue]))
requeue = _queue_command(str(item.get("body") or ""), queue)
if _marker(REQUEST, head, queue) in lines or (requeue and confirmed):
requested, requested_at = True, str(item.get("created_at") or "")
confirmed = _marker(CONFIRMED, head, queue) in lines or (confirmed and not requeue)
Expand Down
150 changes: 150 additions & 0 deletions tests/fixtures/mergify-queue.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
{
"request": "@mergifyio queue\n\n<!-- loopzero:mergify-request head=@head@ queue=main -->",
"report": "<!---\nDO NOT EDIT\n-*- Mergify Payload -*-\n{\"version\": 1, \"state\": \"dequeued\", \"queue_rule_name\": \"main\", \"dequeue_reason\": {\"code\": \"CHECKS_FAILED\", \"checks\": [\"checks\"]}}\n-*- Mergify Payload End -*-\n-->\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"
}
Loading
Loading