From 4f583fe3102a3145c6dc6d3decd27764486be84c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:37:51 +0100 Subject: [PATCH 01/14] feat(skills/bounding-heavy-commands): measure every heavy command of a project in one run that the user starts A project with no record got its measurements one command at a time, when an agent first needed each command. An agent asked to fix a bug and run the unit tests measured only the unit tests, at a --cpus that it picked, asked the user nothing, and left the other heavy commands without an entry. Each of those later first measurements holds the whole queue in the middle of someone's work, and the rows of the record come out at whichever --cpus each session picked. When the record does not exist, discovery now covers every heavy command of the project. The agent writes one command line that measures each command at all, half, and a quarter of the machine's processors, and asks the user to run it when the machine is quiet, or to tell the agent to run it. It then reads the row lines into the record, and writes a row only from a run that did its full work. If the user declines, the agent measures the command that it needs, as before. A command that the project adds later is still measured when an agent first needs it. The wrapper gets two options for this. --measure-rows N,N,... measures the command at each --cpus of the list, the largest first, and gives each smaller row the suggested budget of the row before it as its --memory, so that only the first row of a command holds the whole queue. --label names the command in a new fixed-form row line that each measurement prints, so that the agent reads the output without guessing. Closes #56 Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 41 ++++++- .../scripts/bounded_run.py | 69 ++++++++++- .../scripts/tests/test_bounded_run.py | 113 ++++++++++++++++++ 3 files changed, 214 insertions(+), 9 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index b3f934a..1e83bc7 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -33,7 +33,8 @@ A server that a heavy command talks to is a part of that command: a development ## The wrapper ``` -python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... [--measure] -- +python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... [--measure] [--label ] -- +python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure-rows ,,... [--exclusive ]... [--label ] -- ``` | Option | Meaning | @@ -42,8 +43,18 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--cpus ` | Processor limit, as a whole number. Taken from the record. | | `--exclusive ` | 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 alone in the queue. | +| `--measure-rows ,,...` | Measure the command one time at each `--cpus` of the list, one after the other, the largest first. The largest runs with no `--memory`, so it runs alone in the queue. 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. | +| `--label ` | A name for the row lines of a measurement, such as `unit-tests`. Use letters, digits, `.`, `_`, and `-`. It changes nothing else. | -The wrapper does four things in sequence. It waits for its turn in the queue. It waits until the memory of its budget is free. It runs the command. It prints the budget and the measured peak on the error stream. For the wait, the free memory is the memory that the machine has free now, less the part of their budgets that the running bounded commands do not use yet, less a headroom for the programs outside the queue. The headroom is a tenth of the memory of the machine, and at least 1 GiB. The budget and the headroom together never need more than the memory of the queue, so a budget of the whole queue does not wait for a headroom. The wait has no time limit: the command does not start before its memory is free, and the wrapper prints a line at intervals while it waits. Each line that the wrapper prints starts with `bounded-run:`. Its exit code is the command's exit code. Exit code 125, with a `bounded-run:` line that names a fault and with no line for the budget and the peak, means that the wrapper itself failed (see §When the wrapper cannot run). +The wrapper does four things in sequence. It waits for its turn in the queue. It waits until the memory of its budget is free. It runs the command. It prints the budget and the measured peak on the error stream. For the wait, the free memory is the memory that the machine has free now, less the part of their budgets that the running bounded commands do not use yet, less a headroom for the programs outside the queue. The headroom is a tenth of the memory of the machine, and at least 1 GiB. The budget and the headroom together never need more than the memory of the queue, so a budget of the whole queue does not wait for a headroom. The wait has no time limit: the command does not start before its memory is free, and the wrapper prints a line at intervals while it waits. Each line that the wrapper prints starts with `bounded-run:`. A measurement also prints one row line, in a fixed form: + +``` +bounded-run: row label= cpus= budget=M peak=M exact= exit= +``` + +`budget` is the suggested budget. `exact=no` means that the peak was sampled, so the margin is larger. A `-` in place of the label or the `--cpus` means that the call did not give the option. The wrapper cannot know if the command did its full work: the exit code and the output of the command tell you (§Discovery, step 5). + +The exit code of the wrapper is the command's exit code. Exit code 125, with a `bounded-run:` line that names a fault and with no line for the budget and the peak, means that the wrapper itself failed (see §When the wrapper cannot run). The wrapper sets `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB` in the environment of the command, from `--cpus` and `--memory`. A recorded command line can read them and hand them to the toolchain's own parallelism and memory settings. You do not set them: you change them with the two options. @@ -78,7 +89,7 @@ Then, before each heavy command, use the first case that applies: 2. **The record exists and has a complete entry for the command.** Check that the plain command still exists in the project, and that the file of the wrapper in the command line still exists. When the file of the wrapper is not there, an update of the plugin moved it. The command line in §The wrapper shows the correct path: put it into each command line of the record. Then use the bounded command line with the default row. 3. **The record exists, and the command is not in it, its entry is incomplete, or its entry is no longer correct.** Run the discovery for that command and correct the entry. When the command line changes in more than the values of the wrapper's `--memory` and `--cpus`, its rows measured a different command: delete them, and measure the new command line. Remove an entry whose command the project no longer has. 4. **Your harness has no project memory, or it is off.** You cannot save a record, so do not try. Run the discovery in this session, keep the result in your context, and use the wrapper's default budget for anything you could not measure. -5. **Project memory is on, and the record does not exist.** Run the discovery for the commands that you are about to run, and save the record. The measured runs of the discovery are your first heavy runs. A heavy command of the project that you do not run now gets its entry when an agent first needs it. +5. **Project memory is on, and the record does not exist.** Run the discovery for every heavy command of the project, not only for the command that you are about to run, and measure them all with one command line that the user runs (§Measure the whole project). While you wait for the answer of the user and for the line, run a heavy command that you need through the wrapper, as its bounded command line at `--cpus` of half the machine's processors, with no `--memory` option. A budget is a measurement, not a preference. Change a row only when the wrapper's output at the `--cpus` of that row shows that the peak moved, and write the new peak and date in it. @@ -88,7 +99,7 @@ A part of a recorded command (one test file, one target) uses the bounded comman ## Discovery -1. Find how the project runs its tests, its linter, its build, and its type check. Read the project's instruction files, its build configuration, and its CI configuration. +1. Find how the project runs its tests, its linter, its build, and its type check, and each other heavy command (§When to invoke): code generators, installs, formatters over the whole tree. Read the project's instruction files, its build configuration, and its CI configuration. 2. Bound the command before you measure it. Do not measure a command until this step is done. Find what makes the toolchain run fewer things at once: a flag or a variable for the number of jobs, workers, processes, or threads. Find a memory setting too, but only one that covers the whole command. A memory setting for one process does not cover the processes that it starts. Most tools that start many processes have no memory setting for the whole command, so the number of things that run at once is the main way to lower the peak. Write the command line so that it takes the setting from `BOUNDED_RUN_CPUS` or `BOUNDED_RUN_MEMORY_MIB`, and record that setting as the `self-bound` of the entry. When the tool has no such setting, record `self-bound: none: `, so that a missing bound is a decision and not an omission. The wrapper sets the two variables for the command only. Your own shell does not have them. Put the command into an inner shell, in single quotes, so that your own shell does not replace the variable with an empty value before the wrapper starts: ``` @@ -109,6 +120,26 @@ A part of a recorded command (one test file, one target) uses the bounded comman The measured run is a real run of the command. Its result counts, also when the run stopped early, so do not run the command a second time to get the result. +### Measure the whole project + +When the record does not exist (§The record, case 5), do steps 1 to 3 for every heavy command of the project. Then measure them all in one run, in place of steps 4 and 5. Do not measure only the command that you need now. A command that gets its entry later gets its first measurement in the middle of someone's work, and that measurement holds the whole queue while other sessions wait. + +1. Choose the rows. Measure each command at three `--cpus`: all the machine's processors, half of them, and a quarter of them. Round each one down, use at least 1, and drop a value that is the same as another. A command with `self-bound: none` gets the row at half only: nothing in it reads its `--cpus`, so each row would measure the same command. +2. Write one command line. For each command, write one call of the wrapper with `--measure-rows ,,`, a `--label` that names the command, the `--exclusive` options of the command, and its bounded command line. Join the calls with `;`, so that a measurement that fails does not stop the others. Write the path of the wrapper in full, so that the line runs in any shell. Run it from the root of the project: + + ``` + python3 "" --measure-rows 16,8,4 --label unit-tests -- ; python3 "" --measure-rows 16,8,4 --label lint -- + ``` + +3. Ask the user to run the line when the machine is quiet. Do not run it yourself unless the user asks you to. Your message names the commands and the rows that the line measures. It says that the line can take a long time, and that the first row of each command holds the whole queue, so that the heavy commands of the other sessions wait while it runs. It says how to run the line: type `! ` in this session, or run it in a terminal at the root of the project, or tell you to run it. +4. Act on the answer: + - **The user ran the line.** Read its output into the record (step 5 of this list). + - **The user tells you to run it.** Run it in the background, with no short timeout around it. Continue with work that runs no heavy command. A heavy command that you need before the line ends runs through the wrapper with no `--memory` option. When the line ends, read its output into the record (step 5 of this list). + - **The user declines.** Run steps 4 to 6 of the list above for the command that you are about to run, and save the record. Each other command gets its entry when an agent first needs it (§The record, case 3). +5. Read the row lines of the output. Each row line of a run that did its full work gives the row at its `cpus`, in the entry of its `label`: its `budget`, its `peak`, and the date. A run did its full work when it exits 0, or when it ran all of its work and reported failures, such as a suite that ran each test and reported the failures. Step 5 of the list above names the runs that stopped early. A row line of such a run gives no row: write nothing for it. The row at half the processors is the default row. When it has no row, the default row is the row with the `--cpus` nearest to half. An entry that has no row is incomplete (§The record), and an agent measures it when it first needs it. Save the record. + +A command that the project adds later gets its entry when an agent first needs it (§The record, case 3). + ## Rules for the wait A long wait means that the machine is full. It is never a fault to repair: the queue has no state that can go wrong between runs, and an agent that repairs it breaks it. Waiting commands take turns in a line. Only the command at the head of the line tries for slots, so the smaller commands behind it do not take the slots that it waits for. The line has no fixed order, and a head that sees no slot come free for 5 minutes lets the commands behind it try first. So a small command can wait behind a large one, also when a slot is free. Unless an instruction says otherwise (see the next section), the only correct moves are to keep the run in the queue and to tell the user that the machine is full and the command is queued. A subagent tells its dispatcher in its report. @@ -176,6 +207,8 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "I measured the plain command, the peak is real" | It is the real peak of a command that nothing limits. Bound the command first, then measure the bounded command line at the `--cpus` that you record. | | "The new measurement at a different `--cpus` replaces the old entry" | A different `--cpus` is a different command. Add a row and keep the others. Only a measurement at the same `--cpus` replaces a row. | | "A smaller `--cpus` is a lower budget by another name" | A lower `--memory` on the same command is a guess. A row at a smaller `--cpus` is a smaller command with a measured budget. Use it to start sooner. | +| "I only need the unit tests now, the others get entries when an agent needs them" | Each later first measurement holds the whole queue in the middle of someone's work. When the record does not exist, measure every heavy command of the project with one command line. | +| "I'll run the measurements myself now, it saves the user a step" | The line holds the whole queue for a long time. The user chooses when the machine can give it that time. Ask, and run it only when the user tells you to. | | "Four subagents is too many for this machine, I'll dispatch two" | The queue limits the commands. Fewer subagents only makes the work slower. | | "Project memory is off, so there is no record to keep" | Discover in this session and keep the result in context. The rule does not depend on the memory. | | "The wrapper cannot run here, so none of this applies" | The fallback applies: one heavy command at a time, toolchain parallelism at half or less, and say so. | diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index b75b7f9..e466a78 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1,11 +1,23 @@ #!/usr/bin/env python3 """Runs a command under a memory reservation that every project of the user shares. -Usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] -- COMMAND... +Usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] [--label NAME] -- COMMAND... + bounded_run.py --measure-rows N,N,... [--memory SIZE] [--exclusive NAME]... [--label NAME] -- COMMAND... The exit code is the exit code of the command. Exit code 125 means that this script failed before the command gave a result. +A measurement prints one row line on the error stream, in a fixed form: + + bounded-run: row label=NAME cpus=N budget=MIBM peak=MIBM exact=yes|no exit=CODE + +budget is the suggested budget. A '-' stands for an option that the call did +not give. --measure-rows measures the command at each processor limit of the +list, the largest first. The largest runs with --memory, or alone in the queue. +Each smaller one runs with the suggested budget of the one before it, or with +the budget of the one before it when that run did not exit 0. The exit code +is the first exit code that is not 0. + A normal call sets none of the environment variables below. A person can set the tuning values in the profile of the shell, so that every session on the machine uses the same values. The tests of this script set the @@ -68,7 +80,12 @@ MARGIN_APPROXIMATE = 0.5 BUDGET_STEP_MIB = 256 PR_SET_PDEATHSIG = 1 -USAGE = "usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] -- COMMAND..." +USAGE = ( + "usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] [--label NAME] -- COMMAND...\n" + " bounded_run.py --measure-rows N,N,... [--memory SIZE] [--exclusive NAME]... [--label NAME] -- COMMAND..." +) +# The exit codes of a run that a stop signal to the wrapper ended: 128 plus SIGHUP, SIGINT, SIGQUIT, or SIGTERM. +STOP_CODES = frozenset(128 + int(signum) for signum in (signal.SIGHUP, signal.SIGINT, signal.SIGQUIT, signal.SIGTERM)) class WrapperError(Exception): @@ -939,6 +956,8 @@ def __init__(self) -> None: self.cpus: Optional[int] = None self.exclusive: List[str] = [] self.measure = False + self.rows: List[int] = [] + self.label: Optional[str] = None self.command: List[str] = [] @@ -957,7 +976,7 @@ def parse_arguments(argv: Sequence[str]) -> Options: if flag == "--measure": options.measure = True continue - if flag not in ("--memory", "--cpus", "--exclusive"): + if flag not in ("--memory", "--cpus", "--exclusive", "--measure-rows", "--label"): raise WrapperError("cannot read the option '%s'\n%s" % (flag, USAGE)) if not flags: raise WrapperError("the option '%s' needs a value\n%s" % (flag, USAGE)) @@ -967,14 +986,51 @@ def parse_arguments(argv: Sequence[str]) -> Options: elif flag == "--exclusive": if value not in options.exclusive: options.exclusive.append(value) + elif flag == "--label": + # The row line separates its fields with spaces and marks a missing label with '-'. + if re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*$", value) is None: + raise WrapperError("cannot use the label '%s'; use letters, digits, '.', '_' and '-', and start with a letter or a digit" % value) + options.label = value + elif flag == "--measure-rows": + parts = value.split(",") + if not all(part.isdigit() and int(part) >= 1 for part in parts): + raise WrapperError("cannot read --measure-rows '%s'; use whole numbers of 1 or more, such as 16,8,4" % value) + options.rows = sorted(set(int(part) for part in parts), reverse=True) + options.measure = True else: if not value.isdigit() or int(value) < 1: raise WrapperError("cannot read --cpus '%s'; use a whole number of 1 or more" % value) options.cpus = int(value) + if options.rows and options.cpus is not None: + raise WrapperError("use --measure-rows or --cpus, not both\n" + USAGE) + if options.label is not None and not options.measure: + raise WrapperError("--label needs --measure or --measure-rows\n" + USAGE) return options def bounded(options: Options, environ: Mapping[str, str]) -> int: + if not options.rows: + return bounded_once(options, environ)[0] + memory = options.memory + result = 0 + for cpus in options.rows: + row = Options() + row.memory, row.cpus, row.exclusive, row.measure, row.label, row.command = ( + memory, cpus, options.exclusive, True, options.label, options.command) + code, suggested = bounded_once(row, environ) + if code in STOP_CODES: + log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) + return code + if code == 0: + memory = "%dM" % suggested + else: + # A run that stopped early has a peak that is too small to be the budget of a smaller command. + result = result or code + return result + + +def bounded_once(options: Options, environ: Mapping[str, str]) -> Tuple[int, int]: + """Runs the command one time. Returns the exit code and the suggested budget in MiB.""" settings = Settings(environ) if options.memory is not None: budget = parse_size_mib(options.memory) @@ -1095,9 +1151,12 @@ def on_start(pid: int) -> None: log("budget %d MiB, peak %d MiB (%s), exit %d" % (budget, peak, "cgroup" if exact else "sampled, approximate", code)) if capped and code == 137: log("the command was killed; if the peak is near the budget, the hard cap stopped it") + suggested = suggested_budget_mib(peak, not exact) if options.measure: - log("suggested budget %d MiB" % suggested_budget_mib(peak, not exact)) - return code + log("suggested budget %d MiB" % suggested) + log("row label=%s cpus=%s budget=%dM peak=%dM exact=%s exit=%d" % ( + options.label or "-", options.cpus if options.cpus is not None else "-", suggested, peak, "yes" if exact else "no", code)) + return code, suggested def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 8a58e83..b3c28c5 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1257,6 +1257,25 @@ def test_a_repeated_exclusive_name_is_kept_one_time(self): ) self.assertEqual(options.exclusive, ["port", "cache"]) + def test_reads_the_rows_largest_first_and_each_one_time(self): + options = bounded_run.parse_arguments(["--measure-rows", "4,16,8,4", "--label", "unit-tests", "--", "tool"]) + self.assertEqual((options.rows, options.label, options.measure), ([16, 8, 4], "unit-tests", True)) + + def test_rejects_bad_rows_and_labels(self): + for arguments in ( + ["--measure-rows", "0,2", "--", "tool"], + ["--measure-rows", "two", "--", "tool"], + ["--measure-rows", "", "--", "tool"], + ["--measure-rows", "4,,2", "--", "tool"], + ["--measure-rows", "4,2", "--cpus", "2", "--", "tool"], + ["--measure", "--label", "unit tests", "--", "tool"], + ["--measure", "--label", "-", "--", "tool"], + ["--label", "lint", "--", "tool"], + ): + with self.subTest(arguments=arguments): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.parse_arguments(arguments) + class InsideCapTest(unittest.TestCase): def setUp(self): @@ -1710,6 +1729,91 @@ def test_the_wait_counts_no_unused_budget_without_a_cgroup_version_2(self): self.assertIsNone(self.wait_arguments("")["read_outstanding"]()) +class MeasuredRowTest(unittest.TestCase): + """Calls bounded() in this process, with run_command replaced by a stub and no hard cap. + + The stub gives each run the exit code and the ru_maxrss of the next answer, and keeps the + budget and the processors that the wrapper gave to the command. + """ + + def setUp(self): + self.lines = [] + patcher = mock.patch.object(bounded_run, "log", side_effect=self.lines.append) + patcher.start() + self.addCleanup(patcher.stop) + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.environ = dict(os.environ) + self.environ.pop("BOUNDED_RUN_ACTIVE", None) + self.environ.update({ + "BOUNDED_RUN_LOCK_DIR": os.path.join(self.base.name, "locks"), + "BOUNDED_RUN_TOTAL_MIB": "8192", + "BOUNDED_RUN_RESERVE_MIB": "0", + "BOUNDED_RUN_SLOT_MIB": "2048", + "BOUNDED_RUN_POLL_SECONDS": "0.05", + "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", + "BOUNDED_RUN_SAMPLE_SECONDS": "0.1", + "BOUNDED_RUN_NO_CAP": "1", + "BOUNDED_RUN_FREE_MIB": "1048576", + }) + self.runs = [] + + def run_bounded(self, arguments, answers): + remaining = list(answers) + + def fake_run_command(command, environ, on_start=None): + self.runs.append((int(environ["BOUNDED_RUN_CPUS"]), int(environ["BOUNDED_RUN_MEMORY_MIB"]))) + code, peak_mib = remaining.pop(0) + return code, peak_mib * 1024 + + options = bounded_run.parse_arguments(arguments + ["--", sys.executable, "-c", "pass"]) + with mock.patch.object(bounded_run, "run_command", fake_run_command), \ + mock.patch.object(bounded_run, "rusage_peak_mib", side_effect=lambda maxrss: maxrss // 1024): + return bounded_run.bounded(options, self.environ) + + def row_lines(self): + return [line for line in self.lines if line.startswith("row ")] + + def test_a_measurement_prints_one_row_line(self): + self.assertEqual(self.run_bounded(["--measure", "--cpus", "4", "--label", "unit-tests"], [(0, 1000)]), 0) + self.assertEqual(self.row_lines(), ["row label=unit-tests cpus=4 budget=1536M peak=1000M exact=no exit=0"]) + + def test_a_row_line_marks_the_options_that_were_not_given(self): + self.run_bounded(["--measure"], [(3, 100)]) + self.assertEqual(self.row_lines(), ["row label=- cpus=- budget=256M peak=100M exact=no exit=3"]) + + def test_a_run_that_does_not_measure_prints_no_row_line(self): + self.run_bounded(["--memory", "2G"], [(0, 100)]) + self.assertEqual(self.row_lines(), []) + + def test_rows_run_largest_first_and_each_smaller_row_gets_the_budget_of_the_row_before_it(self): + code = self.run_bounded(["--measure-rows", "2,8,4", "--label", "build"], [(0, 1000), (0, 500), (0, 200)]) + self.assertEqual(code, 0) + # The first row has no budget yet, so it holds the whole queue of 8192 MiB. + self.assertEqual(self.runs, [(8, 8192), (4, 1536), (2, 768)]) + self.assertEqual(self.row_lines(), [ + "row label=build cpus=8 budget=1536M peak=1000M exact=no exit=0", + "row label=build cpus=4 budget=768M peak=500M exact=no exit=0", + "row label=build cpus=2 budget=512M peak=200M exact=no exit=0", + ]) + + def test_the_largest_row_runs_with_the_given_memory(self): + self.run_bounded(["--measure-rows", "8,4", "--memory", "4G"], [(0, 1000), (0, 500)]) + self.assertEqual(self.runs, [(8, 4096), (4, 1536)]) + + def test_the_row_after_a_failed_row_gets_the_budget_of_the_failed_row(self): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(1, 300), (0, 1000), (2, 100)]) + self.assertEqual(code, 1) + self.assertEqual(self.runs, [(8, 8192), (4, 8192), (2, 1536)]) + self.assertEqual([line.split()[-1] for line in self.row_lines()], ["exit=1", "exit=0", "exit=2"]) + + def test_a_row_that_a_stop_signal_ended_ends_the_rows(self): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(0, 1000), (130, 100), (0, 100)]) + self.assertEqual(code, 130) + self.assertEqual(self.runs, [(8, 8192), (4, 1536)]) + self.assertEqual(len(self.row_lines()), 2) + + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" @@ -2222,6 +2326,15 @@ def test_measure_mode_reports_a_peak_and_a_budget(self): self.assertEqual(int(suggested.split()[-2]) % 256, 0) self.assertGreaterEqual(int(suggested.split()[-2]), value * 1.5) + def test_measured_rows_print_their_row_lines_in_order(self): + script = "import os; print(os.environ['BOUNDED_RUN_CPUS'])" + process = self.wrapper(["--measure-rows", "1,2", "--label", "lint"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + self.assertEqual(output.split(), ["2", "1"]) + rows = re.findall(r"^bounded-run: row label=lint cpus=(\d+) budget=\d+M peak=\d+M 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): holder = self.worker("holder", "4G", hold="300") self.wait_for_event("start", "holder") From 3404640cc9afa060dc7bea34f4af6433e403edf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:56:15 +0100 Subject: [PATCH 02/14] fix(skills/bounding-heavy-commands): reject a --measure-rows value that is not ASCII digits str.isdigit() accepts characters such as a superscript two, which int() cannot read, so such a value ended the wrapper with a traceback in place of its option error. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 2 +- .../bounding-heavy-commands/scripts/tests/test_bounded_run.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index e466a78..5d74b23 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -993,7 +993,7 @@ def parse_arguments(argv: Sequence[str]) -> Options: options.label = value elif flag == "--measure-rows": parts = value.split(",") - if not all(part.isdigit() and int(part) >= 1 for part in parts): + if not all(re.fullmatch(r"[0-9]+", part) and int(part) >= 1 for part in parts): raise WrapperError("cannot read --measure-rows '%s'; use whole numbers of 1 or more, such as 16,8,4" % value) options.rows = sorted(set(int(part) for part in parts), reverse=True) options.measure = True diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index b3c28c5..9047728 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1267,6 +1267,7 @@ def test_rejects_bad_rows_and_labels(self): ["--measure-rows", "two", "--", "tool"], ["--measure-rows", "", "--", "tool"], ["--measure-rows", "4,,2", "--", "tool"], + ["--measure-rows", "\u00b2", "--", "tool"], ["--measure-rows", "4,2", "--cpus", "2", "--", "tool"], ["--measure", "--label", "unit tests", "--", "tool"], ["--measure", "--label", "-", "--", "tool"], From dc6b2f80ddf1218f2edbfe4da0378da9293d7530 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:56:15 +0100 Subject: [PATCH 03/14] fix(skills/bounding-heavy-commands): show --memory for --measure-rows, and measure the rows that step 1 chose The skill said that the largest row of --measure-rows runs with no --memory, but the wrapper takes a --memory for it, as its usage text shows. The whole-project line also told each command to use all, half, and a quarter of the processors, while step 1 gives a command with self-bound none the row at half only. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 1e83bc7..d09f90e 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -34,7 +34,7 @@ A server that a heavy command talks to is a part of that command: a development ``` python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... [--measure] [--label ] -- -python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure-rows ,,... [--exclusive ]... [--label ] -- +python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure-rows ,,... [--memory ] [--exclusive ]... [--label ] -- ``` | Option | Meaning | @@ -43,7 +43,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--cpus ` | Processor limit, as a whole number. Taken from the record. | | `--exclusive ` | 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 alone in the queue. | -| `--measure-rows ,,...` | Measure the command one time at each `--cpus` of the list, one after the other, the largest first. The largest runs with no `--memory`, so it runs alone in the queue. 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 ,,...` | 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 alone in the queue. 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. | | `--label ` | A name for the row lines of a measurement, such as `unit-tests`. Use letters, digits, `.`, `_`, and `-`. It changes nothing else. | The wrapper does four things in sequence. It waits for its turn in the queue. It waits until the memory of its budget is free. It runs the command. It prints the budget and the measured peak on the error stream. For the wait, the free memory is the memory that the machine has free now, less the part of their budgets that the running bounded commands do not use yet, less a headroom for the programs outside the queue. The headroom is a tenth of the memory of the machine, and at least 1 GiB. The budget and the headroom together never need more than the memory of the queue, so a budget of the whole queue does not wait for a headroom. The wait has no time limit: the command does not start before its memory is free, and the wrapper prints a line at intervals while it waits. Each line that the wrapper prints starts with `bounded-run:`. A measurement also prints one row line, in a fixed form: @@ -125,7 +125,7 @@ The measured run is a real run of the command. Its result counts, also when the When the record does not exist (§The record, case 5), do steps 1 to 3 for every heavy command of the project. Then measure them all in one run, in place of steps 4 and 5. Do not measure only the command that you need now. A command that gets its entry later gets its first measurement in the middle of someone's work, and that measurement holds the whole queue while other sessions wait. 1. Choose the rows. Measure each command at three `--cpus`: all the machine's processors, half of them, and a quarter of them. Round each one down, use at least 1, and drop a value that is the same as another. A command with `self-bound: none` gets the row at half only: nothing in it reads its `--cpus`, so each row would measure the same command. -2. Write one command line. For each command, write one call of the wrapper with `--measure-rows ,,`, a `--label` that names the command, the `--exclusive` options of the command, and its bounded command line. Join the calls with `;`, so that a measurement that fails does not stop the others. Write the path of the wrapper in full, so that the line runs in any shell. Run it from the root of the project: +2. Write one command line. For each command, write one call of the wrapper with `--measure-rows` and the rows that step 1 chose for it, a `--label` that names the command, the `--exclusive` options of the command, and its bounded command line. Join the calls with `;`, so that a measurement that fails does not stop the others. Write the path of the wrapper in full, so that the line runs in any shell. Run it from the root of the project: ``` python3 "" --measure-rows 16,8,4 --label unit-tests -- ; python3 "" --measure-rows 16,8,4 --label lint -- From 4689820befaa5522695b1e6d8c474d766b537f83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:10:43 +0100 Subject: [PATCH 04/14] fix(skills/bounding-heavy-commands): keep the first failed exit code when a stop signal ends the rows The usage text and the skill say that the exit code of --measure-rows is the first exit code of a row that is not 0. When a row failed and a later row was stopped by a signal, the wrapper returned the code of the stop. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 2 +- .../scripts/tests/test_bounded_run.py | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 5d74b23..043c565 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1020,7 +1020,7 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: code, suggested = bounded_once(row, environ) if code in STOP_CODES: log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) - return code + return result or code if code == 0: memory = "%dM" % suggested else: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 9047728..b036feb 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1814,6 +1814,11 @@ def test_a_row_that_a_stop_signal_ended_ends_the_rows(self): self.assertEqual(self.runs, [(8, 8192), (4, 1536)]) self.assertEqual(len(self.row_lines()), 2) + def test_a_stop_signal_after_a_failed_row_keeps_the_first_exit_code(self): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(1, 1000), (130, 100), (0, 100)]) + self.assertEqual(code, 1) + self.assertEqual(len(self.runs), 2) + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" From b2643739070bfd1cff1a5185ef90850bb6519360 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:10:43 +0100 Subject: [PATCH 05/14] fix(skills/bounding-heavy-commands): give each command of the line its own label, and ask for output from a terminal Step 5 puts each row line into the entry of its label, so two commands with one label made their rows ambiguous. And when the user runs the line in a terminal, the agent cannot see its output, so it now asks the user for the row lines and the end of the output of each command. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index d09f90e..729c571 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -125,7 +125,7 @@ The measured run is a real run of the command. Its result counts, also when the When the record does not exist (§The record, case 5), do steps 1 to 3 for every heavy command of the project. Then measure them all in one run, in place of steps 4 and 5. Do not measure only the command that you need now. A command that gets its entry later gets its first measurement in the middle of someone's work, and that measurement holds the whole queue while other sessions wait. 1. Choose the rows. Measure each command at three `--cpus`: all the machine's processors, half of them, and a quarter of them. Round each one down, use at least 1, and drop a value that is the same as another. A command with `self-bound: none` gets the row at half only: nothing in it reads its `--cpus`, so each row would measure the same command. -2. Write one command line. For each command, write one call of the wrapper with `--measure-rows` and the rows that step 1 chose for it, a `--label` that names the command, the `--exclusive` options of the command, and its bounded command line. Join the calls with `;`, so that a measurement that fails does not stop the others. Write the path of the wrapper in full, so that the line runs in any shell. Run it from the root of the project: +2. Write one command line. For each command, write one call of the wrapper with `--measure-rows` and the rows that step 1 chose for it, a `--label` that names the command and no other command of the line, the `--exclusive` options of the command, and its bounded command line. Join the calls with `;`, so that a measurement that fails does not stop the others. Write the path of the wrapper in full, so that the line runs in any shell. Run it from the root of the project: ``` python3 "" --measure-rows 16,8,4 --label unit-tests -- ; python3 "" --measure-rows 16,8,4 --label lint -- @@ -133,7 +133,7 @@ When the record does not exist (§The record, case 5), do steps 1 to 3 for every 3. Ask the user to run the line when the machine is quiet. Do not run it yourself unless the user asks you to. Your message names the commands and the rows that the line measures. It says that the line can take a long time, and that the first row of each command holds the whole queue, so that the heavy commands of the other sessions wait while it runs. It says how to run the line: type `! ` in this session, or run it in a terminal at the root of the project, or tell you to run it. 4. Act on the answer: - - **The user ran the line.** Read its output into the record (step 5 of this list). + - **The user ran the line.** Read its output into the record (step 5 of this list). When the user ran it in a terminal, you cannot see the output: ask the user for each line that starts with `bounded-run: row`, and for the end of the output of each command, which shows whether the run did its full work. - **The user tells you to run it.** Run it in the background, with no short timeout around it. Continue with work that runs no heavy command. A heavy command that you need before the line ends runs through the wrapper with no `--memory` option. When the line ends, read its output into the record (step 5 of this list). - **The user declines.** Run steps 4 to 6 of the list above for the command that you are about to run, and save the record. Each other command gets its entry when an agent first needs it (§The record, case 3). 5. Read the row lines of the output. Each row line of a run that did its full work gives the row at its `cpus`, in the entry of its `label`: its `budget`, its `peak`, and the date. A run did its full work when it exits 0, or when it ran all of its work and reported failures, such as a suite that ran each test and reported the failures. Step 5 of the list above names the runs that stopped early. A row line of such a run gives no row: write nothing for it. The row at half the processors is the default row. When it has no row, the default row is the row with the `--cpus` nearest to half. An entry that has no row is incomplete (§The record), and an agent measures it when it first needs it. Save the record. From 043d5fa7c631cf99b54a395ece0a19820dd384d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:20:23 +0100 Subject: [PATCH 06/14] fix(skills/bounding-heavy-commands): reject a --measure-rows value with too many digits for int() int() refuses a number with more digits than its limit and raises ValueError, which ended the wrapper with a traceback in place of its option error. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 9 +++++++-- .../scripts/tests/test_bounded_run.py | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 043c565..7e81c9c 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -993,9 +993,14 @@ def parse_arguments(argv: Sequence[str]) -> Options: options.label = value elif flag == "--measure-rows": parts = value.split(",") - if not all(re.fullmatch(r"[0-9]+", part) and int(part) >= 1 for part in parts): + try: + rows = [int(part) for part in parts if re.fullmatch(r"[0-9]+", part)] + except ValueError: + # int() refuses a number with more digits than its limit. + rows = [] + if len(rows) != len(parts) or min(rows) < 1: raise WrapperError("cannot read --measure-rows '%s'; use whole numbers of 1 or more, such as 16,8,4" % value) - options.rows = sorted(set(int(part) for part in parts), reverse=True) + options.rows = sorted(set(rows), reverse=True) options.measure = True else: if not value.isdigit() or int(value) < 1: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index b036feb..f9c3622 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1268,6 +1268,7 @@ def test_rejects_bad_rows_and_labels(self): ["--measure-rows", "", "--", "tool"], ["--measure-rows", "4,,2", "--", "tool"], ["--measure-rows", "\u00b2", "--", "tool"], + ["--measure-rows", "9" * 5000, "--", "tool"], ["--measure-rows", "4,2", "--cpus", "2", "--", "tool"], ["--measure", "--label", "unit tests", "--", "tool"], ["--measure", "--label", "-", "--", "tool"], From 4738772ec2a66b7457a7ef4e9a14a2b6129a383a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:20:23 +0100 Subject: [PATCH 07/14] docs(skills/bounding-heavy-commands): show the row line of the usage text as the wrapper prints it The usage text wrote each size field as MIBM, which reads as a literal value. The wrapper prints a number followed by M, as the skill shows. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 7e81c9c..6b35808 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -9,7 +9,7 @@ A measurement prints one row line on the error stream, in a fixed form: - bounded-run: row label=NAME cpus=N budget=MIBM peak=MIBM exact=yes|no exit=CODE + bounded-run: row label=NAME cpus=N budget=M peak=M exact=yes|no exit=CODE budget is the suggested budget. A '-' stands for an option that the call did not give. --measure-rows measures the command at each processor limit of the From 7304ffcca70b4c31696e64390a3a520f47a75e1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:29:46 +0100 Subject: [PATCH 08/14] fix(skills/bounding-heavy-commands): reject a --label that ends with a line break The check used re.match with $, which also matches before a final line break, so a label such as "lint" with a line break passed and split the row line in two. It now uses re.fullmatch. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 2 +- .../bounding-heavy-commands/scripts/tests/test_bounded_run.py | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 6b35808..1ae5ea4 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -988,7 +988,7 @@ def parse_arguments(argv: Sequence[str]) -> Options: options.exclusive.append(value) elif flag == "--label": # The row line separates its fields with spaces and marks a missing label with '-'. - if re.match(r"^[A-Za-z0-9][A-Za-z0-9._-]*$", value) is None: + if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", value) is None: raise WrapperError("cannot use the label '%s'; use letters, digits, '.', '_' and '-', and start with a letter or a digit" % value) options.label = value elif flag == "--measure-rows": diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index f9c3622..089b35a 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1272,6 +1272,7 @@ def test_rejects_bad_rows_and_labels(self): ["--measure-rows", "4,2", "--cpus", "2", "--", "tool"], ["--measure", "--label", "unit tests", "--", "tool"], ["--measure", "--label", "-", "--", "tool"], + ["--measure", "--label", "lint\n", "--", "tool"], ["--label", "lint", "--", "tool"], ): with self.subTest(arguments=arguments): From bab78b6971deb9e4d2ac29db3ccee619ace924a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:29:46 +0100 Subject: [PATCH 09/14] docs(skills/bounding-heavy-commands): say that a --label starts with a letter or a digit The wrapper rejects a label that starts with '.', '_' or '-', and the option table did not say so. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 729c571..91340de 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -44,7 +44,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--exclusive ` | 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 alone in the queue. | | `--measure-rows ,,...` | 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 alone in the queue. 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. | -| `--label ` | A name for the row lines of a measurement, such as `unit-tests`. Use letters, digits, `.`, `_`, and `-`. It changes nothing else. | +| `--label ` | 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. | The wrapper does four things in sequence. It waits for its turn in the queue. It waits until the memory of its budget is free. It runs the command. It prints the budget and the measured peak on the error stream. For the wait, the free memory is the memory that the machine has free now, less the part of their budgets that the running bounded commands do not use yet, less a headroom for the programs outside the queue. The headroom is a tenth of the memory of the machine, and at least 1 GiB. The budget and the headroom together never need more than the memory of the queue, so a budget of the whole queue does not wait for a headroom. The wait has no time limit: the command does not start before its memory is free, and the wrapper prints a line at intervals while it waits. Each line that the wrapper prints starts with `bounded-run:`. A measurement also prints one row line, in a fixed form: From d420af24e47e84ae3fb51d742413521e483d3657 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:41:16 +0100 Subject: [PATCH 10/14] fix(skills/bounding-heavy-commands): limit each --measure-rows value to six digits The last fix relied on int() refusing a number with too many digits, but Python 3.9 has no such limit, so the new test failed there. Each value now has at most six digits, which the parser checks itself on every version, and the option error names the range. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 9 +++------ .../scripts/tests/test_bounded_run.py | 1 + 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 1ae5ea4..c5a8927 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -993,13 +993,10 @@ def parse_arguments(argv: Sequence[str]) -> Options: options.label = value elif flag == "--measure-rows": parts = value.split(",") - try: - rows = [int(part) for part in parts if re.fullmatch(r"[0-9]+", part)] - except ValueError: - # int() refuses a number with more digits than its limit. - rows = [] + # int() of a very long number is slow on some versions of Python and raises ValueError on others. + rows = [int(part) for part in parts if re.fullmatch(r"[0-9]{1,6}", part)] if len(rows) != len(parts) or min(rows) < 1: - raise WrapperError("cannot read --measure-rows '%s'; use whole numbers of 1 or more, such as 16,8,4" % value) + raise WrapperError("cannot read --measure-rows '%s'; use whole numbers from 1 to 999999, such as 16,8,4" % value) options.rows = sorted(set(rows), reverse=True) options.measure = True else: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 089b35a..e494269 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1269,6 +1269,7 @@ def test_rejects_bad_rows_and_labels(self): ["--measure-rows", "4,,2", "--", "tool"], ["--measure-rows", "\u00b2", "--", "tool"], ["--measure-rows", "9" * 5000, "--", "tool"], + ["--measure-rows", "1000000", "--", "tool"], ["--measure-rows", "4,2", "--cpus", "2", "--", "tool"], ["--measure", "--label", "unit tests", "--", "tool"], ["--measure", "--label", "-", "--", "tool"], From dbb833fafa9405557a34effadf4dbdc59bb1a476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:03:13 +0100 Subject: [PATCH 11/14] fix(skills/bounding-heavy-commands): keep the first failed exit code when an interrupt ends the wait of a later row A signal while a row runs comes back as that row's exit code, but a signal while a row waits in the queue raises KeyboardInterrupt. That went past the rows loop to main(), which returned 130 and lost the failure of an earlier row. The loop now catches it and returns the first failed code, or 130. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 7 ++++++- .../scripts/tests/test_bounded_run.py | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index c5a8927..7339bab 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1019,7 +1019,12 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: row = Options() row.memory, row.cpus, row.exclusive, row.measure, row.label, row.command = ( memory, cpus, options.exclusive, True, options.label, options.command) - code, suggested = bounded_once(row, environ) + try: + code, suggested = bounded_once(row, environ) + except KeyboardInterrupt: + # A signal while a row runs comes back as its exit code. A signal while it waits in the queue raises. + log("interrupted while waiting; the rows from --cpus %d are not measured" % cpus) + return result or 130 if code in STOP_CODES: log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) return result or code diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index e494269..b162da4 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1822,6 +1822,21 @@ def test_a_stop_signal_after_a_failed_row_keeps_the_first_exit_code(self): self.assertEqual(code, 1) self.assertEqual(len(self.runs), 2) + def test_an_interrupt_while_a_later_row_waits_keeps_the_first_exit_code(self): + real_once = bounded_run.bounded_once + calls = [] + + def once(options, environ): + calls.append(options.cpus) + if len(calls) == 2: + raise KeyboardInterrupt + return real_once(options, environ) + + with mock.patch.object(bounded_run, "bounded_once", once): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(1, 1000)]) + self.assertEqual(code, 1) + self.assertEqual(calls, [8, 4]) + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" From 232a361fb81fbf49c1d2565df6a717d613d7bf1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:08:42 +0100 Subject: [PATCH 12/14] fix(skills/bounding-heavy-commands): measure a command that reuses its own output at one row only --measure-rows runs a command once for each row, one after the other. A build, a generator, or an install reuses the output of the run before, so its smaller rows did less work and recorded a peak that was too small. Such a command now gets the row at half only, like a command with self-bound none. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 91340de..6511ea7 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -124,7 +124,7 @@ The measured run is a real run of the command. Its result counts, also when the When the record does not exist (§The record, case 5), do steps 1 to 3 for every heavy command of the project. Then measure them all in one run, in place of steps 4 and 5. Do not measure only the command that you need now. A command that gets its entry later gets its first measurement in the middle of someone's work, and that measurement holds the whole queue while other sessions wait. -1. Choose the rows. Measure each command at three `--cpus`: all the machine's processors, half of them, and a quarter of them. Round each one down, use at least 1, and drop a value that is the same as another. A command with `self-bound: none` gets the row at half only: nothing in it reads its `--cpus`, so each row would measure the same command. +1. Choose the rows. Measure each command at three `--cpus`: all the machine's processors, half of them, and a quarter of them. Round each one down, use at least 1, and drop a value that is the same as another. A command with `self-bound: none` gets the row at half only: nothing in it reads its `--cpus`, so each row would measure the same command. A command whose next run reuses the output of the run before, such as a build or a generator with a cache, also gets the row at half only: its later rows would do less work and measure a peak that is too small. 2. Write one command line. For each command, write one call of the wrapper with `--measure-rows` and the rows that step 1 chose for it, a `--label` that names the command and no other command of the line, the `--exclusive` options of the command, and its bounded command line. Join the calls with `;`, so that a measurement that fails does not stop the others. Write the path of the wrapper in full, so that the line runs in any shell. Run it from the root of the project: ``` From 4924c83cf2b669b081d24ac56e964aa213c2c26a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 03:15:40 +0100 Subject: [PATCH 13/14] fix(skills/bounding-heavy-commands): keep the first failed exit code for each stop signal between the rows The last fix covered SIGINT only. SIGTERM, SIGHUP, or SIGQUIT while a later row waited in the queue still ended the wrapper with the default action of the signal, and the failure of an earlier row was lost. --measure-rows now handles the three signals for the whole list and returns the first failed code, or 128 plus the signal. The handlers of the caller come back when the list ends. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 26 ++++++++++++++++--- .../scripts/tests/test_bounded_run.py | 21 +++++++++++++++ 2 files changed, 44 insertions(+), 3 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 7339bab..2fcb3a4 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1010,9 +1010,29 @@ def parse_arguments(argv: Sequence[str]) -> Options: return options +class _Stopped(Exception): + def __init__(self, signum: int) -> None: + super().__init__(signum) + self.signum = signum + + +def _raise_stopped(signum: int, frame: object) -> None: + raise _Stopped(signum) + + def bounded(options: Options, environ: Mapping[str, str]) -> int: if not options.rows: return bounded_once(options, environ)[0] + # run_command sets its own handlers while a row runs and puts these back after it. + previous = {signum: signal.signal(signum, _raise_stopped) for signum in (signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT)} + try: + return _bounded_rows(options, environ) + finally: + for signum, handler in previous.items(): + signal.signal(signum, handler) + + +def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int: memory = options.memory result = 0 for cpus in options.rows: @@ -1021,10 +1041,10 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: memory, cpus, options.exclusive, True, options.label, options.command) try: code, suggested = bounded_once(row, environ) - except KeyboardInterrupt: + except (KeyboardInterrupt, _Stopped) as stop: # A signal while a row runs comes back as its exit code. A signal while it waits in the queue raises. - log("interrupted while waiting; the rows from --cpus %d are not measured" % cpus) - return result or 130 + log("stopped by a signal while waiting; the rows from --cpus %d are not measured" % cpus) + return result or 128 + (stop.signum if isinstance(stop, _Stopped) else int(signal.SIGINT)) if code in STOP_CODES: log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) return result or code diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index b162da4..f4e7e26 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1822,6 +1822,27 @@ def test_a_stop_signal_after_a_failed_row_keeps_the_first_exit_code(self): self.assertEqual(code, 1) self.assertEqual(len(self.runs), 2) + def test_a_stop_signal_while_a_later_row_waits_keeps_the_first_exit_code(self): + for failure, expected in ((1, 1), (0, 128 + signal.SIGTERM)): + with self.subTest(failure=failure): + real_once = bounded_run.bounded_once + calls = [] + + def once(options, environ): + calls.append(options.cpus) + if len(calls) == 2: + os.kill(os.getpid(), signal.SIGTERM) + time.sleep(5) + return real_once(options, environ) + + before = signal.getsignal(signal.SIGTERM) + self.runs = [] + with mock.patch.object(bounded_run, "bounded_once", once): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(failure, 1000)]) + self.assertEqual(code, expected) + self.assertEqual(calls, [8, 4]) + self.assertIs(signal.getsignal(signal.SIGTERM), before) + def test_an_interrupt_while_a_later_row_waits_keeps_the_first_exit_code(self): real_once = bounded_run.bounded_once calls = [] From 83c2de08a4a7953d7beb24d7537d4b83402d960e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 09:48:38 +0100 Subject: [PATCH 14/14] fix(skills/bounding-heavy-commands): catch a stop signal anywhere in the list of rows The handlers of --measure-rows raise at any point of the list, but the rows loop caught the signal only while a row waited, and main() caught SIGINT only. A SIGTERM, SIGHUP, or SIGQUIT between two rows, or after the list before the handlers were put back, ended the wrapper with a traceback. The loop now catches it for the whole list and keeps the first failed code, and main() catches it after the list. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 40 +++++++++++-------- .../scripts/tests/test_bounded_run.py | 5 +++ 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 2fcb3a4..00717cd 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1035,24 +1035,26 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int: memory = options.memory result = 0 - for cpus in options.rows: - row = Options() - row.memory, row.cpus, row.exclusive, row.measure, row.label, row.command = ( - memory, cpus, options.exclusive, True, options.label, options.command) - try: + measured = 0 + try: + for cpus in options.rows: + row = Options() + row.memory, row.cpus, row.exclusive, row.measure, row.label, row.command = ( + memory, cpus, options.exclusive, True, options.label, options.command) code, suggested = bounded_once(row, environ) - except (KeyboardInterrupt, _Stopped) as stop: - # A signal while a row runs comes back as its exit code. A signal while it waits in the queue raises. - log("stopped by a signal while waiting; the rows from --cpus %d are not measured" % cpus) - return result or 128 + (stop.signum if isinstance(stop, _Stopped) else int(signal.SIGINT)) - if code in STOP_CODES: - log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) - return result or code - if code == 0: - memory = "%dM" % suggested - else: - # A run that stopped early has a peak that is too small to be the budget of a smaller command. - result = result or code + measured += 1 + if code in STOP_CODES: + log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) + return result or code + if code == 0: + memory = "%dM" % suggested + else: + # A run that stopped early has a peak that is too small to be the budget of a smaller command. + 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. + 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 @@ -1204,6 +1206,10 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st except KeyboardInterrupt: 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. + log("stopped by a signal") + return 128 + stop.signum except WrapperError as error: log(str(error)) return EXIT_WRAPPER diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index f4e7e26..f6ec6bc 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1843,6 +1843,11 @@ def once(options, environ): self.assertEqual(calls, [8, 4]) self.assertIs(signal.getsignal(signal.SIGTERM), before) + def test_a_stop_signal_outside_a_row_ends_main_with_its_code(self): + options = ["--measure-rows", "8,4", "--", sys.executable, "-c", "pass"] + with mock.patch.object(bounded_run, "bounded", side_effect=bounded_run._Stopped(int(signal.SIGTERM))): + self.assertEqual(bounded_run.main(options, self.environ), 128 + signal.SIGTERM) + def test_an_interrupt_while_a_later_row_waits_keeps_the_first_exit_code(self): real_once = bounded_run.bounded_once calls = []