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
2 changes: 1 addition & 1 deletion skills/bounding-heavy-commands/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru
| `--cpus <n>` | Processor limit, as a whole number. Taken from the record. |
| `--exclusive <name>` | A resource that only one command may hold at a time, such as a fixed port. You choose the name. The wrapper keeps the names of each repository apart, and all worktrees of one repository share them. Repeat the option for each resource. |
| `--measure` | Also print a suggested budget. Discovery uses it. With no `--memory`, the command runs with the default budget where the hard cap is available, and alone in the queue where it is not. |
| `--measure-rows <n>,<n>,...` | Measure the command one time at each `--cpus` of the list, one after the other, the largest first. The largest runs with the `--memory` of the call. With no `--memory`, it runs with the default budget where the hard cap is available, and alone in the queue where it is not. Each smaller one runs with `--memory` at the suggested budget of the one before it. When the one before it did not exit 0, the smaller one runs with the same `--memory` as that one. Use it in place of `--cpus` and `--measure`. A stop signal ends the list. The exit code is the first exit code of a row that is not 0. |
| `--measure-rows <n>,<n>,...` | Measure the command one time at each `--cpus` of the list, one after the other, the largest first. The largest runs with the `--memory` of the call. With no `--memory`, it runs with the default budget where the hard cap is available, and alone in the queue where it is not. Each smaller one runs with `--memory` at the suggested budget of the one before it. When the one before it did not exit 0, the smaller one runs with the same `--memory` as that one. Use it in place of `--cpus` and `--measure`. A stop signal ends the list. A stop signal to the wrapper then ends the wrapper by that signal. So a Ctrl-C, which reaches the shell too, stops a line of joined calls; a signal sent to the wrapper alone does not stop the shell's line. Otherwise the exit code is the first exit code of a row that is not 0. |
| `--label <name>` | A name for the row lines of a measurement, such as `unit-tests`. Use letters, digits, `.`, `_`, and `-`, and start with a letter or a digit. It changes nothing else. |
| `--check` | Run no command. Print the state of the queue now, and for each `--memory`, whether a command of that budget would start now. It takes only `--memory`, which you can repeat. It holds no slot, and its exit code is 0. §The record says how to choose a row with it. |

Expand Down
49 changes: 46 additions & 3 deletions skills/bounding-heavy-commands/scripts/bounded_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@
bounded_run.py --check [--memory SIZE]...

The exit code is the exit code of the command. Exit code 125 means that this
script failed before the command gave a result.
script failed before the command gave a result. A stop signal to this script
(SIGHUP, SIGINT, SIGQUIT, or SIGTERM) stops the command, and then this script
ends by the same signal. So a Ctrl-C at the terminal, which reaches the shell
too, stops a line of joined commands; a signal sent to this script alone does
not stop the shell. A caller that reads the exit status reads 128 plus the
signal.

A measurement prints one row line on the error stream, in a fixed form:

Expand Down Expand Up @@ -67,6 +72,7 @@
import os
import random
import re
import resource
import shutil
import signal
import stat
Expand Down Expand Up @@ -108,6 +114,37 @@
STOP_CODES = frozenset(128 + int(signum) for signum in (signal.SIGHUP, signal.SIGINT, signal.SIGQUIT, signal.SIGTERM))


# The first stop signal that reached the wrapper in this run of main.
_stopped_by: List[int] = []


def _note_stop(signum: int) -> None:
if not _stopped_by:
_stopped_by.append(int(signum))


def exit_as(code: int) -> None:
"""Ends the process with the exit code, or, when a stop signal reached the wrapper, by that signal.

A shell stops a line of joined commands only when the command that runs dies from the signal and the shell
got the signal too, as with a Ctrl-C at the terminal. A caller that reads the status of a death by signal
reads 128 plus the signal.
"""
if _stopped_by:
signum = _stopped_by[0]
sys.stdout.flush()
sys.stderr.flush()
if signum == signal.SIGQUIT:
# The default action of SIGQUIT also writes a core file.
try:
resource.setrlimit(resource.RLIMIT_CORE, (0, resource.getrlimit(resource.RLIMIT_CORE)[1]))
except (ValueError, OSError):
pass
signal.signal(signum, signal.SIG_DFL)
os.kill(os.getpid(), signum)
sys.exit(code)


class WrapperError(Exception):
"""A failure of the wrapper, not of the command."""

Expand Down Expand Up @@ -1054,6 +1091,7 @@ def forward(signum: int, frame: object) -> None:
for signum, handler in previous.items():
signal.signal(signum, handler)
if received:
_note_stop(received[0])
return 128 + received[0], usage.ru_maxrss
return process.returncode, usage.ru_maxrss

Expand Down Expand Up @@ -1249,8 +1287,10 @@ def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int:
result = result or code
except (KeyboardInterrupt, _Stopped) as stop:
# A signal while a row runs comes back as its exit code. A signal at any other time in the list raises.
signum = stop.signum if isinstance(stop, _Stopped) else int(signal.SIGINT)
_note_stop(signum)
log("stopped by a signal; %d of %d rows are measured" % (measured, len(options.rows)))
return result or 128 + (stop.signum if isinstance(stop, _Stopped) else int(signal.SIGINT))
return result or 128 + signum
return result


Expand Down Expand Up @@ -1449,6 +1489,7 @@ def mib(value: Optional[int]) -> str:
def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int:
arguments = list(sys.argv[1:] if argv is None else argv)
variables = os.environ if environ is None else environ
del _stopped_by[:]
try:
if len(arguments) > 4 and arguments[0] == "--inside-cap" and arguments[3] == "--":
return inside_cap(arguments[1], arguments[2], arguments[4:])
Expand All @@ -1464,10 +1505,12 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st
try:
return bounded(options, variables)
except KeyboardInterrupt:
_note_stop(signal.SIGINT)
log("interrupted while waiting")
return 130
except _Stopped as stop:
# The handlers of --measure-rows can fire after its list ends, before they are put back.
_note_stop(stop.signum)
log("stopped by a signal")
return 128 + stop.signum
except WrapperError as error:
Expand All @@ -1476,4 +1519,4 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st


if __name__ == "__main__":
sys.exit(main())
exit_as(main())
126 changes: 114 additions & 12 deletions skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2565,13 +2565,13 @@ def test_a_nested_call_of_a_command_that_does_not_exist_gives_125(self):
self.assertNotIn("Traceback", errors)

def test_a_stop_signal_stops_the_command(self):
for signum, code in ((signal.SIGTERM, 143), (signal.SIGINT, 130), (signal.SIGQUIT, 131)):
for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT):
with self.subTest(signal=signum):
name = "stopped-%d" % code
name = "stopped-%d" % signum
process = self.worker(name, "2G", hold="300")
line = self.wait_for_event("start", name)
process.send_signal(signum)
self.assertEqual(process.wait(timeout=60), code)
self.assertEqual(process.wait(timeout=60), -signum)
child = int(line.split()[2])
deadline = time.time() + 5
alive = True
Expand All @@ -2583,12 +2583,12 @@ def test_a_stop_signal_stops_the_command(self):
alive = False
self.assertFalse(alive, "the command still runs")

def test_a_hangup_stops_the_command_and_gives_129(self):
def test_a_hangup_stops_the_command_and_ends_the_wrapper_by_the_hangup(self):
name = "hangup-129"
process = self.worker(name, "2G", hold="300")
line = self.wait_for_event("start", name)
process.send_signal(signal.SIGHUP)
self.assertEqual(process.wait(timeout=60), 129)
self.assertEqual(process.wait(timeout=60), -signal.SIGHUP)
child = int(line.split()[2])
deadline = time.time() + 5
alive = True
Expand Down Expand Up @@ -2619,7 +2619,7 @@ def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self):
self.wait_for_event("signaled", "stubborn", seconds=60.0)
self.assertIsNone(process.poll())
process.send_signal(signal.SIGTERM)
self.assertEqual(process.wait(timeout=60), 143)
self.assertEqual(process.wait(timeout=60), -signal.SIGTERM)
child = int(line.split()[2])
deadline = time.time() + 5
alive = True
Expand Down Expand Up @@ -2877,36 +2877,36 @@ def test_measured_rows_print_their_row_lines_in_order(self):
rows = re.findall(r"^bounded-run: row label=lint cpus=(\d+) budget=\d+M peak=\d+M held=- exact=no exit=0$", errors, re.MULTILINE)
self.assertEqual(rows, ["2", "1"], errors)

def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self):
def test_an_interrupt_in_the_queue_ends_the_wrapper_by_the_interrupt_with_no_traceback(self):
holder = self.worker("holder", "4G", hold="300")
self.wait_for_event("start", "holder")
waiting = self.worker("waiting", "4G", hold="0") # never reached; interrupted while still queued

self.wait_for_stderr(waiting, "waiting for")

waiting.send_signal(signal.SIGINT)
self.assertEqual(waiting.wait(timeout=60), 130)
self.assertEqual(waiting.wait(timeout=60), -signal.SIGINT)
buffer = self.stderr_of(waiting)
self.assertNotIn("Traceback", buffer)
for line in buffer.splitlines():
self.assertTrue(line.startswith("bounded-run: "), buffer)

holder.send_signal(signal.SIGTERM)
self.assertEqual(holder.wait(timeout=60), 143)
self.assertEqual(holder.wait(timeout=60), -signal.SIGTERM)

def hold_the_line(self):
os.makedirs(self.environ["BOUNDED_RUN_LOCK_DIR"], exist_ok=True)
descriptor = os.open(os.path.join(self.environ["BOUNDED_RUN_LOCK_DIR"], "line.lock"), os.O_RDWR | os.O_CREAT, 0o600)
bounded_run.fcntl.flock(descriptor, bounded_run.fcntl.LOCK_EX)
return descriptor

def test_an_interrupt_behind_others_in_the_line_gives_130_and_no_traceback(self):
def test_an_interrupt_behind_others_in_the_line_ends_the_wrapper_by_the_interrupt_with_no_traceback(self):
line = self.hold_the_line()
self.addCleanup(os.close, line)
waiting = self.worker("waiting", "2G", hold="0") # never reached; interrupted while still in the line
self.wait_for_stderr(waiting, "behind other commands")
waiting.send_signal(signal.SIGINT)
self.assertEqual(waiting.wait(timeout=10), 130)
self.assertEqual(waiting.wait(timeout=10), -signal.SIGINT)
buffer = self.stderr_of(waiting)
self.assertNotIn("Traceback", buffer)
self.assertIn("interrupted while waiting", buffer)
Expand Down Expand Up @@ -2993,6 +2993,108 @@ def test_a_fault_of_the_call_gives_125(self):
self.assertNotIn("check slots=", errors)


# Writes the pid of its parent, the wrapper, to the file in PARENT, then holds until the wrapper stops it.
PARENT_WRITER = "import os, time; open(os.environ['PARENT'], 'w').write(str(os.getppid())); time.sleep(300)"


@unittest.skipIf(shutil.which("bash") is None, "needs bash")
class JoinedLineTest(WrapperProcessCase):
"""Runs the wrapper as the first call of a line of bash that joins its calls with ';'.

A terminal sends Ctrl-C to the whole process group of the line. Bash stops the line only when
the call that runs dies from the signal. A plain sh can end from the signal by itself, so it proves nothing.
"""

def line(self, path, then, options, command, **environ):
"""Starts `wrapper; <then> "$0"` with $0 set to path, in a new process group."""
variables = dict(self.environ)
variables.update(environ)
process = subprocess.Popen(
["bash", "-c", '"$@"; ' + then + ' "$0"', path, sys.executable, WRAPPER] + options + ["--"] + command,
env=variables, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True,
)
self.processes.append(process)

def kill_group():
try:
os.killpg(process.pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
pass
self.addCleanup(kill_group)
return process

def wait_for_file(self, path, seconds=60.0):
deadline = time.time() + seconds
while time.time() < deadline:
try:
text = Path(path).read_text()
except OSError:
text = ""
if text:
return text
time.sleep(0.02)
self.fail("no %s after %s seconds" % (path, seconds))

def test_an_interrupt_while_the_command_runs_stops_the_line(self):
marker = os.path.join(self.base.name, "next-ran")
process = self.line(marker, "touch", ["--memory", "2G"], [sys.executable, "-c", WORKER, "joined"], HOLD="300")
self.wait_for_event("start", "joined")
os.killpg(process.pid, signal.SIGINT)
self.assertEqual(process.wait(timeout=60), -signal.SIGINT, self.stderr_of(process))
self.assertFalse(os.path.exists(marker), "the next command of the line ran")

def test_an_interrupt_while_the_wrapper_waits_in_the_queue_stops_the_line(self):
holder = self.worker("holder", "4G", hold="300") # holds every slot until the SIGTERM below
self.wait_for_event("start", "holder")
marker = os.path.join(self.base.name, "next-ran")
process = self.line(marker, "touch", ["--memory", "4G"], [sys.executable, "-c", WORKER, "queued"], HOLD="0")
self.wait_for_stderr(process, "waiting for")
os.killpg(process.pid, signal.SIGINT)
self.assertEqual(process.wait(timeout=60), -signal.SIGINT)
self.assertIn("interrupted while waiting", self.stderr_of(process))
self.assertFalse(os.path.exists(marker), "the next command of the line ran")
holder.send_signal(signal.SIGTERM)
holder.wait(timeout=60)

def test_an_interrupt_while_rows_are_measured_stops_the_rows_and_the_line(self):
marker = os.path.join(self.base.name, "next-ran")
process = self.line(marker, "touch", ["--measure-rows", "2,1"], [sys.executable, "-c", WORKER, "rows"], HOLD="300")
self.wait_for_event("start", "rows")
os.killpg(process.pid, signal.SIGINT)
self.assertEqual(process.wait(timeout=60), -signal.SIGINT)
errors = self.stderr_of(process)
self.assertIn("stopped by a signal; the rows after --cpus 2 are not measured", errors)
self.assertFalse(os.path.exists(marker), "the next command of the line ran")

def test_an_interrupt_after_a_failed_row_still_stops_the_line(self):
marker = os.path.join(self.base.name, "next-ran")
fail_then_hold = "import os, sys\nif os.environ['BOUNDED_RUN_CPUS'] == '2':\n sys.exit(3)\n" + WORKER
process = self.line(marker, "touch", ["--measure-rows", "2,1"], [sys.executable, "-c", fail_then_hold, "rows"], HOLD="300")
self.wait_for_event("start", "rows")
os.killpg(process.pid, signal.SIGINT)
self.assertEqual(process.wait(timeout=60), -signal.SIGINT)
errors = self.stderr_of(process)
self.assertRegex(errors, r"row label=- cpus=2 .* exit=3")
self.assertFalse(os.path.exists(marker), "the next command of the line ran")

def test_a_command_that_exits_130_by_itself_does_not_stop_the_line(self):
status = os.path.join(self.base.name, "status")
process = self.line(status, "echo $? >", ["--memory", "2G"], [sys.executable, "-c", "import sys; sys.exit(130)"])
self.assertEqual(process.wait(timeout=60), 0, self.stderr_of(process))
self.assertEqual(Path(status).read_text(), "130\n")

def test_the_caller_reads_128_plus_the_signal(self):
for signum in (signal.SIGINT, signal.SIGTERM):
with self.subTest(signal=signum):
status = os.path.join(self.base.name, "status-%d" % signum)
parent = os.path.join(self.base.name, "parent-%d" % signum)
# Only the wrapper gets the signal, so bash itself does not stop and reads the status.
process = self.line(status, "echo $? >", ["--memory", "2G"], [sys.executable, "-c", PARENT_WRITER], PARENT=parent)
os.kill(int(self.wait_for_file(parent)), signum)
self.assertEqual(process.wait(timeout=60), 0, self.stderr_of(process))
self.assertEqual(Path(status).read_text(), "%d\n" % (128 + signum))


@unittest.skipUnless(
bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None,
"no hard cap on this machine",
Expand Down Expand Up @@ -3028,7 +3130,7 @@ def test_a_stop_signal_stops_a_capped_command(self):
process = self.worker("capped", "1G", hold="300")
line = self.wait_for_event("start", "capped")
process.send_signal(signal.SIGTERM)
self.assertEqual(process.wait(timeout=60), 143)
self.assertEqual(process.wait(timeout=60), -signal.SIGTERM)
with self.assertRaises(ProcessLookupError):
deadline = time.time() + 5
while time.time() < deadline:
Expand Down
Loading