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..ce52ff65 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1799,7 +1799,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 a358d56f..f74eed7e 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 3421662b..725858d1 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 @@ -3669,6 +3673,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)"],