Skip to content

Commit c161cb0

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 1f53642 commit c161cb0

3 files changed

Lines changed: 147 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: 43 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

@@ -1054,6 +1088,7 @@ def forward(signum: int, frame: object) -> None:
10541088
for signum, handler in previous.items():
10551089
signal.signal(signum, handler)
10561090
if received:
1091+
_note_stop(received[0])
10571092
return 128 + received[0], usage.ru_maxrss
10581093
return process.returncode, usage.ru_maxrss
10591094

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

12561293

@@ -1449,6 +1486,7 @@ def mib(value: Optional[int]) -> str:
14491486
def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int:
14501487
arguments = list(sys.argv[1:] if argv is None else argv)
14511488
variables = os.environ if environ is None else environ
1489+
del _stopped_by[:]
14521490
try:
14531491
if len(arguments) > 4 and arguments[0] == "--inside-cap" and arguments[3] == "--":
14541492
return inside_cap(arguments[1], arguments[2], arguments[4:])
@@ -1464,10 +1502,12 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st
14641502
try:
14651503
return bounded(options, variables)
14661504
except KeyboardInterrupt:
1505+
_note_stop(signal.SIGINT)
14671506
log("interrupted while waiting")
14681507
return 130
14691508
except _Stopped as stop:
14701509
# The handlers of --measure-rows can fire after its list ends, before they are put back.
1510+
_note_stop(stop.signum)
14711511
log("stopped by a signal")
14721512
return 128 + stop.signum
14731513
except WrapperError as error:
@@ -1476,4 +1516,4 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st
14761516

14771517

14781518
if __name__ == "__main__":
1479-
sys.exit(main())
1519+
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
@@ -2565,13 +2565,13 @@ def test_a_nested_call_of_a_command_that_does_not_exist_gives_125(self):
25652565
self.assertNotIn("Traceback", errors)
25662566

25672567
def test_a_stop_signal_stops_the_command(self):
2568-
for signum, code in ((signal.SIGTERM, 143), (signal.SIGINT, 130), (signal.SIGQUIT, 131)):
2568+
for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT):
25692569
with self.subTest(signal=signum):
2570-
name = "stopped-%d" % code
2570+
name = "stopped-%d" % signum
25712571
process = self.worker(name, "2G", hold="300")
25722572
line = self.wait_for_event("start", name)
25732573
process.send_signal(signum)
2574-
self.assertEqual(process.wait(timeout=60), code)
2574+
self.assertEqual(process.wait(timeout=60), -signum)
25752575
child = int(line.split()[2])
25762576
deadline = time.time() + 5
25772577
alive = True
@@ -2583,12 +2583,12 @@ def test_a_stop_signal_stops_the_command(self):
25832583
alive = False
25842584
self.assertFalse(alive, "the command still runs")
25852585

2586-
def test_a_hangup_stops_the_command_and_gives_129(self):
2586+
def test_a_hangup_stops_the_command_and_ends_the_wrapper_by_the_hangup(self):
25872587
name = "hangup-129"
25882588
process = self.worker(name, "2G", hold="300")
25892589
line = self.wait_for_event("start", name)
25902590
process.send_signal(signal.SIGHUP)
2591-
self.assertEqual(process.wait(timeout=60), 129)
2591+
self.assertEqual(process.wait(timeout=60), -signal.SIGHUP)
25922592
child = int(line.split()[2])
25932593
deadline = time.time() + 5
25942594
alive = True
@@ -2619,7 +2619,7 @@ def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self):
26192619
self.wait_for_event("signaled", "stubborn", seconds=60.0)
26202620
self.assertIsNone(process.poll())
26212621
process.send_signal(signal.SIGTERM)
2622-
self.assertEqual(process.wait(timeout=60), 143)
2622+
self.assertEqual(process.wait(timeout=60), -signal.SIGTERM)
26232623
child = int(line.split()[2])
26242624
deadline = time.time() + 5
26252625
alive = True
@@ -2877,36 +2877,36 @@ def test_measured_rows_print_their_row_lines_in_order(self):
28772877
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)
28782878
self.assertEqual(rows, ["2", "1"], errors)
28792879

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

28852885
self.wait_for_stderr(waiting, "waiting for")
28862886

28872887
waiting.send_signal(signal.SIGINT)
2888-
self.assertEqual(waiting.wait(timeout=60), 130)
2888+
self.assertEqual(waiting.wait(timeout=60), -signal.SIGINT)
28892889
buffer = self.stderr_of(waiting)
28902890
self.assertNotIn("Traceback", buffer)
28912891
for line in buffer.splitlines():
28922892
self.assertTrue(line.startswith("bounded-run: "), buffer)
28932893

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

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

2903-
def test_an_interrupt_behind_others_in_the_line_gives_130_and_no_traceback(self):
2903+
def test_an_interrupt_behind_others_in_the_line_ends_the_wrapper_by_the_interrupt_with_no_traceback(self):
29042904
line = self.hold_the_line()
29052905
self.addCleanup(os.close, line)
29062906
waiting = self.worker("waiting", "2G", hold="0") # never reached; interrupted while still in the line
29072907
self.wait_for_stderr(waiting, "behind other commands")
29082908
waiting.send_signal(signal.SIGINT)
2909-
self.assertEqual(waiting.wait(timeout=10), 130)
2909+
self.assertEqual(waiting.wait(timeout=10), -signal.SIGINT)
29102910
buffer = self.stderr_of(waiting)
29112911
self.assertNotIn("Traceback", buffer)
29122912
self.assertIn("interrupted while waiting", buffer)
@@ -2993,6 +2993,97 @@ def test_a_fault_of_the_call_gives_125(self):
29932993
self.assertNotIn("check slots=", errors)
29942994

29952995

2996+
# Writes the pid of its parent, the wrapper, to the file in PARENT, then holds until the wrapper stops it.
2997+
PARENT_WRITER = "import os, time; open(os.environ['PARENT'], 'w').write(str(os.getppid())); time.sleep(300)"
2998+
2999+
3000+
@unittest.skipIf(shutil.which("bash") is None, "needs bash")
3001+
class JoinedLineTest(WrapperProcessCase):
3002+
"""Runs the wrapper as the first call of a line of bash that joins its calls with ';'.
3003+
3004+
A terminal sends Ctrl-C to the whole process group of the line. Bash stops the line only when
3005+
the call that runs dies from the signal. A plain sh can end from the signal by itself, so it proves nothing.
3006+
"""
3007+
3008+
def line(self, path, then, options, command, **environ):
3009+
"""Starts `wrapper; <then> "$0"` with $0 set to path, in a new process group."""
3010+
variables = dict(self.environ)
3011+
variables.update(environ)
3012+
process = subprocess.Popen(
3013+
["bash", "-c", '"$@"; ' + then + ' "$0"', path, sys.executable, WRAPPER] + options + ["--"] + command,
3014+
env=variables, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, start_new_session=True,
3015+
)
3016+
self.processes.append(process)
3017+
3018+
def kill_group():
3019+
try:
3020+
os.killpg(process.pid, signal.SIGKILL)
3021+
except (ProcessLookupError, PermissionError):
3022+
pass
3023+
self.addCleanup(kill_group)
3024+
return process
3025+
3026+
def wait_for_file(self, path, seconds=60.0):
3027+
deadline = time.time() + seconds
3028+
while time.time() < deadline:
3029+
try:
3030+
text = Path(path).read_text()
3031+
except OSError:
3032+
text = ""
3033+
if text:
3034+
return text
3035+
time.sleep(0.02)
3036+
self.fail("no %s after %s seconds" % (path, seconds))
3037+
3038+
def test_an_interrupt_while_the_command_runs_stops_the_line(self):
3039+
marker = os.path.join(self.base.name, "next-ran")
3040+
process = self.line(marker, "touch", ["--memory", "2G"], [sys.executable, "-c", WORKER, "joined"], HOLD="300")
3041+
self.wait_for_event("start", "joined")
3042+
os.killpg(process.pid, signal.SIGINT)
3043+
self.assertEqual(process.wait(timeout=60), -signal.SIGINT, self.stderr_of(process))
3044+
self.assertFalse(os.path.exists(marker), "the next command of the line ran")
3045+
3046+
def test_an_interrupt_while_the_wrapper_waits_in_the_queue_stops_the_line(self):
3047+
holder = self.worker("holder", "4G", hold="300") # holds every slot until the SIGTERM below
3048+
self.wait_for_event("start", "holder")
3049+
marker = os.path.join(self.base.name, "next-ran")
3050+
process = self.line(marker, "touch", ["--memory", "4G"], [sys.executable, "-c", WORKER, "queued"], HOLD="0")
3051+
self.wait_for_stderr(process, "waiting for")
3052+
os.killpg(process.pid, signal.SIGINT)
3053+
self.assertEqual(process.wait(timeout=60), -signal.SIGINT)
3054+
self.assertIn("interrupted while waiting", self.stderr_of(process))
3055+
self.assertFalse(os.path.exists(marker), "the next command of the line ran")
3056+
holder.send_signal(signal.SIGTERM)
3057+
holder.wait(timeout=60)
3058+
3059+
def test_an_interrupt_while_rows_are_measured_stops_the_rows_and_the_line(self):
3060+
marker = os.path.join(self.base.name, "next-ran")
3061+
process = self.line(marker, "touch", ["--measure-rows", "2,1"], [sys.executable, "-c", WORKER, "rows"], HOLD="300")
3062+
self.wait_for_event("start", "rows")
3063+
os.killpg(process.pid, signal.SIGINT)
3064+
self.assertEqual(process.wait(timeout=60), -signal.SIGINT)
3065+
errors = self.stderr_of(process)
3066+
self.assertIn("stopped by a signal; the rows after --cpus 2 are not measured", errors)
3067+
self.assertFalse(os.path.exists(marker), "the next command of the line ran")
3068+
3069+
def test_a_command_that_exits_130_by_itself_does_not_stop_the_line(self):
3070+
status = os.path.join(self.base.name, "status")
3071+
process = self.line(status, "echo $? >", ["--memory", "2G"], [sys.executable, "-c", "import sys; sys.exit(130)"])
3072+
self.assertEqual(process.wait(timeout=60), 0, self.stderr_of(process))
3073+
self.assertEqual(Path(status).read_text(), "130\n")
3074+
3075+
def test_the_caller_reads_128_plus_the_signal(self):
3076+
for signum in (signal.SIGINT, signal.SIGTERM):
3077+
with self.subTest(signal=signum):
3078+
status = os.path.join(self.base.name, "status-%d" % signum)
3079+
parent = os.path.join(self.base.name, "parent-%d" % signum)
3080+
# Only the wrapper gets the signal, so bash itself does not stop and reads the status.
3081+
process = self.line(status, "echo $? >", ["--memory", "2G"], [sys.executable, "-c", PARENT_WRITER], PARENT=parent)
3082+
os.kill(int(self.wait_for_file(parent)), signum)
3083+
self.assertEqual(process.wait(timeout=60), 0, self.stderr_of(process))
3084+
self.assertEqual(Path(status).read_text(), "%d\n" % (128 + signum))
3085+
3086+
29963087
@unittest.skipUnless(
29973088
bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None,
29983089
"no hard cap on this machine",
@@ -3028,7 +3119,7 @@ def test_a_stop_signal_stops_a_capped_command(self):
30283119
process = self.worker("capped", "1G", hold="300")
30293120
line = self.wait_for_event("start", "capped")
30303121
process.send_signal(signal.SIGTERM)
3031-
self.assertEqual(process.wait(timeout=60), 143)
3122+
self.assertEqual(process.wait(timeout=60), -signal.SIGTERM)
30323123
with self.assertRaises(ProcessLookupError):
30333124
deadline = time.time() + 5
30343125
while time.time() < deadline:

0 commit comments

Comments
 (0)