From fbcce3a2ec6bcae5517e4e557044c76cf68eb8c0 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:06:50 +0100 Subject: [PATCH 1/3] Verify linked PR commit completeness at the activity limit Co-Authored-By: Codex --- scripts/retro_metrics.py | 15 +++++++++-- tests/test_retro_metrics.py | 51 +++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/scripts/retro_metrics.py b/scripts/retro_metrics.py index 4945b5ac..a8cee3ed 100755 --- a/scripts/retro_metrics.py +++ b/scripts/retro_metrics.py @@ -294,6 +294,16 @@ def count(value): } +def _complete_pr_commits(inputs, path, commits): + if commits is None: + return False + if len(commits) < 250: + return True + detail = inputs.get(path, lambda: run_json(["gh", "api", "--method", "GET", path]), dict) + count = (detail or {}).get("commits") + return type(count) is int and count == len(commits) + + def issue_progress(inputs, repo, issue, end): timeline = pages(inputs, f"repos/{repo}/issues/{issue['number']}/timeline") if timeline is None: @@ -313,9 +323,10 @@ def issue_progress(inputs, repo, issue, end): if not match or timestamp(event["created_at"]) >= end: continue dates += [timestamp(source["created_at"]), timestamp(event["created_at"])] - commits = pages(inputs, f"repos/{match[1]}/pulls/{match[2]}/commits") + pull = f"repos/{match[1]}/pulls/{match[2]}" + commits = pages(inputs, f"{pull}/commits") comments = pages(inputs, f"repos/{match[1]}/issues/{match[2]}/comments") - if commits is None or len(commits) >= 250 or comments is None: + if comments is None or not _complete_pr_commits(inputs, pull, commits): raise ValueError("linked PR activity unavailable or truncated") dates += [timestamp(item["commit"]["committer"]["date"]) for item in commits] dates += [timestamp(item["created_at"]) for item in comments] diff --git a/tests/test_retro_metrics.py b/tests/test_retro_metrics.py index 9f1309a5..f66cb609 100644 --- a/tests/test_retro_metrics.py +++ b/tests/test_retro_metrics.py @@ -1,5 +1,6 @@ import json import subprocess +from types import SimpleNamespace import pytest @@ -196,3 +197,53 @@ def test_invalid_band_is_usage_error(capsys): retro_metrics.main(["--repo", REPO, "--until", END, "--band", "merges", "3", "2"]) assert exc.value.code == 2 assert "ordered limits" in capsys.readouterr().err + + +@pytest.mark.parametrize(("rows", "total", "stalled"), [ + (101, None, True), + (250, 250, True), + (250, 251, False), + (250, None, False), +]) +def test_stalled_issue_checks_linked_pr_commit_count_at_limit( + tmp_path, monkeypatch, rows, total, stalled, +): + old = "2026-05-26T00:00:00Z" + pull = f"repos/{REPO}/pulls/3" + calls = [] + + def collect(argv): + endpoint = argv[-1] + calls.append(endpoint) + if endpoint == pull: + return {} if total is None else {"commits": total} + if endpoint.startswith(f"{pull}/commits?"): + page = int(endpoint.rsplit("=", 1)[1]) + size = min(100, rows - (page - 1) * 100) + return [{"commit": {"committer": {"date": old}}}] * size + if endpoint == f"repos/{REPO}/issues/3/comments?per_page=100&page=1": + return [] + assert endpoint == f"repos/{REPO}/issues/4/timeline?per_page=100&page=1" + return [{ + "event": "cross-referenced", "created_at": old, + "source": {"issue": {"created_at": old, "pull_request": { + "url": f"https://api.github.com/{pull}", + }}}, + }] + + monkeypatch.setattr(retro_metrics, "run_json", collect) + args = SimpleNamespace(repo=REPO, stall_hours=12) + priority_issues = [issue(4, old)] + end = retro_metrics.timestamp(END) + live = retro_metrics.Inputs(tmp_path, record=True) + alerts = retro_metrics.stalled_p0s(live, args, priority_issues, end) + assert [alert["kind"] for alert in alerts] == (["stalled_p0"] if stalled else []) + assert any(a["source"] == "p0/#4/activity" for a in live.alerts) == (not stalled) + assert calls.count(pull) == (1 if rows == 250 else 0) + + live.save() + before = calls.copy() + replay = retro_metrics.Inputs(tmp_path, record=False) + assert retro_metrics.stalled_p0s(replay, args, priority_issues, end) == alerts + assert replay.alerts == live.alerts + assert calls == before From 72f49165c22a50f0e85bdc47c6e51adc3101cb05 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:12:09 +0100 Subject: [PATCH 2/3] Raise the source line cap to 8,250 Architecture-Review: unchanged; the size check keeps the same counters and enforcement with the approved source threshold. Co-Authored-By: Codex --- scripts/size_budget.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/size_budget.sh b/scripts/size_budget.sh index c1bcca8d..ebd78fb5 100755 --- a/scripts/size_budget.sh +++ b/scripts/size_budget.sh @@ -8,11 +8,11 @@ # it under the cap. # Usage: scripts/size_budget.sh [BASE] (default: merge-base with origin/main) set -euo pipefail -# Measured 2026-11-10: 6777 source lines. +# Measured 2026-11-26: 7494 source lines. # Measured 2026-11-25: 12289 test lines. # Measured 2026-11-25: 1406 core Markdown / 600 delegation Markdown lines. # Allow ~10% growth, rounded up, so small fixes do not require cap changes. -SRC_CAP=7500 +SRC_CAP=8250 TESTS_CAP=13500 CORE_DOCS_CAP=1500 DELEGATION_DOC_CAP=660 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 3/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)"],