Skip to content

Commit b89df3b

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 56f1670 commit b89df3b

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

@@ -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

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

12531290

@@ -1445,6 +1482,7 @@ def mib(value: Optional[int]) -> str:
14451482
def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int:
14461483
arguments = list(sys.argv[1:] if argv is None else argv)
14471484
variables = os.environ if environ is None else environ
1485+
del _stopped_by[:]
14481486
try:
14491487
if len(arguments) > 4 and arguments[0] == "--inside-cap" and arguments[3] == "--":
14501488
return inside_cap(arguments[1], arguments[2], arguments[4:])
@@ -1460,10 +1498,12 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st
14601498
try:
14611499
return bounded(options, variables)
14621500
except KeyboardInterrupt:
1501+
_note_stop(signal.SIGINT)
14631502
log("interrupted while waiting")
14641503
return 130
14651504
except _Stopped as stop:
14661505
# The handlers of --measure-rows can fire after its list ends, before they are put back.
1506+
_note_stop(stop.signum)
14671507
log("stopped by a signal")
14681508
return 128 + stop.signum
14691509
except WrapperError as error:
@@ -1472,4 +1512,4 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st
14721512

14731513

14741514
if __name__ == "__main__":
1475-
sys.exit(main())
1515+
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
@@ -2529,13 +2529,13 @@ def test_a_nested_call_of_a_command_that_does_not_exist_gives_125(self):
25292529
self.assertNotIn("Traceback", errors)
25302530

25312531
def test_a_stop_signal_stops_the_command(self):
2532-
for signum, code in ((signal.SIGTERM, 143), (signal.SIGINT, 130), (signal.SIGQUIT, 131)):
2532+
for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGQUIT):
25332533
with self.subTest(signal=signum):
2534-
name = "stopped-%d" % code
2534+
name = "stopped-%d" % signum
25352535
process = self.worker(name, "2G", hold="300")
25362536
line = self.wait_for_event("start", name)
25372537
process.send_signal(signum)
2538-
self.assertEqual(process.wait(timeout=60), code)
2538+
self.assertEqual(process.wait(timeout=60), -signum)
25392539
child = int(line.split()[2])
25402540
deadline = time.time() + 5
25412541
alive = True
@@ -2547,12 +2547,12 @@ def test_a_stop_signal_stops_the_command(self):
25472547
alive = False
25482548
self.assertFalse(alive, "the command still runs")
25492549

2550-
def test_a_hangup_stops_the_command_and_gives_129(self):
2550+
def test_a_hangup_stops_the_command_and_ends_the_wrapper_by_the_hangup(self):
25512551
name = "hangup-129"
25522552
process = self.worker(name, "2G", hold="300")
25532553
line = self.wait_for_event("start", name)
25542554
process.send_signal(signal.SIGHUP)
2555-
self.assertEqual(process.wait(timeout=60), 129)
2555+
self.assertEqual(process.wait(timeout=60), -signal.SIGHUP)
25562556
child = int(line.split()[2])
25572557
deadline = time.time() + 5
25582558
alive = True
@@ -2583,7 +2583,7 @@ def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self):
25832583
self.wait_for_event("signaled", "stubborn", seconds=60.0)
25842584
self.assertIsNone(process.poll())
25852585
process.send_signal(signal.SIGTERM)
2586-
self.assertEqual(process.wait(timeout=60), 143)
2586+
self.assertEqual(process.wait(timeout=60), -signal.SIGTERM)
25872587
child = int(line.split()[2])
25882588
deadline = time.time() + 5
25892589
alive = True
@@ -2841,36 +2841,36 @@ def test_measured_rows_print_their_row_lines_in_order(self):
28412841
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)
28422842
self.assertEqual(rows, ["2", "1"], errors)
28432843

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

28492849
self.wait_for_stderr(waiting, "waiting for")
28502850

28512851
waiting.send_signal(signal.SIGINT)
2852-
self.assertEqual(waiting.wait(timeout=60), 130)
2852+
self.assertEqual(waiting.wait(timeout=60), -signal.SIGINT)
28532853
buffer = self.stderr_of(waiting)
28542854
self.assertNotIn("Traceback", buffer)
28552855
for line in buffer.splitlines():
28562856
self.assertTrue(line.startswith("bounded-run: "), buffer)
28572857

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

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

2867-
def test_an_interrupt_behind_others_in_the_line_gives_130_and_no_traceback(self):
2867+
def test_an_interrupt_behind_others_in_the_line_ends_the_wrapper_by_the_interrupt_with_no_traceback(self):
28682868
line = self.hold_the_line()
28692869
self.addCleanup(os.close, line)
28702870
waiting = self.worker("waiting", "2G", hold="0") # never reached; interrupted while still in the line
28712871
self.wait_for_stderr(waiting, "behind other commands")
28722872
waiting.send_signal(signal.SIGINT)
2873-
self.assertEqual(waiting.wait(timeout=10), 130)
2873+
self.assertEqual(waiting.wait(timeout=10), -signal.SIGINT)
28742874
buffer = self.stderr_of(waiting)
28752875
self.assertNotIn("Traceback", buffer)
28762876
self.assertIn("interrupted while waiting", buffer)
@@ -2957,6 +2957,97 @@ def test_a_fault_of_the_call_gives_125(self):
29572957
self.assertNotIn("check slots=", errors)
29582958

29592959

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

0 commit comments

Comments
 (0)