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
66 changes: 36 additions & 30 deletions scripts/pr_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@
activity. The loop runs in-process, so a 45-minute wait costs one agent turn, not 90. A pull request
found no longer open, on the first read or on any poll, is neither requested nor polled further. `wait` then prints its digest and exits
as `status` does, so a 0 there says nothing about review coverage, and `state=` says why.
No poll sleeps past --timeout. The digest prints after the reads that follow it. A SIGINT or SIGTERM prints one line naming it and re-raises that signal, exiting 130 on Windows instead.
Exit 0 = review present, or on a held head an attested local pass whose checks no longer
hold the poll, with no thread open where the pull request is open. Exit 0 on a review
present polls the checks only for an after-checks CodeRabbit or Qodo still to ask, so it does not prove the required checks ran. On an open attested held head whose commit the payload carries,
Expand Down Expand Up @@ -232,12 +233,14 @@
from __future__ import annotations

import argparse
import contextlib
import functools
import io
import itertools
import json
import os
import re
import signal
import subprocess
import sys
import tarfile
Expand Down Expand Up @@ -944,20 +947,14 @@ def origin_owner() -> str | None:
if k not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY")
and not k.startswith("GIT_CONFIG")
}
argv = ["git", "-C", str(HERE), "remote", "get-url", "origin"]
try:
url = _run(
["git", "-C", str(HERE), "remote", "get-url", "origin"],
5,
"git could not be run",
text=True,
encoding="utf-8",
env=env,
).stdout.strip()
url = _run(argv, 5, "git could not be run", text=True, encoding="utf-8", env=env).stdout
# `_run` returns a missing git or a timeout as no output, and a decode error lands here.
except Exception: # noqa: BLE001
return None
m = re.search(r"[:/]([A-Za-z0-9_.\-]+)/([A-Za-z0-9_.\-]+?)(?:\.git)?/?$", url)
return m.group(1).lower() if m else None
slug = shared.origin_slug(url.strip())
return slug.split("/")[0] if slug else None


def in_scope(target_owner: str) -> tuple[bool, str]:
Expand Down Expand Up @@ -1248,16 +1245,18 @@ def backoff[Polled](

`delays` defaults to `POLL_DELAYS`, its last delay repeated only where a clock bounds the loop.
A finite schedule ends by running out, with no clock where `start` is None. Otherwise `start`
is a `time.monotonic` reading and `timeout` is in seconds, checked before each sleep. Returns
the last value read, or `value` itself where the poll never sleeps.
is a `time.monotonic` reading and `timeout` is in seconds. Each sleep is cut to the time left,
so no sleep runs past the bound and one read follows it there. Returns the last value read, or
`value` itself where the poll never sleeps.
"""
if delays is None:
repeated = itertools.repeat(POLL_DELAYS[-1]) if start is not None else ()
delays = itertools.chain(POLL_DELAYS, repeated)
for delay in delays:
if not keep(value) or (start is not None and time.monotonic() - start > timeout):
left = float("inf") if start is None else timeout - (time.monotonic() - start)
if not keep(value) or left <= 0:
break
time.sleep(delay)
time.sleep(min(delay, left))
value = read()
return value

Expand Down Expand Up @@ -1399,14 +1398,8 @@ def gh_takes_escape_flag() -> bool:

def _gh_run(argv: list[str], raw: bool) -> subprocess.CompletedProcess:
"""Run one `gh` read, a log decoded leniently since its bytes are the runner's own."""
return _run(
argv,
30,
"gh could not be run",
text=True,
encoding="utf-8",
errors="replace" if raw else "strict",
)
errors = "replace" if raw else "strict"
return _run(argv, 30, "gh could not be run", text=True, encoding="utf-8", errors=errors)


def answered_absent(proc: subprocess.CompletedProcess) -> bool:
Expand Down Expand Up @@ -1724,13 +1717,8 @@ def read_live() -> tuple[bool, dict | None, list[str], bool]:
polls = True
else:
polls = True
backoff(
(done, answer, drift),
lambda: live_state(owner, repo, a.number, a.min_rounds),
lambda s: not any(s),
start,
a.timeout,
)
live = functools.partial(live_state, owner, repo, a.number, a.min_rounds)
backoff((done, answer, drift), live, lambda s: not any(s), start, a.timeout)

ask("after-checks", await_green if polls else None)
# One payload decides the digest and the exit code together, and the digest also prints at the timeout.
Expand Down Expand Up @@ -2188,5 +2176,23 @@ def refuse_foreign(late: bool) -> None:
return run_wait(owner, repo, a)


def on_sigterm(signum: int, _frame: object) -> None:
"""Raise SIGTERM as a `KeyboardInterrupt` carrying its number, so both signals unwind one path."""
raise KeyboardInterrupt(signum)
Comment thread
ptr727 marked this conversation as resolved.
Resolved


if __name__ == "__main__":
sys.exit(main())
signal.signal(signal.SIGTERM, on_sigterm)
try:
sys.exit(main())
except KeyboardInterrupt as stop:
signum = signal.Signals(stop.args[0] if stop.args else signal.SIGINT)
print(f"pr_review.py: interrupted by {signum.name}.", file=sys.stderr)
with contextlib.suppress(OSError):
sys.stdout.flush()
sys.stderr.flush()
if os.name == "nt":
sys.exit(130)
signal.signal(signum, signal.SIG_DFL)
os.kill(os.getpid(), signum)
sys.exit(128 + signum)
88 changes: 84 additions & 4 deletions tests/test_pr_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import unittest
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
Expand All @@ -46,6 +49,12 @@
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "spec"))
from git_env import without_git_location
from import_probe import import_delta
from test_pre_commit_hook import (
assert_group_ended,
end_group,
wait_until_started,
write_executable,
)

DEFAULT_POLICY = pr_review.review_policy.load_default()
_POLICY_PATCH = mock.patch.object(
Expand Down Expand Up @@ -3161,6 +3170,29 @@ def test_wait_returns_zero_once_the_review_lands_on_the_head(self) -> None:
slept.assert_not_called()
self.assertIn("waited=", self.out.getvalue())

def test_wait_sleeps_no_further_than_its_timeout_and_then_prints_the_digest(self) -> None:
"""No sleep runs past `--timeout`, so the outcome follows it by the reads alone.

Sleeps of 15, 20, and 30 seconds reach 65, and the next is cut from 45 to 35. Uncut, the
wait slept to 110 seconds on a 100-second bound before it printed anything.
"""
self.answer(payload([], pending=True))
clock = [0.0]

def sleep(seconds: float) -> None:
clock[0] += seconds

with (
mock.patch.object(pr_review.time, "monotonic", side_effect=lambda: clock[0]),
mock.patch.object(pr_review.time, "sleep", side_effect=sleep),
):
self.assertEqual(30, self.cli(["wait", "7", "--timeout", "100"]))
self.assertEqual(100, clock[0])
out = self.out.getvalue()
self.assertIn("pr=7", out)
self.assertIn("waited=100s", out)
self.assertIn("\nstatus=PENDING", out)

def test_wait_exits_forty_four_where_the_review_closed_but_a_check_is_starved(self) -> None:
"""Exit 0 was saying the review loop closing is the merge gate, and it is not.

Expand Down Expand Up @@ -7332,10 +7364,11 @@ def test_the_backoff_is_bounded_and_non_decreasing(self) -> None:
self.assertEqual(delays, sorted(delays))

def test_the_backoff_sleeps_the_schedule_until_the_timeout(self) -> None:
"""The last delay repeats, and the bound is read before each sleep rather than after.
"""The last delay repeats, and each sleep is cut to the time left, so none runs past the bound.

Six sleeps reach 290 seconds and a seventh 410, so with a 400-second bound the eighth is
never taken.
Six sleeps reach 290 seconds, so with a 400-second bound the seventh is cut to 110 and no
eighth is taken. Uncut, the seventh reached 410, and an outer bound at 400 ended the
process before anything printed.
"""
clock = [0.0]
slept: list[int] = []
Expand All @@ -7350,7 +7383,7 @@ def sleep(seconds: int) -> None:
mock.patch.object(pr_review.time, "sleep", side_effect=sleep),
):
last = pr_review.backoff(0, lambda: next(reads), lambda _: True, 0.0, 400)
self.assertEqual([15, 20, 30, 45, 60, 120, 120], slept)
self.assertEqual([15, 20, 30, 45, 60, 120, 110], slept)
self.assertEqual(7, last)

def test_the_backoff_returns_the_first_value_it_does_not_keep(self) -> None:
Expand Down Expand Up @@ -8485,5 +8518,52 @@ def test_the_dedupe_falls_back_to_the_app_slug_for_a_null_workflow_run(self) ->
self.assertEqual([("lint", "FAILURE"), ("lint", "SUCCESS")], kept)


@unittest.skipIf(os.name == "nt", "Windows cannot deliver SIGTERM for a script to handle")
class TestWaitInterrupt(unittest.TestCase):
"""A SIGTERM mid-wait prints one line naming it, stops the read in flight, and ends by it.

An outer bound kills a wait with SIGTERM, and a wait killed that way once printed nothing at
all. The script runs under its interpreter directly, since a launcher hides the signal death.
It runs from a copy of the scripts tree whose origin names a constructed owner. A stand-in
`gh` on PATH holds the first read open, so the signal lands mid-wait with a child to stop.
"""

def test_sigterm_mid_wait_prints_one_line_and_ends_by_that_signal(self) -> None:
"""The signal goes half a second after the stand-in starts, once the read is under way."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
scripts = root / "checkout" / "scripts"
shutil.copytree(REPO / "scripts", scripts, ignore=shutil.ignore_patterns("__pycache__"))
env = without_git_location()
git = ["git", "-C", str(scripts.parent)]
subprocess.run(["git", "init", "--quiet", str(scripts.parent)], check=True, env=env)
origin = "https://github.com/acme/widget.git"
subprocess.run([*git, "remote", "add", "origin", origin], check=True, env=env)
bin_dir, ready = root / "bin", root / "gh.started"
bin_dir.mkdir()
write_executable(bin_dir / "gh", f'#!/bin/sh\n: > "{ready}"\nexec sleep 300\n')
env["PATH"] = f"{bin_dir}{os.pathsep}{env.get('PATH', '')}"
argv = [sys.executable, str(scripts / "pr_review.py"), "wait", "7"]
proc = subprocess.Popen(
[*argv, "--repo", "acme/widget", "--timeout", "600"],
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
start_new_session=True,
)
try:
wait_until_started(proc, ready)
time.sleep(0.5)
proc.send_signal(signal.SIGTERM)
_, err = proc.communicate(timeout=60)
finally:
end_group(proc)
self.assertEqual(-signal.SIGTERM, proc.returncode, err)
self.assertEqual("pr_review.py: interrupted by SIGTERM.\n", err)
assert_group_ended(proc.pid)


if __name__ == "__main__":
unittest.main(verbosity=2)
Loading