diff --git a/SETUP.md b/SETUP.md index 557f4782..5b87243d 100644 --- a/SETUP.md +++ b/SETUP.md @@ -74,6 +74,14 @@ symlinked skill directory and resolve its relative links from the real files, so the contract and references stay reachable. Do not also keep copies of these skills in a repository: both would load. +Before resuming automated PR check refreshes or explicit PR resyncs after an +upgrade, advance every PR-body writer to the selected CLI revision. For +unverified receipt warnings, use a revision containing +[3ff80bd9 (#1160)](https://github.com/feder-positronics/loop-zero/commit/3ff80bd91c92f12d557cead31776df40d4328097). +Once the writers are updated, run `loopzero check` for the current head to +replace old receipts. If you roll back across that fix, pause those writes before +switching the CLI and resume them once the writers support the warning again. + If you roll back across [#732](https://github.com/feder-positronics/loop-zero/pull/732) after GitHub may have accepted a Claude review, run `loopzero review --repost` with the publishing CLI revision or a newer compatible revision. The rollback diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 31e63dfa..3bfaf9a0 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 @@ -107,8 +157,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 46a93e29..b1393e13 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1442,19 +1442,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 @@ -1483,8 +1503,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)): @@ -1523,10 +1543,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 @@ -1799,7 +1819,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/github.py b/src/loopzero/github.py index dc8baabb..dc64281d 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -1462,6 +1462,14 @@ def commit_status(repo: str, head: str, context: str, state: str, description: s raise +def status_matches(repo: str, head: str, context: str, state: str, description: str) -> bool: + statuses = _iter_paged(f"repos/{repo}/commits/{head}/statuses") + latest = next((row for row in statuses if row.get("context") == context), {}) + creator = latest.get("creator") + return (isinstance(creator, dict) and creator.get("login") == "github-actions[bot]" + and (latest.get("state"), latest.get("description")) == (state, description)) + + def _status_limit_reached(repo: str, head: str, context: str) -> bool: # A validation error alone does not prove exhaustion. with suppress(GhError, ProcTimeout, OSError): diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 726b64f6..3b963850 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -89,12 +89,25 @@ def policy(source_number: int, source: dict) -> None: if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,): message = "Awaiting trusted review of current source head" state = "pending" - publish(state, message) - print(message) - return 0 if ready or state == "pending" else 1 except Exception as exc: _mark_refresh_failed(publish, exc) raise + _publish_verdict(cfg.repo, head, state, message[:140]) + print(message) + return 0 if ready or state == "pending" else 1 + + +def _publish_verdict(repo: str, head: str, state: str, description: str) -> None: + context = eligibility.CONTEXT + try: + github.commit_status(repo, head, context, state, description) + except github.StatusLimitReached: + raise + except (github.GhError, github.ProcTimeout, OSError) as exc: + with suppress(github.GhError, github.ProcTimeout, OSError): + if github.status_matches(repo, head, context, state, description): + return + raise LoopZeroError(f"Could not confirm eligibility status publication: {exc}") from exc def _mark_refresh_failed(publish: Callable[[str, str], None], exc: Exception) -> None: 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 3421662b..e9f304b6 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 @@ -45,6 +49,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"]] @@ -3669,6 +3674,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: @@ -4355,29 +4407,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]) @@ -4388,35 +4460,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 @@ -4744,19 +4795,28 @@ def test_generated_pr_body_limit(wt, gh, capsys, monkeypatch, create, extra): assert json.loads(writes[0]["--input"])["body"] == prose + suffix -def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): +@pytest.mark.parametrize("refresh", ["resync", "automatic"]) +def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys, refresh): head = head_of(wt) - live = "# PR\n\n## Validation\nManual validation evidence.\n" + config = cli._load_config(SimpleNamespace(command="check", config=None), wt, pin_checks=True) + live = ("# PR\n\n## Validation\nManual validation evidence.\n\n" + "\n" + f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0\n" + "\n") gh.respond_pr_list([pr_json(headRefOid=head, body=live)]) gh.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {}) - cli._save_report(wt, CheckReport(head, False, (CheckResult("echo ok", 0, 0.0, ""),))) + stages = tuple(CheckResult(command, 0, 0.0, "") for command in config.checks) + cli._save_report(wt, CheckReport(head, False, stages)) + git(wt, "push", "-q", "-u", "origin", "lz/t1") - assert run(capsys, "pr")[0] == 0 + if refresh == "resync": + assert run(capsys, "pr")[0] == 0 + else: + cli._refresh_pr_checks(wt, config) draft = json.loads(gh.calls[-1]["--input"])["body"] assert "unverified" in draft and "run `loopzero check`" in draft assert "Manual validation evidence." in draft - git(wt, "push", "-q", "-u", "origin", "lz/t1") gh.respond_pr_list([pr_json(headRefOid=head, body=draft)]) assert run(capsys, "check")[0] == 0 draft = json.loads(gh.calls[-1]["--input"])["body"] diff --git a/tests/test_hosted.py b/tests/test_hosted.py index e15e7912..60092cc1 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -104,6 +104,45 @@ def test_merged_source_refresh_publishes_nothing(publisher): assert hosted.main() == 0 and not [c for c in publisher.calls if "--input" in c] and publisher.argv(0)[-1] == "--include" +@pytest.mark.parametrize("state,readback", [ + ("success", "match"), ("failure", "match"), ("success", "absent"), + ("success", "publisher"), ("success", "description"), ("success", "state"), + ("success", "unreadable"), +]) +def test_final_status_lost_reply(publisher, monkeypatch, state, readback): + ready = state == "success" + monkeypatch.setattr(hosted.eligibility, "evaluate", + lambda *_: github.Readiness(ready, () if ready else ("Blocking finding",))) + post = github.commit_status + endpoint = f"api repos/{REPO}/commits/{HEAD}/statuses" + monkeypatch.setattr(github, "_retry_sleep", lambda _: None) + + def lose_reply(repo, head, context, value, description): + post(repo, head, context, value, description) + if description.startswith(("Refreshing", "Eligibility refresh failed")): + return + accepted = {"context": context, "state": value, "description": description, + "creator": {"login": "github-actions[bot]"}} + assert value == state + observed = { + "absent": [], + "publisher": [accepted | {"creator": {"login": "other"}}, accepted], + "description": [accepted | {"description": "other"}, accepted], + "state": [accepted | {"state": "pending"}, accepted], + "unreadable": {"exit": 1, "stderr": "unavailable"}, + }.get(readback, [accepted]) + publisher.respond(endpoint, observed) + raise github.ProcTimeout("lost status reply", "") + + monkeypatch.setattr(github, "commit_status", lose_reply) + if readback == "match": + assert hosted.main() == (0 if ready else 1) + else: + with pytest.raises(hosted.LoopZeroError, match="confirm eligibility status publication"): + hosted.main() + assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] + + @pytest.mark.parametrize("error", ["api", "head", "publication", "config"]) def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, error): monkeypatch.setattr(github, "_retry_sleep", lambda _: None) @@ -124,7 +163,7 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er if error == "publication": assert "invalid description (HTTP 422)" in str(raised.value) statuses = [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] - assert statuses == ([] if error == "config" else ["pending", "pending", "failure"] + assert statuses == ([] if error == "config" else ["pending", "pending"] if error == "publication" else ["pending", "failure"]) 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)"],