From 1c765bed182110f06318d87de2b8f0b5b42c406a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:22:37 +0100 Subject: [PATCH 1/3] Unwind supervised subprocesses on CLI SIGTERM Architecture-Review: unchanged; CLI dispatch shares the existing signal handler and preserves termination during late signal delivery. Co-Authored-By: Codex --- src/loopzero/_proc.py | 55 ++++++++++++++++++++++++++++++++++--- src/loopzero/cli.py | 3 ++- src/loopzero/sandbox.py | 60 ++++------------------------------------- tests/test_cli.py | 51 +++++++++++++++++++++++++++++++++++ tests/test_proc.py | 20 ++++++++++++++ 5 files changed, 130 insertions(+), 59 deletions(-) diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index c86dc83f..ef21b46c 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -5,9 +5,10 @@ import os import signal import subprocess +import threading import time from collections.abc import Mapping, Sequence -from contextlib import suppress +from contextlib import contextmanager, suppress from dataclasses import dataclass from pathlib import Path @@ -32,6 +33,55 @@ def __init__( self.duration_s = duration_s +class Terminated(BaseException): + """Unwind the active operation before exiting from SIGTERM.""" + + +def _request_unwind(_signum, _frame): + signal.signal(signal.SIGTERM, signal.SIG_IGN) + raise Terminated + + +@contextmanager +def unwind_on_sigterm(): + if (threading.current_thread() is not threading.main_thread() + or signal.getsignal(signal.SIGTERM) != signal.SIG_DFL): + yield + return + try: + try: + signal.signal(signal.SIGTERM, _request_unwind) + yield + finally: + signal.signal(signal.SIGTERM, signal.SIG_DFL) + except Terminated: + signal.signal(signal.SIGTERM, signal.SIG_DFL) + signal.raise_signal(signal.SIGTERM) + raise + + +@contextmanager +def defer_sigterm(): + """Finish a private directory operation before unwinding.""" + if (threading.current_thread() is not threading.main_thread() + or signal.getsignal(signal.SIGTERM) is not _request_unwind): + yield + return + pending = False + + def remember_signal(_signum, _frame): + nonlocal pending + pending = True + + signal.signal(signal.SIGTERM, remember_signal) + try: + yield + finally: + signal.signal(signal.SIGTERM, _request_unwind) + if pending: + _request_unwind(signal.SIGTERM, None) + + @dataclass(frozen=True) class Completed: exit_code: int @@ -102,8 +152,7 @@ def run( raise FileNotFoundError(f"working directory {cwd} does not exist") from exc raise ToolMissing(f"{argv[0]}: executable not found on PATH") from exc except subprocess.TimeoutExpired as exc: - out = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else exc.stdout - out = out or "" + out = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "") err = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else exc.stderr elapsed = time.monotonic() - started raise ProcTimeout( diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 31c6ad72..f6b09163 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1803,7 +1803,8 @@ def main(argv: list[str] | None = None) -> int: if conflicts: parser.error(f"review --repost cannot be combined with {' or '.join(conflicts)}") try: - return args.func(args) + with _proc.unwind_on_sigterm(): + return args.func(args) except IndependentReviewerUnavailable as exc: print(f"loopzero {args.command}: {exc}", file=sys.stderr) return 4 diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 5ddeae70..b4b9cec6 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -11,7 +11,6 @@ import re import resource import shutil -import signal import stat import tempfile import threading @@ -52,55 +51,6 @@ class SandboxUnavailable(LoopZeroError): """bubblewrap is missing or cannot create a sandbox on this host.""" -class _Terminated(BaseException): - """Unwind the active operation before exiting from SIGTERM.""" - - -def _request_unwind(_signum, _frame): - signal.signal(signal.SIGTERM, signal.SIG_IGN) - raise _Terminated - - -@contextmanager -def _unwind_on_sigterm(): - if (threading.current_thread() is not threading.main_thread() - or signal.getsignal(signal.SIGTERM) != signal.SIG_DFL): - yield - return - try: - try: - signal.signal(signal.SIGTERM, _request_unwind) - yield - finally: - signal.signal(signal.SIGTERM, signal.SIG_DFL) - except _Terminated: - signal.signal(signal.SIGTERM, signal.SIG_DFL) - signal.raise_signal(signal.SIGTERM) - raise - - -@contextmanager -def _defer_sigterm(): - """Finish a private directory operation before unwinding.""" - if (threading.current_thread() is not threading.main_thread() - or signal.getsignal(signal.SIGTERM) is not _request_unwind): - yield - return - pending = False - - def remember_signal(_signum, _frame): - nonlocal pending - pending = True - - signal.signal(signal.SIGTERM, remember_signal) - try: - yield - finally: - signal.signal(signal.SIGTERM, _request_unwind) - if pending: - _request_unwind(signal.SIGTERM, None) - - @contextmanager def _private_directories(): with ExitStack() as stack: @@ -108,12 +58,12 @@ def _private_directories(): yield stack finally: # Keep the stack's own exit as a fallback if SIGTERM arrives before deferral. - with _defer_sigterm(): + with _proc.defer_sigterm(): stack.close() def _enter_private_directory(stack: ExitStack, prefix: str) -> Path: - with _defer_sigterm(): + with _proc.defer_sigterm(): directory = tempfile.TemporaryDirectory(prefix=prefix) stack.callback(directory.cleanup) return Path(directory.name) @@ -122,7 +72,7 @@ def _enter_private_directory(stack: ExitStack, prefix: str) -> Path: @contextmanager def private_directory(prefix: str): """Keep a private directory scoped to an operation, including on SIGTERM.""" - with _unwind_on_sigterm(), _private_directories() as stack: + with _proc.unwind_on_sigterm(), _private_directories() as stack: yield _enter_private_directory(stack, prefix) @@ -154,7 +104,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO git_dir = _git_dir(config, worktree, "--git-dir") _validate_scratch(config.scratch, worktree, common_dir, git_dir) - with _unwind_on_sigterm(), _private_directories() as stack: + with _proc.unwind_on_sigterm(), _private_directories() as stack: prefix = [] if not config.check_runner: home = _enter_private_directory(stack, "loopzero-home-") @@ -354,7 +304,7 @@ def heartbeat(): join_reporter = True try: yield - except _Terminated: + except _proc.Terminated: join_reporter = False raise finally: diff --git a/tests/test_cli.py b/tests/test_cli.py index 4b779553..9fc58f38 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -5,12 +5,16 @@ import base64 import errno import json +import os import re import shutil +import signal import subprocess import sys +from contextlib import suppress from dataclasses import replace from pathlib import Path +from select import select from types import SimpleNamespace from unittest.mock import Mock from urllib.parse import quote @@ -3580,6 +3584,53 @@ def test_status_full(wt: Path, gh: FakeGh, capsys, git_calls) -> None: assert sum(1 for c in gh.calls if c["argv"][:2] == ["api", reviews_key()[4:]]) == 1 +@pytest.mark.parametrize(("signum", "status"), [ + (signal.SIGTERM, -signal.SIGTERM), + (signal.SIGINT, 130), +]) +def test_status_reaps_gh_after_signal(wt, fake_tool, signum, status): + fake_tool("gh", "exec /bin/sleep 30") + driver = """ +import subprocess +import sys +from loopzero import cli, github + +github.app_token = lambda: "" +communicate = subprocess.Popen.communicate + +def announce(process, *args, **kwargs): + if process.args[0] == "gh": + print(process.pid, flush=True) + return communicate(process, *args, **kwargs) + +subprocess.Popen.communicate = announce +sys.exit(cli.main(["status"])) +""" + env = {**os.environ, "PYTHONPATH": str(Path(cli.__file__).resolve().parents[1])} + with subprocess.Popen( + [sys.executable, "-c", driver], cwd=wt, env=env, stdout=subprocess.PIPE, bufsize=0, + ) as process: + child = None + try: + # Read until the supervisor enters communicate on the offline gh child. + for _ in range(6): + assert select([process.stdout], [], [], 5)[0] + line = process.stdout.readline().strip() + if line.isdigit(): + child = int(line) + break + assert child is not None + process.send_signal(signum) + assert process.wait(timeout=5) == status + with pytest.raises(ProcessLookupError): + os.kill(child, 0) + finally: + process.kill() + if child is not None: + with suppress(ProcessLookupError): + os.killpg(child, signal.SIGKILL) + + def test_status_silently_ignores_legacy_report_without_dirty( wt: Path, gh: FakeGh, capsys, head ) -> None: diff --git a/tests/test_proc.py b/tests/test_proc.py index f2dc4159..ba289e03 100644 --- a/tests/test_proc.py +++ b/tests/test_proc.py @@ -14,6 +14,26 @@ from loopzero import _proc +def test_unwind_on_sigterm_when_signal_arrives_during_disposition_restore(): + script = """ +import signal +from loopzero import _proc + +set_disposition = signal.signal + +def deliver_before_restore(signum, disposition): + if signum == signal.SIGTERM and disposition is signal.SIG_DFL and callable(signal.getsignal(signum)): + signal.raise_signal(signum) + return set_disposition(signum, disposition) + +signal.signal = deliver_before_restore +with _proc.unwind_on_sigterm(): + pass +""" + result = subprocess.run([sys.executable, "-c", script], capture_output=True, timeout=5) + assert result.returncode == -signal.SIGTERM, result.stderr.decode() + + def test_run_captures_output_exit_code_and_duration(tmp_path): done = _proc.run( [sys.executable, "-c", "import sys; print('out'); print('err', file=sys.stderr); sys.exit(3)"], From b6a7527bb5c8ba31e505841a9452c5a78a93c668 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:57:55 +0100 Subject: [PATCH 2/3] Report Mergify departures tied to the current queue attempt Architecture-Review: unchanged; departure diagnostics use the existing authenticated report and still verify the exact head before a verdict. Co-Authored-By: Codex --- src/loopzero/cli.py | 40 +++++++++++---- src/loopzero/mergify.py | 71 +++++++++++++++++++++++++-- tests/fixtures/mergify-departure.json | 31 ++++++++++++ tests/test_cli.py | 55 ++++++++++++++------- 4 files changed, 167 insertions(+), 30 deletions(-) create mode 100644 tests/fixtures/mergify-departure.json 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`" + ] +} diff --git a/tests/test_cli.py b/tests/test_cli.py index cb422f69..7e855503 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4335,29 +4335,50 @@ 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`", - }) + fixture = json.loads((Path(__file__).with_name("fixtures") / "mergify-departure.json").read_text()) + admission = kind in fixture["admission"] + comments = [{"id": 42, "user": {"login": LOGIN}, "created_at": "2026-11-25T19:00:00Z", + "body": fixture["request"].replace("@head@", head)}] + if kind != "missing": + template = fixture["admission_report"] if admission else 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": fixture["admission"].get(kind), + "body": body + 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 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 [*fixture["requeue_guidance"], *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]) From 929cbc812c930eb85811dc8e92525c4a1039bf08 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:07:04 +0100 Subject: [PATCH 3/3] Share fixtures for Mergify report and candidate tests Co-Authored-By: Codex --- tests/fixtures/mergify-departure.json | 31 ------ tests/fixtures/mergify-queue.json | 150 ++++++++++++++++++++++++++ tests/test_cli.py | 41 ++----- 3 files changed, 160 insertions(+), 62 deletions(-) delete mode 100644 tests/fixtures/mergify-departure.json create mode 100644 tests/fixtures/mergify-queue.json diff --git a/tests/fixtures/mergify-departure.json b/tests/fixtures/mergify-departure.json deleted file mode 100644 index ab1cdfd9..00000000 --- a/tests/fixtures/mergify-departure.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "request": "@mergifyio queue\n\n", - "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`" - ] -} diff --git a/tests/fixtures/mergify-queue.json b/tests/fixtures/mergify-queue.json new file mode 100644 index 00000000..9a892e44 --- /dev/null +++ b/tests/fixtures/mergify-queue.json @@ -0,0 +1,150 @@ +{ + "request": "@mergifyio queue\n\n", + "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 7e855503..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"]] @@ -4344,16 +4345,15 @@ def test_mergify_reports_current_queue_attempt(wt, gh, capsys, monkeypatch, conf commit_mergify_configuration(wt) head = head_of(wt) arm_approved_ready_pr(gh, head, wt, isDraft=False) - fixture = json.loads((Path(__file__).with_name("fixtures") / "mergify-departure.json").read_text()) - admission = kind in fixture["admission"] + admission = kind in MERGIFY_QUEUE_FIXTURE["admission"] comments = [{"id": 42, "user": {"login": LOGIN}, "created_at": "2026-11-25T19:00:00Z", - "body": fixture["request"].replace("@head@", head)}] + "body": MERGIFY_QUEUE_FIXTURE["request"].replace("@head@", head)}] if kind != "missing": - template = fixture["admission_report"] if admission else fixture["report"] + 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": fixture["admission"].get(kind), - "body": body + fixture["attribution"].get(kind, "")}) + "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) @@ -4373,9 +4373,9 @@ def test_mergify_reports_current_queue_attempt(wt, gh, capsys, monkeypatch, conf 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 fixture["expected"]: + 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 [*fixture["requeue_guidance"], *fixture["expected"][kind]]) + 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") @@ -4389,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