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
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)

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: Unwind-time children inherit SIGTERM=SIG_IGN, now across the whole CLI

_request_unwind sets SIGTERM to SIG_IGN until unwind_on_sigterm exits. Popen(restore_signals=True) only resets SIGPIPE, SIGXFZ and SIGXFSZ. So any subprocess started from a finally/cleanup path while Terminated is propagating keeps ignoring SIGTERM after exec. This already happened inside sandbox scopes. Because cli.main now wraps every command, it can affect any cleanup that runs Git or gh. Impact is small: those children are short-lived and _proc.run SIGKILLs on exceptions. Smallest fix: block SIGTERM with signal.pthread_sigmask instead of using SIG_IGN, or pass a preexec_fn/process_group reset in _proc.run. At minimum, add a comment documenting it.

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 @@ -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 "")

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: Unrelated TimeoutExpired refactor

This change folds out = out or "" into the conditional expression. It is behavior-neutral but unrelated to SIGTERM unwinding, and the new line is longer than the surrounding style. Revert it to keep the diff focused.

err = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else exc.stderr
elapsed = time.monotonic() - started
raise ProcTimeout(
Expand Down
3 changes: 2 additions & 1 deletion src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1798,7 +1798,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
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
51 changes: 51 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
20 changes: 20 additions & 0 deletions tests/test_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)"],
Expand Down
Loading