Skip to content

Commit 3cca79c

Browse files
sourcehawkclaude
andcommitted
fix(skills/bounding-heavy-commands): stop a joined line on one Ctrl-C
A line of wrapper calls joined with ';' needed one Ctrl-C for each call. The wrapper caught the signal, cleaned up, and exited normally with 130, so the shell ran the next call. When a stop signal (SIGINT, SIGTERM, SIGHUP, SIGQUIT) reaches the wrapper, while it waits in the queue or while the command runs, the wrapper now finishes its cleanup and its lines, restores the default handler, and sends the signal to itself. The shell sees a death by signal and stops the line. A caller that reads the status still reads 128 plus the signal. A command that exits 130 by itself, with no signal to the wrapper, still gives a normal exit 130. --measure-rows still stops its rows first. The --inside-cap process is unchanged: its parent wrapper got the signal and ends by it. Fixes #69 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 03022ae commit 3cca79c

3 files changed

Lines changed: 146 additions & 16 deletions

File tree

‎skills/bounding-heavy-commands/SKILL.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru
4444
| `--cpus <n>` | Processor limit, as a whole number. Taken from the record. |
4545
| `--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. |
4646
| `--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. |
47-
| `--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. |
47+
| `--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 that a line of joined calls stops too. Otherwise the exit code is the first exit code of a row that is not 0. |
4848
| `--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. |
4949
| `--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. |
5050

‎skills/bounding-heavy-commands/scripts/bounded_run.py‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66
bounded_run.py --check [--memory SIZE]...
77
88
The exit code is the exit code of the command. Exit code 125 means that this
9-
script failed before the command gave a result.
9+
script failed before the command gave a result. A stop signal to this script
10+
(SIGHUP, SIGINT, SIGQUIT, or SIGTERM) stops the command, and then this script
11+
ends by the same signal, so that a shell stops a line of joined commands. A
12+
caller that reads the exit status reads 128 plus the signal.
1013
1114
A measurement prints one row line on the error stream, in a fixed form:
1215
@@ -67,6 +70,7 @@
6770
import os
6871
import random
6972
import re
73+
import resource
7074
import shutil
7175
import signal
7276
import stat
@@ -108,6 +112,36 @@
108112
STOP_CODES = frozenset(128 + int(signum) for signum in (signal.SIGHUP, signal.SIGINT, signal.SIGQUIT, signal.SIGTERM))
109113

110114

115+
# The first stop signal that reached the wrapper in this run of main.
116+
_stopped_by: List[int] = []
117+
118+
119+
def _note_stop(signum: int) -> None:
120+
if not _stopped_by:
121+
_stopped_by.append(int(signum))
122+
123+
124+
def exit_as(code: int) -> None:
125+
"""Ends the process with the exit code, or, when a stop signal reached the wrapper, by that signal.
126+
127+
A shell stops a line of joined commands only when the command that runs dies from the signal.
128+
A caller that reads the status of a death by signal reads 128 plus the signal.
129+
"""
130+
if _stopped_by:
131+
signum = _stopped_by[0]
132+
sys.stdout.flush()
133+
sys.stderr.flush()
134+
if signum == signal.SIGQUIT:
135+
# The default action of SIGQUIT also writes a core file.
136+
try:
137+
resource.setrlimit(resource.RLIMIT_CORE, (0, resource.getrlimit(resource.RLIMIT_CORE)[1]))
138+
except (ValueError, OSError):
139+
pass
140+
signal.signal(signum, signal.SIG_DFL)
141+
os.kill(os.getpid(), signum)
142+
sys.exit(code)
143+
144+
111145
class WrapperError(Exception):
112146
"""A failure of the wrapper, not of the command."""
113147

@@ -1051,6 +1085,7 @@ def forward(signum: int, frame: object) -> None:
10511085
for signum, handler in previous.items():
10521086
signal.signal(signum, handler)
10531087
if received:
1088+
_note_stop(received[0])
10541089
return 128 + received[0], usage.ru_maxrss
10551090
return process.returncode, usage.ru_maxrss
10561091

@@ -1236,8 +1271,10 @@ def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int:
12361271
code, suggested = bounded_once(row, environ)
12371272
except (KeyboardInterrupt, _Stopped) as stop:
12381273
# A signal while a row runs comes back as its exit code. A signal while it waits in the queue raises.
1274+
signum = stop.signum if isinstance(stop, _Stopped) else int(signal.SIGINT)
1275+
_note_stop(signum)
12391276
log("stopped by a signal while waiting; the rows from --cpus %d are not measured" % cpus)
1240-
return result or 128 + (stop.signum if isinstance(stop, _Stopped) else int(signal.SIGINT))
1277+
return result or 128 + signum
12411278
if code in STOP_CODES:
12421279
log("stopped by a signal; the rows after --cpus %d are not measured" % cpus)
12431280
return result or code
@@ -1443,6 +1480,7 @@ def mib(value: Optional[int]) -> str:
14431480
def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int:
14441481
arguments = list(sys.argv[1:] if argv is None else argv)
14451482
variables = os.environ if environ is None else environ
1483+
del _stopped_by[:]
14461484
try:
14471485
if len(arguments) > 4 and arguments[0] == "--inside-cap" and arguments[3] == "--":
14481486
return inside_cap(arguments[1], arguments[2], arguments[4:])
@@ -1458,6 +1496,7 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st
14581496
try:
14591497
return bounded(options, variables)
14601498
except KeyboardInterrupt:
1499+
_note_stop(signal.SIGINT)
14611500
log("interrupted while waiting")
14621501
return 130
14631502
except WrapperError as error:
@@ -1466,4 +1505,4 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st
14661505

14671506

14681507
if __name__ == "__main__":
1469-
sys.exit(main())
1508+
exit_as(main())

‎skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py‎

Lines changed: 103 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2524,13 +2524,13 @@ def test_a_nested_call_of_a_command_that_does_not_exist_gives_125(self):
25242524
self.assertNotIn("Traceback", errors)
25252525

25262526
def test_a_stop_signal_stops_the_command(self):
2527-
for signum, code in ((signal.SIGTERM, 143), (signal.SIGINT, 130), (signal.SIGQUIT, 131)):
2527+
for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT):
25282528
with self.subTest(signal=signum):
2529-
name = "stopped-%d" % code
2529+
name = "stopped-%d" % signum
25302530
process = self.worker(name, "2G", hold="300")
25312531
line = self.wait_for_event("start", name)
25322532
process.send_signal(signum)
2533-
self.assertEqual(process.wait(timeout=60), code)
2533+
self.assertEqual(process.wait(timeout=60), -signum)
25342534
child = int(line.split()[2])
25352535
deadline = time.time() + 5
25362536
alive = True
@@ -2542,12 +2542,12 @@ def test_a_stop_signal_stops_the_command(self):
25422542
alive = False
25432543
self.assertFalse(alive, "the command still runs")
25442544

2545-
def test_a_hangup_stops_the_command_and_gives_129(self):
2545+
def test_a_hangup_stops_the_command_and_ends_the_wrapper_by_the_hangup(self):
25462546
name = "hangup-129"
25472547
process = self.worker(name, "2G", hold="300")
25482548
line = self.wait_for_event("start", name)
25492549
process.send_signal(signal.SIGHUP)
2550-
self.assertEqual(process.wait(timeout=60), 129)
2550+
self.assertEqual(process.wait(timeout=60), -signal.SIGHUP)
25512551
child = int(line.split()[2])
25522552
deadline = time.time() + 5
25532553
alive = True
@@ -2578,7 +2578,7 @@ def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self):
25782578
self.wait_for_event("signaled", "stubborn", seconds=60.0)
25792579
self.assertIsNone(process.poll())
25802580
process.send_signal(signal.SIGTERM)
2581-
self.assertEqual(process.wait(timeout=60), 143)
2581+
self.assertEqual(process.wait(timeout=60), -signal.SIGTERM)
25822582
child = int(line.split()[2])
25832583
deadline = time.time() + 5
25842584
alive = True
@@ -2836,36 +2836,36 @@ def test_measured_rows_print_their_row_lines_in_order(self):
28362836
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)
28372837
self.assertEqual(rows, ["2", "1"], errors)
28382838

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

28442844
self.wait_for_stderr(waiting, "waiting for")
28452845

28462846
waiting.send_signal(signal.SIGINT)
2847-
self.assertEqual(waiting.wait(timeout=60), 130)
2847+
self.assertEqual(waiting.wait(timeout=60), -signal.SIGINT)
28482848
buffer = self.stderr_of(waiting)
28492849
self.assertNotIn("Traceback", buffer)
28502850
for line in buffer.splitlines():
28512851
self.assertTrue(line.startswith("bounded-run: "), buffer)
28522852

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

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

2862-
def test_an_interrupt_behind_others_in_the_line_gives_130_and_no_traceback(self):
2862+
def test_an_interrupt_behind_others_in_the_line_ends_the_wrapper_by_the_interrupt_with_no_traceback(self):
28632863
line = self.hold_the_line()
28642864
self.addCleanup(os.close, line)
28652865
waiting = self.worker("waiting", "2G", hold="0") # never reached; interrupted while still in the line
28662866
self.wait_for_stderr(waiting, "behind other commands")
28672867
waiting.send_signal(signal.SIGINT)
2868-
self.assertEqual(waiting.wait(timeout=10), 130)
2868+
self.assertEqual(waiting.wait(timeout=10), -signal.SIGINT)
28692869
buffer = self.stderr_of(waiting)
28702870
self.assertNotIn("Traceback", buffer)
28712871
self.assertIn("interrupted while waiting", buffer)
@@ -2952,6 +2952,97 @@ def test_a_fault_of_the_call_gives_125(self):
29522952
self.assertNotIn("check slots=", errors)
29532953

29542954

2955+
# Writes the pid of its parent, the wrapper, to the file in PARENT, then holds until the wrapper stops it.
2956+
PARENT_WRITER = "import os, time; open(os.environ['PARENT'], 'w').write(str(os.getppid())); time.sleep(300)"
2957+
2958+
2959+
@unittest.skipIf(shutil.which("bash") is None, "needs bash")
2960+
class JoinedLineTest(WrapperProcessCase):
2961+
"""Runs the wrapper as the first call of a line of bash that joins its calls with ';'.
2962+
2963+
A terminal sends Ctrl-C to the whole process group of the line. Bash stops the line only when
2964+
the call that runs dies from the signal. A plain sh can end from the signal by itself, so it proves nothing.
2965+
"""
2966+
2967+
def line(self, path, then, options, command, **environ):
2968+
"""Starts `wrapper; <then> "$0"` with $0 set to path, in a new process group."""
2969+
variables = dict(self.environ)
2970+
variables.update(environ)
2971+
process = subprocess.Popen(
2972+
["bash", "-c", '"$@"; ' + then + ' "$0"', path, sys.executable, WRAPPER] + options + ["--"] + command,
2973+
env=variables, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True,
2974+
)
2975+
self.processes.append(process)
2976+
2977+
def kill_group():
2978+
try:
2979+
os.killpg(process.pid, signal.SIGKILL)
2980+
except (ProcessLookupError, PermissionError):
2981+
pass
2982+
self.addCleanup(kill_group)
2983+
return process
2984+
2985+
def wait_for_file(self, path, seconds=60.0):
2986+
deadline = time.time() + seconds
2987+
while time.time() < deadline:
2988+
try:
2989+
text = Path(path).read_text()
2990+
except OSError:
2991+
text = ""
2992+
if text:
2993+
return text
2994+
time.sleep(0.02)
2995+
self.fail("no %s after %s seconds" % (path, seconds))
2996+
2997+
def test_an_interrupt_while_the_command_runs_stops_the_line(self):
2998+
marker = os.path.join(self.base.name, "next-ran")
2999+
process = self.line(marker, "touch", ["--memory", "2G"], [sys.executable, "-c", WORKER, "joined"], HOLD="300")
3000+
self.wait_for_event("start", "joined")
3001+
os.killpg(process.pid, signal.SIGINT)
3002+
self.assertEqual(process.wait(timeout=60), -signal.SIGINT, self.stderr_of(process))
3003+
self.assertFalse(os.path.exists(marker), "the next command of the line ran")
3004+
3005+
def test_an_interrupt_while_the_wrapper_waits_in_the_queue_stops_the_line(self):
3006+
holder = self.worker("holder", "4G", hold="300") # holds every slot until the SIGTERM below
3007+
self.wait_for_event("start", "holder")
3008+
marker = os.path.join(self.base.name, "next-ran")
3009+
process = self.line(marker, "touch", ["--memory", "4G"], [sys.executable, "-c", WORKER, "queued"], HOLD="0")
3010+
self.wait_for_stderr(process, "waiting for")
3011+
os.killpg(process.pid, signal.SIGINT)
3012+
self.assertEqual(process.wait(timeout=60), -signal.SIGINT)
3013+
self.assertIn("interrupted while waiting", self.stderr_of(process))
3014+
self.assertFalse(os.path.exists(marker), "the next command of the line ran")
3015+
holder.send_signal(signal.SIGTERM)
3016+
holder.wait(timeout=60)
3017+
3018+
def test_an_interrupt_while_rows_are_measured_stops_the_rows_and_the_line(self):
3019+
marker = os.path.join(self.base.name, "next-ran")
3020+
process = self.line(marker, "touch", ["--measure-rows", "2,1"], [sys.executable, "-c", WORKER, "rows"], HOLD="300")
3021+
self.wait_for_event("start", "rows")
3022+
os.killpg(process.pid, signal.SIGINT)
3023+
self.assertEqual(process.wait(timeout=60), -signal.SIGINT)
3024+
errors = self.stderr_of(process)
3025+
self.assertIn("stopped by a signal; the rows after --cpus 2 are not measured", errors)
3026+
self.assertFalse(os.path.exists(marker), "the next command of the line ran")
3027+
3028+
def test_a_command_that_exits_130_by_itself_does_not_stop_the_line(self):
3029+
status = os.path.join(self.base.name, "status")
3030+
process = self.line(status, "echo $? >", ["--memory", "2G"], [sys.executable, "-c", "import sys; sys.exit(130)"])
3031+
self.assertEqual(process.wait(timeout=60), 0, self.stderr_of(process))
3032+
self.assertEqual(Path(status).read_text(), "130\n")
3033+
3034+
def test_the_caller_reads_128_plus_the_signal(self):
3035+
for signum in (signal.SIGINT, signal.SIGTERM):
3036+
with self.subTest(signal=signum):
3037+
status = os.path.join(self.base.name, "status-%d" % signum)
3038+
parent = os.path.join(self.base.name, "parent-%d" % signum)
3039+
# Only the wrapper gets the signal, so bash itself does not stop and reads the status.
3040+
process = self.line(status, "echo $? >", ["--memory", "2G"], [sys.executable, "-c", PARENT_WRITER], PARENT=parent)
3041+
os.kill(int(self.wait_for_file(parent)), signum)
3042+
self.assertEqual(process.wait(timeout=60), 0, self.stderr_of(process))
3043+
self.assertEqual(Path(status).read_text(), "%d\n" % (128 + signum))
3044+
3045+
29553046
@unittest.skipUnless(
29563047
bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None,
29573048
"no hard cap on this machine",
@@ -2987,7 +3078,7 @@ def test_a_stop_signal_stops_a_capped_command(self):
29873078
process = self.worker("capped", "1G", hold="300")
29883079
line = self.wait_for_event("start", "capped")
29893080
process.send_signal(signal.SIGTERM)
2990-
self.assertEqual(process.wait(timeout=60), 143)
3081+
self.assertEqual(process.wait(timeout=60), -signal.SIGTERM)
29913082
with self.assertRaises(ProcessLookupError):
29923083
deadline = time.time() + 5
29933084
while time.time() < deadline:

0 commit comments

Comments
 (0)