Skip to content
Closed
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
15 changes: 13 additions & 2 deletions scripts/retro_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions scripts/size_budget.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
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 @@ -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(
Expand Down
3 changes: 2 additions & 1 deletion src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1777,7 +1777,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 @@ -3640,6 +3644,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
51 changes: 51 additions & 0 deletions tests/test_retro_metrics.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import subprocess
from types import SimpleNamespace

import pytest

Expand Down Expand Up @@ -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
Loading