Skip to content
Closed
55 changes: 52 additions & 3 deletions src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down
43 changes: 32 additions & 11 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
19 changes: 16 additions & 3 deletions src/loopzero/hosted.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
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
60 changes: 5 additions & 55 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import re
import resource
import shutil
import signal
import stat
import tempfile
import threading
Expand Down Expand Up @@ -52,68 +51,19 @@ 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:
try:
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)
Expand All @@ -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)


Expand Down Expand Up @@ -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-")
Expand Down Expand Up @@ -354,7 +304,7 @@ def heartbeat():
join_reporter = True
try:
yield
except _Terminated:
except _proc.Terminated:
join_reporter = False
raise
finally:
Expand Down
Loading
Loading