Skip to content

Commit e4baec9

Browse files
sourcehawkclaude
andauthored
fix(skills/bounding-heavy-commands): stop a joined line of bounded commands on one Ctrl-C (#71)
* 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> * docs(skills/bounding-heavy-commands): say that a joined line stops on a Ctrl-C, not on a signal to the wrapper alone The shell stops a line of joined commands when it gets the interrupt too, as with a Ctrl-C at the terminal. A signal sent to the wrapper alone ends the wrapper by that signal, and the shell runs the next command of the line. The usage text and the skill said that each stop signal to the wrapper stops the line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(skills/bounding-heavy-commands): say in exit_as that the shell must get the signal too The docstring said that a shell stops a joined line when the running command dies from a signal. The shell stops it only when it got the signal as well, as with a Ctrl-C at the terminal; the caller test shows bash going on when only the wrapper is signalled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(skills/bounding-heavy-commands): stop a joined line on Ctrl-C after a failed row No process test covered the case where a row fails and a later row gets the interrupt. The new test runs --measure-rows in a bash line, lets the first row exit 3, interrupts the second, and checks that the wrapper dies from SIGINT and that the next command of the line does not run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 48fd634 commit e4baec9

3 files changed

Lines changed: 161 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 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. |
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: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@
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 a Ctrl-C at the terminal, which reaches the shell
12+
too, stops a line of joined commands; a signal sent to this script alone does
13+
not stop the shell. A caller that reads the exit status reads 128 plus the
14+
signal.
1015
1116
A measurement prints one row line on the error stream, in a fixed form:
1217
@@ -67,6 +72,7 @@
6772
import os
6873
import random
6974
import re
75+
import resource
7076
import shutil
7177
import signal
7278
import stat
@@ -108,6 +114,37 @@
108114
STOP_CODES = frozenset(128 + int(signum) for signum in (signal.SIGHUP, signal.SIGINT, signal.SIGQUIT, signal.SIGTERM))
109115

110116

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

@@ -1054,6 +1091,7 @@ def forward(signum: int, frame: object) -> None:
10541091
for signum, handler in previous.items():
10551092
signal.signal(signum, handler)
10561093
if received:
1094+
_note_stop(received[0])
10571095
return 128 + received[0], usage.ru_maxrss
10581096
return process.returncode, usage.ru_maxrss
10591097

@@ -1249,8 +1287,10 @@ def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int:
12491287
result = result or code
12501288
except (KeyboardInterrupt, _Stopped) as stop:
12511289
# A signal while a row runs comes back as its exit code. A signal at any other time in the list raises.
1290+
signum = stop.signum if isinstance(stop, _Stopped) else int(signal.SIGINT)
1291+
_note_stop(signum)
12521292
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))
1293+
return result or 128 + signum
12541294
return result
12551295

12561296

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

14771520

14781521
if __name__ == "__main__":
1479-
sys.exit(main())
1522+
exit_as(main())

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

Lines changed: 114 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,108 @@ 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_an_interrupt_after_a_failed_row_still_stops_the_line(self):
3070+
marker = os.path.join(self.base.name, "next-ran")
3071+
fail_then_hold = "import os, sys\nif os.environ['BOUNDED_RUN_CPUS'] == '2':\n sys.exit(3)\n" + WORKER
3072+
process = self.line(marker, "touch", ["--measure-rows", "2,1"], [sys.executable, "-c", fail_then_hold, "rows"], HOLD="300")
3073+
self.wait_for_event("start", "rows")
3074+
os.killpg(process.pid, signal.SIGINT)
3075+
self.assertEqual(process.wait(timeout=60), -signal.SIGINT)
3076+
errors = self.stderr_of(process)
3077+
self.assertRegex(errors, r"row label=- cpus=2 .* exit=3")
3078+
self.assertFalse(os.path.exists(marker), "the next command of the line ran")
3079+
3080+
def test_a_command_that_exits_130_by_itself_does_not_stop_the_line(self):
3081+
status = os.path.join(self.base.name, "status")
3082+
process = self.line(status, "echo $? >", ["--memory", "2G"], [sys.executable, "-c", "import sys; sys.exit(130)"])
3083+
self.assertEqual(process.wait(timeout=60), 0, self.stderr_of(process))
3084+
self.assertEqual(Path(status).read_text(), "130\n")
3085+
3086+
def test_the_caller_reads_128_plus_the_signal(self):
3087+
for signum in (signal.SIGINT, signal.SIGTERM):
3088+
with self.subTest(signal=signum):
3089+
status = os.path.join(self.base.name, "status-%d" % signum)
3090+
parent = os.path.join(self.base.name, "parent-%d" % signum)
3091+
# Only the wrapper gets the signal, so bash itself does not stop and reads the status.
3092+
process = self.line(status, "echo $? >", ["--memory", "2G"], [sys.executable, "-c", PARENT_WRITER], PARENT=parent)
3093+
os.kill(int(self.wait_for_file(parent)), signum)
3094+
self.assertEqual(process.wait(timeout=60), 0, self.stderr_of(process))
3095+
self.assertEqual(Path(status).read_text(), "%d\n" % (128 + signum))
3096+
3097+
29963098
@unittest.skipUnless(
29973099
bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None,
29983100
"no hard cap on this machine",
@@ -3028,7 +3130,7 @@ def test_a_stop_signal_stops_a_capped_command(self):
30283130
process = self.worker("capped", "1G", hold="300")
30293131
line = self.wait_for_event("start", "capped")
30303132
process.send_signal(signal.SIGTERM)
3031-
self.assertEqual(process.wait(timeout=60), 143)
3133+
self.assertEqual(process.wait(timeout=60), -signal.SIGTERM)
30323134
with self.assertRaises(ProcessLookupError):
30333135
deadline = time.time() + 5
30343136
while time.time() < deadline:

0 commit comments

Comments
 (0)