From 9e94e5d302774704a88d324f4638ece1c8bc5aca 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:08:36 +0100 Subject: [PATCH 01/13] feat(skills/bounding-heavy-commands): let an agent check the queue before it chooses a measured row A command in the record can have a row for each --cpus, and an agent must choose one before each run. It had nothing to choose with: the skill tells it that looking at the load does not protect the machine, so an agent with rows at 2, 4, and 8 processors on a busy machine chose the middle row by guess. The wrapper now has a check mode, --check [--memory ]..., that runs no command and holds no lock when it returns. It prints the slots, the free slots, the free memory, the unused budgets of the running commands, the headroom, and whether a command waits in the line. For each budget it prints the slots that it needs and whether a run of that budget would start now, with the same memory test as the wait. It counts the slots under the turn lock without a wait, so it never makes a free slot look held to a waiter. The skill tells an agent to run the check before a run of a command with more than one row, to choose the largest row that would start now, and to choose the default row and let it wait when none would. The check is a snapshot, so the chosen row still goes through the queue. A subagent gets the rows and the check line, and chooses the row itself before each run. Closes #57 Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 24 ++- .../scripts/bounded_run.py | 105 +++++++++- .../scripts/tests/test_bounded_run.py | 188 ++++++++++++++++++ 3 files changed, 308 insertions(+), 9 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 6511ea7..046fcf9 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -11,7 +11,7 @@ Every heavy command an agent starts goes through the wrapper. There is no except A machine freezes because of the heavy commands that run on it, not because of the number of agents. Sessions in other terminals and other projects run their own test suites and builds at the same moment, and no session can see the others. When the commands together need more memory than the machine has, it swaps until it stops responding, and that costs every session, not only the one that started the last command. The wrapper makes the commands of every session and every project on the machine take turns on its memory, so too much work shows up as a queue instead of a freeze. -**Looking first does not protect the machine.** Two sessions that look at the load at the same moment both see a quiet machine, and both start. A sum of budgets against the machine's total memory does not protect it either: the sum counts your commands and no one else's. Only a reservation that every session takes before it starts can count the commands, and the wrapper is that reservation. +**Looking first does not protect the machine.** Two sessions that look at the load at the same moment both see a quiet machine, and both start. A sum of budgets against the machine's total memory does not protect it either: the sum counts your commands and no one else's. Only a reservation that every session takes before it starts can count the commands, and the wrapper is that reservation. The check of the wrapper looks too, but it decides which measured row to queue, never whether to queue (§The record). **Violating the letter of these rules is violating their spirit.** @@ -35,6 +35,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 ,,... [--memory ] [--exclusive ]... [--label ] -- +python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --check [--memory ]... ``` | Option | Meaning | @@ -45,6 +46,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--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 `-`, and start with a letter or a digit. It changes nothing else. | +| `--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. | 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: @@ -54,6 +56,15 @@ 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). +A check prints its lines in a fixed form too: + +``` +bounded-run: check slots= slot=M free-slots= free=M unused=M headroom=M line= +bounded-run: check budget=M slots= starts= +``` + +The first line gives the slots of the queue and their size, the slots that are free now, the free memory, the unused budgets of the running commands, and the headroom. `line=busy` means that a command waits in the line. Each next line is one `--memory`, in the order given: the slots that it needs, and `starts=yes` when a command of that budget would start now. A `-` means that the check cannot read or count the value at that moment. + 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. @@ -81,12 +92,16 @@ A budget is valid only at the `--cpus` of its row. The same command at more proc The table has one row for each `--cpus`. A measurement at a `--cpus` that has no row adds a row. A measurement at a `--cpus` that has a row replaces that row. Never delete a row because a different `--cpus` was measured. Two entries whose command lines differ only in the values of the wrapper's `--memory` and `--cpus`, before the `--`, are one entry: keep one, with the rows of both, and where both have a row at the same `--cpus`, keep the newer one. The row at the `--cpus` of the default row of the entry that you keep stays the default row, and no other row is marked as the default. Then write the `--cpus` and the budget of the default row into the command line. One row is the default row. A run uses it when nothing asks for a different one. +Before a run of a command whose entry has more than one row, choose the row with the check. Run the wrapper with `--check` and one `--memory` for the budget of each row. Choose the largest row that would start now (`starts=yes`). When no row would start now, choose the default row and let it wait in the queue: the smallest row runs slowest, and the line keeps the wait fair. Then run the chosen row through the wrapper, with the `--cpus` and the `--memory` of that row. An entry with one row needs no check. + +The check is a snapshot, not a reservation. Two sessions can see the same free slots at the same moment, so the chosen row still goes through the queue. A check never replaces the wrapper. + An entry is complete when it has a `self-bound` field, at least one row, and one default row whose `--cpus` and budget are the values in its command line. An entry without the `self-bound` field is incomplete, also when it has a budget: its budget can be the peak of a command that nothing limits. An entry from an older shape of this record, with one budget and no table, is complete in one case only: its command line passes `--cpus` to the wrapper, before the `--`, and reads `BOUNDED_RUN_CPUS`. Then rewrite it into this shape. The setting that reads the variable is its `self-bound`, and its budget, peak, and date become the default row at that `--cpus`. Then, before each heavy command, use the first case that applies: 1. **Your prompt carries bounded command lines.** You are a subagent. Use them under the rule that your prompt gives with them, and run no discovery. For a heavy command that your prompt does not carry, use the wrapper with no `--memory` option. -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. +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 row that you chose. 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 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. @@ -168,8 +183,8 @@ A subagent does not see your project memory. It knows the bounded commands only On a machine on which the wrapper can run, every dispatch prompt for a subagent that will run a heavy command MUST include: -1. The bounded command line for each heavy command, copied from the record, with the `--cpus` and the budget of the row that you chose for it. -2. This rule, in these words: "Run the bounded commands as written. You can make two changes: a narrower argument at the end of the line, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited." +1. The bounded command line for each heavy command, copied from the record, with the `--cpus` and the budget of its default row. When its entry has more than one row, also the `--cpus` and the budget of each row, and its check line with one `--memory` for each row. +2. This rule, in these words: "Run the bounded commands as written. You can make three changes: the `--cpus` and the `--memory` of a row that this prompt gives for the command, a narrower argument at the end of the line, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. When this prompt gives a command more than one row, run its check line before each run, and use the largest row with `starts=yes`, or the default row when no row has it. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited." 3. Each command that an instruction exempts from the wrapper, in its plain form, in a list of its own, with the instruction that exempts it. The rule of item 2 does not apply to that list. An instruction of the user that covers one run goes to the one subagent that does that run, and to no other. Do not dispatch fewer subagents to protect the machine. The queue protects it. Subagents that wait in the queue cost time, not memory. On a machine on which the wrapper cannot run, the next section says how to dispatch. @@ -191,6 +206,7 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "This session is the only one running, so the plain command is fine" | You cannot see other sessions or other projects. Each heavy command goes through the wrapper, unless an instruction names the plain command. | | "Both budgets together are well under the machine's memory" | The sum counts your commands only. The queue counts the commands of every session. | | "I'll check the load first and start when it is quiet" | Each session that looks at that moment sees the same quiet machine. Take the reservation: run through the wrapper. | +| "The check says it would start, so I'll run the plain command" | The check is a snapshot, not a reservation. Another session can take the same slots a moment later. Run the chosen row through the wrapper. | | "It is only the linter, it is small" | The record says what is heavy, not your sense of it. Not in the record, and not a part of a recorded command, means not yet measured. | | "I'll run just those few tests now, that fits in the free memory" | A part of a heavy command goes through the wrapper too. "It fits" is your estimate; the queue is the count. | | "I'll run the plain command once to check quickly" | One command outside the queue is all a freeze needs. | diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 00717cd..8fd1599 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -3,6 +3,7 @@ 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... + bounded_run.py --check [--memory SIZE]... The exit code is the exit code of the command. Exit code 125 means that this script failed before the command gave a result. @@ -18,6 +19,16 @@ 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. +--check runs no command and holds no lock when it returns. Its exit code is 0. +It prints the state of the queue at that moment, and one line for each +--memory, in the order given: + + bounded-run: check slots=N slot=MIBM free-slots=N|- free=MIBM|- unused=MIBM|- headroom=MIBM line=free|busy + bounded-run: check budget=MIBM slots=N starts=yes|no + +A '-' stands for a value that the check cannot read or count here. starts=yes +means that a run of that budget would start now. It is not a reservation. + 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 @@ -82,7 +93,8 @@ PR_SET_PDEATHSIG = 1 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..." + " bounded_run.py --measure-rows N,N,... [--memory SIZE] [--exclusive NAME]... [--label NAME] -- COMMAND...\n" + " bounded_run.py --check [--memory SIZE]..." ) # 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)) @@ -441,8 +453,11 @@ def _names_free(directory: str, exclusive_files: Sequence[str]) -> bool: return True -def _free_slots(directory: str, count: int) -> int: - turn = _lock(os.path.join(directory, "reserve.lock"), wait=True) +def _free_slots(directory: str, count: int, wait: bool = True) -> Optional[int]: + """Returns the number of free slots, or None when wait is false and a waiter holds the turn lock.""" + turn = _lock(os.path.join(directory, "reserve.lock"), wait=wait) + if turn is None: + return None try: free = 0 for index in range(count): @@ -553,6 +568,11 @@ def available_memory_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/c return min(found) if found else None +def memory_fits(budget_mib: int, available: Optional[int], outstanding: Optional[int], headroom_mib: int) -> bool: + """Returns whether a command of the budget may start. True when the free memory is not known.""" + return available is None or available - (outstanding or 0) - headroom_mib >= budget_mib + + def wait_for_memory( budget_mib: int, interval_seconds: float, poll_seconds: float, headroom_mib: int = 0, read_available: Callable[[], Optional[int]] = available_memory_mib, @@ -583,7 +603,7 @@ def wait_for_memory( outstanding = None if before is None or after is None else max(before, after) counted = "unused running budgets not counted here" if outstanding is None else "%d MiB of running budgets unused" % outstanding state = "%d MiB free, %s, %d MiB headroom, budget %d MiB" % (available, counted, headroom_mib, budget_mib) - if available - (outstanding or 0) - headroom_mib >= budget_mib: + if memory_fits(budget_mib, available, outstanding, headroom_mib): log(state + "; starting") return waited = clock() - started @@ -959,14 +979,36 @@ def __init__(self) -> None: self.rows: List[int] = [] self.label: Optional[str] = None self.command: List[str] = [] + self.check = False + self.budgets: List[int] = [] + + +def _parse_check(flags: Sequence[str], has_command: bool) -> Options: + options = Options() + options.check = True + if has_command: + raise WrapperError("--check runs no command; remove the '--' and the command\n" + USAGE) + remaining = list(flags) + while remaining: + flag = remaining.pop(0) + if flag == "--check": + continue + if flag != "--memory": + raise WrapperError("--check takes only --memory, not '%s'\n%s" % (flag, USAGE)) + if not remaining: + raise WrapperError("the option '--memory' needs a value\n" + USAGE) + options.budgets.append(parse_size_mib(remaining.pop(0))) + return options def parse_arguments(argv: Sequence[str]) -> Options: options = Options() arguments = list(argv) + split = arguments.index("--") if "--" in arguments else len(arguments) + if "--check" in arguments[:split]: + return _parse_check(arguments[:split], split < len(arguments)) if "--" not in arguments: raise WrapperError("the '--' before the command is missing\n" + USAGE) - split = arguments.index("--") options.command = arguments[split + 1:] if not options.command: raise WrapperError("the command is missing\n" + USAGE) @@ -1188,6 +1230,57 @@ def on_start(pid: int) -> None: return code, suggested +def check( + budgets: Sequence[int], environ: Mapping[str, str], + read_available: Callable[[], Optional[int]] = available_memory_mib, + read_outstanding: Optional[Callable[[], Optional[int]]] = None, +) -> int: + """Prints the state of the queue and, for each budget in MiB, whether a run of that budget would start now. + + Takes no reservation and holds no lock when it returns. read_outstanding gives the unused budgets of the + running commands, or None where they cannot be counted; by default the check finds them as a run does. + """ + settings = Settings(environ) + count = slot_count(settings.total_mib, settings.slot_mib, settings.reserve_mib) + most = queue_mib(settings.total_mib, settings.slot_mib, settings.reserve_mib) + uid = os.getuid() + directory = lock_directory(environ, uid) + ensure_lock_directory(directory, uid) + # A waiter tries for slots only while it holds the turn lock, so a count under that lock never makes a free slot look held to it. + free_slots = _free_slots(directory, count, wait=False) + line = _try_lock(os.path.join(directory, "line.lock")) + if line is not None: + os.close(line) + if read_outstanding is None: + unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) + choice = None if settings.no_cap else choose_cap_prefix(settings.slot_mib, None, unit, probe_cap) + scopes = scope_parent_directory(choice[1]) if choice is not None else None + skip = [name for name in (own_scope_name(),) if name is not None] + + def read_outstanding() -> Optional[int]: + return None if scopes is None else unused_budget_mib(scopes, skip) + + if settings.free_mib is None: + available = read_available() + outstanding = read_outstanding() + else: + available, outstanding = settings.free_mib, None + headroom = headroom_mib(settings.total_mib, 0, most) + + def mib(value: Optional[int]) -> str: + return "-" if value is None else "%dM" % value + + log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s headroom=%dM line=%s" % ( + count, settings.slot_mib, "-" if free_slots is None else free_slots, mib(available), mib(outstanding), + headroom, "free" if line is not None else "busy")) + for budget in budgets: + needed = slots_needed(budget, settings.slot_mib, count) + starts = (line is not None and free_slots is not None and free_slots >= needed + and memory_fits(min(budget, most), available, outstanding, headroom_mib(settings.total_mib, min(budget, most), most))) + log("check budget=%dM slots=%d starts=%s" % (budget, needed, "yes" if starts else "no")) + return 0 + + def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int: arguments = list(sys.argv[1:] if argv is None else argv) variables = os.environ if environ is None else environ @@ -1195,6 +1288,8 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st if len(arguments) > 4 and arguments[0] == "--inside-cap" and arguments[3] == "--": return inside_cap(arguments[1], arguments[2], arguments[4:]) options = parse_arguments(arguments) + if options.check: + return check(options.budgets, variables) if variables.get(ACTIVE_VARIABLE): log("nested call; running the command directly") try: 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 f6ec6bc..b80519b 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1864,6 +1864,164 @@ def once(options, environ): self.assertEqual(calls, [8, 4]) +class CheckTest(unittest.TestCase): + """Calls check() in this process with four slots of 2 GiB, a headroom of 1024 MiB, and no hard cap. + + The test holds lock files of the queue itself, as a running command and a waiter hold them. + """ + + 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.directory = os.path.join(self.base.name, "locks") + os.mkdir(self.directory, 0o700) + self.environ = dict(os.environ) + self.environ.pop("BOUNDED_RUN_ACTIVE", None) + self.environ.update({ + "BOUNDED_RUN_LOCK_DIR": self.directory, + "BOUNDED_RUN_TOTAL_MIB": "8192", + "BOUNDED_RUN_RESERVE_MIB": "0", + "BOUNDED_RUN_SLOT_MIB": "2048", + "BOUNDED_RUN_NO_CAP": "1", + }) + + def hold(self, name): + descriptor = bounded_run._try_lock(os.path.join(self.directory, name)) + self.assertIsNotNone(descriptor) + self.addCleanup(os.close, descriptor) + return descriptor + + def check(self, budgets=(), available=16384, outstanding=None): + options = bounded_run.parse_arguments(["--check"] + [part for budget in budgets for part in ("--memory", budget)]) + code = bounded_run.check(options.budgets, self.environ, read_available=lambda: available, read_outstanding=lambda: outstanding) + self.assertEqual(code, 0) + return self.lines + + def test_reports_the_slots_the_memory_and_the_line(self): + self.assertEqual(self.check(), [ + "check slots=4 slot=2048M free-slots=4 free=16384M unused=- headroom=1024M line=free", + ]) + + def test_a_budget_of_the_whole_queue_starts_when_the_memory_of_the_queue_is_free(self): + self.assertEqual(self.check(["8G"], available=8192)[-1], "check budget=8192M slots=4 starts=yes") + + def test_the_free_memory_for_the_tests_replaces_the_measured_one(self): + self.environ["BOUNDED_RUN_FREE_MIB"] = "4096" + lines = self.check(["2G"], available=0, outstanding=65536) + self.assertIn(" free=4096M unused=- ", lines[0]) + self.assertEqual(lines[-1], "check budget=2048M slots=1 starts=yes") + + def test_counts_the_slots_that_running_commands_hold(self): + self.hold("slot-000.lock") + self.hold("slot-002.lock") + self.assertIn(" free-slots=2 ", self.check()[0]) + + def test_a_command_can_take_every_free_slot_after_the_check(self): + self.hold("slot-001.lock") + self.check(["2G"]) + reservation = bounded_run.try_reserve(self.directory, 4, 3, []) + self.assertIsNotNone(reservation, "the check still holds a slot") + reservation.release() + line = bounded_run._try_lock(os.path.join(self.directory, "line.lock")) + self.assertIsNotNone(line, "the check still holds the line") + os.close(line) + + def test_a_waiter_in_the_line_makes_the_line_busy_and_no_budget_starts(self): + self.hold("line.lock") + lines = self.check(["2G"]) + self.assertTrue(lines[0].endswith(" line=busy"), lines) + self.assertEqual(lines[1], "check budget=2048M slots=1 starts=no") + + def test_a_count_of_slots_that_another_command_takes_at_that_moment_is_not_given(self): + self.hold("reserve.lock") + lines = self.check(["2G"]) + self.assertIn(" free-slots=- ", lines[0]) + self.assertEqual(lines[1], "check budget=2048M slots=1 starts=no") + + def test_each_budget_gets_its_slots_and_its_answer_in_the_order_given(self): + self.hold("slot-000.lock") + self.hold("slot-001.lock") + lines = self.check(["2G", "4096M", "5G"]) + self.assertEqual(lines[1:], [ + "check budget=2048M slots=1 starts=yes", + "check budget=4096M slots=2 starts=yes", + "check budget=5120M slots=3 starts=no", + ]) + + def test_a_budget_starts_only_when_the_free_memory_less_the_unused_budgets_and_the_headroom_holds_it(self): + lines = self.check(["2G", "4G"], available=6000, outstanding=900) + self.assertEqual(lines[0], "check slots=4 slot=2048M free-slots=4 free=6000M unused=900M headroom=1024M line=free") + self.assertEqual(lines[1:], ["check budget=2048M slots=1 starts=yes", "check budget=4096M slots=2 starts=no"]) + + def test_a_budget_starts_when_the_free_memory_cannot_be_read_as_the_wait_does(self): + lines = self.check(["2G"], available=None) + self.assertIn(" free=- ", lines[0]) + self.assertEqual(lines[1], "check budget=2048M slots=1 starts=yes") + + def test_a_budget_larger_than_the_queue_needs_every_slot_and_the_memory_of_the_queue(self): + lines = self.check(["64G"], available=9300) + self.assertEqual(lines[1], "check budget=65536M slots=4 starts=yes") + + def test_counts_the_unused_budgets_beside_the_scope_of_the_probe(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + calls = [] + + def unused(parent, skip): + calls.append(parent) + return 700 + + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ + mock.patch.object(bounded_run, "unused_budget_mib", unused): + self.assertEqual(bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000), 0) + self.assertEqual(calls, ["/sys/fs/cgroup/user.slice/app.slice"]) + self.assertIn(" unused=700M ", self.lines[0]) + + def test_counts_no_unused_budget_without_a_cap(self): + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap") as probe: + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + probe.assert_not_called() + self.assertIn(" unused=- ", self.lines[0]) + + +class CheckArgumentTest(unittest.TestCase): + def test_reads_each_budget_in_order(self): + options = bounded_run.parse_arguments(["--check", "--memory", "6G", "--memory", "512M"]) + self.assertEqual((options.check, options.budgets), (True, [6144, 512])) + + def test_the_check_option_can_come_after_a_budget(self): + self.assertEqual(bounded_run.parse_arguments(["--memory", "2G", "--check"]).budgets, [2048]) + + def test_needs_no_budget(self): + self.assertEqual(bounded_run.parse_arguments(["--check"]).budgets, []) + + def test_a_command_after_the_check_option_is_a_command_of_a_run(self): + options = bounded_run.parse_arguments(["--memory", "2G", "--", "tool", "--check"]) + self.assertEqual((options.check, options.command), (False, ["tool", "--check"])) + + def test_rejects_a_command_and_the_other_options(self): + for arguments in ( + ["--check", "--", "tool"], + ["--check", "--memory", "2G", "--", "tool"], + ["--check", "--cpus", "2"], + ["--check", "--exclusive", "port"], + ["--check", "--measure"], + ["--check", "--measure-rows", "4,2"], + ["--check", "--label", "lint"], + ["--check", "--memory"], + ["--check", "--memory", "six"], + ): + with self.subTest(arguments=arguments): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.parse_arguments(arguments) + + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" @@ -2475,6 +2633,36 @@ def test_a_first_measurement_starts_while_small_commands_keep_arriving(self): bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None, "no hard cap on this machine", ) +class CheckProcessTest(WrapperProcessCase): + def check(self, arguments): + process = subprocess.Popen( + [sys.executable, WRAPPER, "--check"] + arguments, env=self.environ, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + self.processes.append(process) + output, errors = process.communicate(timeout=60) + return process.returncode, output, errors + + def test_prints_the_check_lines_on_the_error_stream_and_exits_0(self): + holder = self.worker("holder", "2G", hold="300") + self.wait_for_event("start", "holder") + code, output, errors = self.check(["--memory", "2G", "--memory", "4G"]) + self.assertEqual((code, output), (0, ""), errors) + self.assertRegex(errors, r"^bounded-run: check slots=2 slot=2048M free-slots=1 free=(\d+M|-) unused=- headroom=1024M line=free\n") + self.assertRegex(errors, r"\nbounded-run: check budget=2048M slots=1 starts=(yes|no)\nbounded-run: check budget=4096M slots=2 starts=no\n$") + holder.kill() + + def test_a_command_starts_at_once_after_the_check(self): + self.assertEqual(self.check([])[0], 0) + self.assertEqual(self.worker("after", "4G", hold="0").wait(timeout=60), 0) + + def test_a_fault_of_the_call_gives_125(self): + code, output, errors = self.check(["--cpus", "2"]) + self.assertEqual(code, 125) + self.assertTrue(errors.startswith("bounded-run: "), errors) + self.assertNotIn("check slots=", errors) + + class HardCapTest(WrapperProcessCase): def setUp(self): super().setUp() From 6747cb2cbad4a6ce91e7e0c470c9181c1e6f49b0 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:11:29 +0100 Subject: [PATCH 02/13] feat(skills/bounding-heavy-commands): name the commands that hold the queue in the check When the queue is full, every session waits and no one can see what holds it. The user has to ask, and the agent has no way to answer: the skill tells it not to look for the process that holds a lock file. The kernel already knows. Each running bounded command is a scope in the slice that the probe finds. The check now prints one held line for each such scope, with its budget, the memory it uses, its age, its working directory, and its command without the prefix that the wrapper adds. A field that cannot be read is '-', and a scope that ends while it is read is skipped. Without the hard cap there are no scopes, so there are no held lines. The skill tells an agent to run the check after a long wait and to name the held commands in its message to the user. It says that the held lines are the way to name what holds the queue, and that a held command belongs to another session or to the user, so the agent never stops it. Refs #57 Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 7 +- .../scripts/bounded_run.py | 104 +++++++++++++--- .../scripts/tests/test_bounded_run.py | 111 +++++++++++++++++- 3 files changed, 204 insertions(+), 18 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 046fcf9..6cc625a 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -60,10 +60,11 @@ A check prints its lines in a fixed form too: ``` bounded-run: check slots= slot=M free-slots= free=M unused=M headroom=M line= +bounded-run: check held unit= budget=M used=M age=s dir= command= bounded-run: check budget=M slots= starts= ``` -The first line gives the slots of the queue and their size, the slots that are free now, the free memory, the unused budgets of the running commands, and the headroom. `line=busy` means that a command waits in the line. Each next line is one `--memory`, in the order given: the slots that it needs, and `starts=yes` when a command of that budget would start now. A `-` means that the check cannot read or count the value at that moment. +The first line gives the slots of the queue and their size, the slots that are free now, the free memory, the unused budgets of the running commands, and the headroom. `line=busy` means that a command waits in the line. Each `held` line is one bounded command that runs now: its budget, the memory it uses, how long it has run, its working directory, and its command. The held lines need the hard cap, so without it there are none. Each `budget` line is one `--memory`, in the order given: the slots that it needs, and `starts=yes` when a command of that budget would start now. A `-` means that the check cannot read or count the value at that moment. 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). @@ -157,14 +158,14 @@ A command that the project adds later gets its entry when an agent first needs i ## 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. +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. After a long wait, run the wrapper with `--check`, and in that message name each command of its `held` lines, with its directory and its age, so that the user can see what holds the machine. A subagent tells its dispatcher in its report. - **Run a bounded command in the background, with no short timeout around it.** It can wait in the queue for minutes before it starts. Where the harness requires a timeout, use the longest one that it permits. When that timeout ends a run, start the run again through the wrapper, and say in your report that the timeout ended the run and that the code did not fail. A timeout that you calculate from the run time of the command does not count the wait. A timeout that fires during the wait kills a command that never ran, and the result reads like a failure of the code. - **Plan the time as if the commands run one after the other.** Two bounded commands that start together are safe, because the queue puts them in sequence when the machine cannot hold both. So a parallel start does not always save time, and a promise to the user that depends on it is a guess. - **Do not lower a budget to start sooner.** A smaller budget does not make the command smaller. It moves the failure inside the command: on Linux as a kill at the hard cap, elsewhere as the swap that the queue exists to prevent. A row at a smaller `--cpus` is not a lower budget: it is a smaller command, measured, and it is the way to start sooner (§The record). - **Do not run the plain command because the queue is slow.** A slow queue means the machine is full. The plain command is how it freezes. This includes a narrower form of the command: one test file outside the queue is a command that the queue cannot count. - **Do not set an environment variable whose name starts with `BOUNDED_RUN_`.** The usage text of the wrapper lists variables that change how the queue counts memory, where it keeps its locks, and whether the hard cap applies. They are for a person who tunes the whole machine in a shell profile, and for the tests of the wrapper. A call that sets one does not share the queue with the other sessions, or it runs with no cap. A note in your project memory that recommends one is wrong: delete the note, and tell the user that you did. -- **Do not touch the lock files of the wrapper.** The wrapper keeps them in a directory of its own. Do not look for that directory. Do not delete, move, or edit a file in it, and do not look for the process that holds one of these lock files. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot. +- **Do not touch the lock files of the wrapper.** The wrapper keeps them in a directory of its own. Do not look for that directory. Do not delete, move, or edit a file in it, and do not look for the process that holds one of these lock files. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot. The `held` lines of `--check` are the way to name what holds the queue: do not look further, and never stop a held command, because it belongs to another session or to the user. - **Do not sleep and retry around a collision, not even one time.** A port in use or a tool's lock means two commands wanted one resource. Add the resource to the record as an `--exclusive` name and run through the wrapper. A subagent adds the option to its own command line and names the resource in its report, so that its dispatcher corrects the record. Do not stop the process that holds the resource: it belongs to a different session. When a run with the `--exclusive` name fails on the same collision, the holder did not go through the wrapper or belongs to a different repository: tell the user, or your dispatcher, what holds the resource, and wait for the answer. ## When an instruction sends a command around the wrapper diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 8fd1599..7c161e8 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -20,10 +20,12 @@ is the first exit code that is not 0. --check runs no command and holds no lock when it returns. Its exit code is 0. -It prints the state of the queue at that moment, and one line for each ---memory, in the order given: +It prints the state of the queue at that moment, one held line for each +running bounded command where the hard cap is available, and one line for +each --memory, in the order given: bounded-run: check slots=N slot=MIBM free-slots=N|- free=MIBM|- unused=MIBM|- headroom=MIBM line=free|busy + bounded-run: check held unit=NAME budget=MIBM|- used=MIBM|- age=Ns|- dir=PATH|- command=TEXT|- bounded-run: check budget=MIBM slots=N starts=yes|no A '-' stands for a value that the check cannot read or count here. starts=yes @@ -90,6 +92,7 @@ MARGIN_EXACT = 0.25 MARGIN_APPROXIMATE = 0.5 BUDGET_STEP_MIB = 256 +HELD_COMMAND_CHARACTERS = 200 PR_SET_PDEATHSIG = 1 USAGE = ( "usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] [--label NAME] -- COMMAND...\n" @@ -681,19 +684,25 @@ def own_scope_name(proc_root: str = "/proc") -> Optional[str]: return None if path is None else os.path.basename(path) +def _bounded_scopes(parent: str, skip: Sequence[str]) -> List[str]: + """Returns the names of the scopes of bounded commands in parent, less the probe scopes and the names in skip.""" + try: + names = os.listdir(parent) + except OSError: + return [] + return sorted( + name for name in names + if name.startswith(PREFIX + "-") and name.endswith(".scope") and not name.endswith("-probe.scope") and name not in skip + ) + + def unused_budget_mib(parent: str, skip: Sequence[str]) -> int: """Returns the part of their budgets that the bounded commands whose scopes are in parent do not use yet. Probe scopes, the scopes named in skip, and scopes with no memory limit add nothing. """ - try: - names = os.listdir(parent) - except OSError: - return 0 unused = 0 - for name in names: - if not name.startswith(PREFIX + "-") or not name.endswith(".scope") or name.endswith("-probe.scope") or name in skip: - continue + for name in _bounded_scopes(parent, skip): try: with open(os.path.join(parent, name, "memory.max")) as handle: limit = handle.read().strip() @@ -735,6 +744,72 @@ def wait_for_scope( return True +def _read_text(path: str) -> Optional[str]: + try: + with open(path, "rb") as handle: + return handle.read().decode("utf-8", "replace") + except OSError: + return None + + +def _process_age_seconds(pid: int, proc_root: str, ticks: int) -> Optional[int]: + stat_text = _read_text(os.path.join(proc_root, str(pid), "stat")) + uptime = _read_text(os.path.join(proc_root, "uptime")) + try: + # The name of the process can hold spaces and ')', so the fields are counted from its last ')'. + start = int(stat_text.rsplit(")", 1)[1].split()[19]) + return max(0, int(float(uptime.split()[0]) - start / ticks)) + except (AttributeError, IndexError, ValueError): + return None + + +def _held_command(pid: int, proc_root: str) -> Optional[str]: + text = _read_text(os.path.join(proc_root, str(pid), "cmdline")) + if not text: + return None + arguments = text.rstrip("\0").split("\0") + if "--inside-cap" in arguments: + at = arguments.index("--inside-cap") + if arguments[at + 3:at + 4] == ["--"]: + arguments = arguments[at + 4:] + # The check prints one line for each command, so a line break inside an argument becomes a space. + return " ".join(" ".join(arguments).split())[:HELD_COMMAND_CHARACTERS] + + +def held_commands(parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None) -> List[str]: + """Returns one text for each running bounded command whose scope is in parent, as the fields of a check line. + + A field that cannot be read is '-'. Probe scopes and the scopes named in skip give no text. + """ + if ticks is None: + ticks = os.sysconf("SC_CLK_TCK") + + def mib(text: Optional[str]) -> str: + return "%dM" % (int(text) // (1024 * 1024)) if text is not None and text.strip().isdigit() else "-" + + held = [] + for name in _bounded_scopes(parent, skip): + directory = os.path.join(parent, name) + limit = _read_text(os.path.join(directory, "memory.max")) + current = _read_text(os.path.join(directory, "memory.current")) + pids = [int(line) for line in (_read_text(os.path.join(directory, "cgroup.procs")) or "").split() if line.isdigit()] + if not os.path.isdir(directory): + # The scope ended while it was read. + continue + # The wrapper starts the first process of the scope, and that process starts the command. + pid = min(pids) if pids else None + age = _process_age_seconds(pid, proc_root, ticks) if pid is not None else None + try: + working = os.readlink(os.path.join(proc_root, str(pid), "cwd")) if pid is not None else None + except OSError: + working = None + command = _held_command(pid, proc_root) if pid is not None else None + held.append("unit=%s budget=%s used=%s age=%s dir=%s command=%s" % ( + name[:-len(".scope")], mib(limit), mib(current), "-" if age is None else "%ds" % age, + working or "-", command or "-")) + return held + + def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]: try: with open(os.path.join(proc_root, str(pid), "cgroup")) as handle: @@ -1251,12 +1326,11 @@ def check( line = _try_lock(os.path.join(directory, "line.lock")) if line is not None: os.close(line) + unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) + choice = None if settings.no_cap else choose_cap_prefix(settings.slot_mib, None, unit, probe_cap) + scopes = scope_parent_directory(choice[1]) if choice is not None else None + skip = [name for name in (own_scope_name(),) if name is not None] if read_outstanding is None: - unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) - choice = None if settings.no_cap else choose_cap_prefix(settings.slot_mib, None, unit, probe_cap) - scopes = scope_parent_directory(choice[1]) if choice is not None else None - skip = [name for name in (own_scope_name(),) if name is not None] - def read_outstanding() -> Optional[int]: return None if scopes is None else unused_budget_mib(scopes, skip) @@ -1273,6 +1347,8 @@ def mib(value: Optional[int]) -> str: log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s headroom=%dM line=%s" % ( count, settings.slot_mib, "-" if free_slots is None else free_slots, mib(available), mib(outstanding), headroom, "free" if line is not None else "busy")) + for held in held_commands(scopes, skip) if scopes is not None else []: + log("check held " + held) for budget in budgets: needed = slots_needed(budget, settings.slot_mib, count) starts = (line is not None and free_slots is not None and free_slots >= needed 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 b80519b..dbf94e5 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1055,6 +1055,92 @@ def sleep(seconds): self.assertEqual(sleeps, [5.0]) +class HeldCommandTest(unittest.TestCase): + """Gives held_commands a slice of the cgroup filesystem and a process filesystem in temporary directories.""" + + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.slice = os.path.join(self.base.name, "app.slice") + self.proc = os.path.join(self.base.name, "proc") + os.makedirs(self.slice) + os.makedirs(self.proc) + Path(self.proc, "uptime").write_text("170.52 300.00\n") + + def scope(self, name, limit=str(4096 * 1024 ** 2), current=str(1024 * 1024 ** 2), pids=("100",)): + directory = os.path.join(self.slice, name) + os.makedirs(directory) + Path(directory, "memory.max").write_text(limit + "\n") + Path(directory, "memory.current").write_text(current + "\n") + Path(directory, "cgroup.procs").write_text("".join(pid + "\n" for pid in pids)) + + def process(self, pid, arguments, start_ticks=5000, cwd="/work/project"): + directory = os.path.join(self.proc, str(pid)) + os.makedirs(directory) + Path(directory, "stat").write_text("%d (python 3) S %s %d 0 0\n" % (pid, " ".join(["0"] * 18), start_ticks)) + Path(directory, "cmdline").write_bytes(b"".join(argument.encode() + b"\0" for argument in arguments)) + os.symlink(cwd, os.path.join(directory, "cwd")) + + def held(self, skip=()): + return bounded_run.held_commands(self.slice, skip, proc_root=self.proc, ticks=100) + + def inside(self, *command): + return ["python3", "/x/bounded_run.py", "--inside-cap", "/l/peak-u", "bounded-run-100-aaaaaa", "--"] + list(command) + + def test_names_the_budget_the_use_the_age_the_directory_and_the_command(self): + self.scope("bounded-run-100-aaaaaa.scope", pids=("105", "100")) + self.process(100, self.inside("sh", "-c", "make test")) + self.process(105, ["make", "test"], start_ticks=9000, cwd="/elsewhere") + self.assertEqual(self.held(), [ + "unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=120s dir=/work/project command=sh -c make test", + ]) + + def test_a_scope_with_no_budget_gives_a_dash(self): + self.scope("bounded-run-100-aaaaaa.scope", limit="max") + self.process(100, self.inside("tool")) + self.assertIn(" budget=- ", self.held()[0]) + + def test_skips_probe_scopes_named_scopes_and_other_units(self): + self.scope("bounded-run-100-aaaaaa-probe.scope") + self.scope("bounded-run-101-bbbbbb.scope") + self.scope("editor-1.scope") + self.scope("bounded-run-102-cccccc.scope") + self.process(100, self.inside("tool")) + held = self.held(skip=["bounded-run-101-bbbbbb.scope"]) + self.assertEqual([line.split()[0] for line in held], ["unit=bounded-run-102-cccccc"]) + + def test_a_process_that_cannot_be_read_gives_dashes(self): + self.scope("bounded-run-100-aaaaaa.scope", pids=("999",)) + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=- dir=- command=-"]) + + def test_a_scope_with_no_process_gives_dashes(self): + self.scope("bounded-run-100-aaaaaa.scope", pids=()) + self.assertTrue(self.held()[0].endswith(" age=- dir=- command=-"), self.held()) + + def test_a_scope_that_ends_while_it_is_read_is_skipped(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, self.inside("tool")) + listing = os.listdir(self.slice) + ["bounded-run-200-dddddd.scope"] + with mock.patch.object(bounded_run.os, "listdir", return_value=listing): + held = self.held() + self.assertEqual([line.split()[0] for line in held], ["unit=bounded-run-100-aaaaaa"]) + + def test_a_long_command_is_cut_and_stays_on_one_line(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, self.inside("sh", "-c", "first\nsecond " + "x" * 300)) + command = self.held()[0].split(" command=", 1)[1] + self.assertEqual(len(command), bounded_run.HELD_COMMAND_CHARACTERS) + self.assertTrue(command.startswith("sh -c first second x"), command) + + def test_a_command_without_the_prefix_of_the_wrapper_is_given_whole(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, ["sleep", "60"]) + self.assertTrue(self.held()[0].endswith(" command=sleep 60"), self.held()) + + def test_no_slice_gives_no_line(self): + self.assertEqual(bounded_run.held_commands(os.path.join(self.base.name, "gone"), (), proc_root=self.proc), []) + + class CapTest(unittest.TestCase): def test_prefix_holds_the_limits(self): self.assertEqual(bounded_run.cap_prefix(6144, 4, "unit-1"), [ @@ -1977,11 +2063,34 @@ def unused(parent, skip): options = bounded_run.parse_arguments(["--check"]) with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ - mock.patch.object(bounded_run, "unused_budget_mib", unused): + mock.patch.object(bounded_run, "unused_budget_mib", unused), \ + mock.patch.object(bounded_run, "held_commands", return_value=[]): self.assertEqual(bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000), 0) self.assertEqual(calls, ["/sys/fs/cgroup/user.slice/app.slice"]) self.assertIn(" unused=700M ", self.lines[0]) + def test_names_each_held_command_after_the_state_line(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + calls = [] + + def held(parent, skip): + calls.append(parent) + return ["unit=bounded-run-7-abcdef budget=4096M used=100M age=5s dir=/w command=tool"] + + options = bounded_run.parse_arguments(["--check", "--memory", "2G"]) + with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ + mock.patch.object(bounded_run, "unused_budget_mib", return_value=0), \ + mock.patch.object(bounded_run, "held_commands", held): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + self.assertEqual(calls, ["/sys/fs/cgroup/user.slice/app.slice"]) + self.assertEqual(self.lines[1], "check held unit=bounded-run-7-abcdef budget=4096M used=100M age=5s dir=/w command=tool") + self.assertTrue(self.lines[2].startswith("check budget=2048M "), self.lines) + + def test_no_held_line_without_a_cap(self): + self.hold("slot-000.lock") + self.assertFalse(any(line.startswith("check held") for line in self.check(["2G"]))) + def test_counts_no_unused_budget_without_a_cap(self): options = bounded_run.parse_arguments(["--check"]) with mock.patch.object(bounded_run, "probe_cap") as probe: From fb8ac72db34d3f27b362ead60201c9366c0b7d28 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:58:18 +0100 Subject: [PATCH 03/13] fix(skills/bounding-heavy-commands): keep the directory of a held command on one line A path name can hold a line break, so a held line of the check could split in two, and the second part could read as a line of its own. The directory now gets the same whitespace folding as the command. 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, 7 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 7c161e8..3feaab8 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -803,6 +803,8 @@ def mib(text: Optional[str]) -> str: working = os.readlink(os.path.join(proc_root, str(pid), "cwd")) if pid is not None else None except OSError: working = None + if working is not None: + working = " ".join(working.split()) command = _held_command(pid, proc_root) if pid is not None else None held.append("unit=%s budget=%s used=%s age=%s dir=%s command=%s" % ( name[:-len(".scope")], mib(limit), mib(current), "-" if age is None else "%ds" % age, 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 dbf94e5..8c1a979 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1132,6 +1132,11 @@ def test_a_long_command_is_cut_and_stays_on_one_line(self): self.assertEqual(len(command), bounded_run.HELD_COMMAND_CHARACTERS) self.assertTrue(command.startswith("sh -c first second x"), command) + def test_a_directory_with_a_line_break_stays_on_one_line(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, self.inside("tool"), cwd="/work/two\nlines") + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=120s dir=/work/two lines command=tool"]) + def test_a_command_without_the_prefix_of_the_wrapper_is_given_whole(self): self.scope("bounded-run-100-aaaaaa.scope") self.process(100, ["sleep", "60"]) From c725e180b634234624d57645490e3b6566ad8325 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:58:18 +0100 Subject: [PATCH 04/13] fix(skills/bounding-heavy-commands): give a subagent the check after a long wait The rules for the wait tell an agent to run the check after a long wait and name the held commands, and a subagent tells its dispatcher. The rule that a dispatch prompt must carry said only to report the length of the wait, so a subagent that follows its prompt did not run the check. 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 6cc625a..84edec6 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -185,7 +185,7 @@ A subagent does not see your project memory. It knows the bounded commands only On a machine on which the wrapper can run, every dispatch prompt for a subagent that will run a heavy command MUST include: 1. The bounded command line for each heavy command, copied from the record, with the `--cpus` and the budget of its default row. When its entry has more than one row, also the `--cpus` and the budget of each row, and its check line with one `--memory` for each row. -2. This rule, in these words: "Run the bounded commands as written. You can make three changes: the `--cpus` and the `--memory` of a row that this prompt gives for the command, a narrower argument at the end of the line, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. When this prompt gives a command more than one row, run its check line before each run, and use the largest row with `starts=yes`, or the default row when no row has it. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited." +2. This rule, in these words: "Run the bounded commands as written. You can make three changes: the `--cpus` and the `--memory` of a row that this prompt gives for the command, a narrower argument at the end of the line, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. When this prompt gives a command more than one row, run its check line before each run, and use the largest row with `starts=yes`, or the default row when no row has it. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited. After a long wait, run the same wrapper with `--check`, and name in your report each command of its `held` lines, with its directory and its age." 3. Each command that an instruction exempts from the wrapper, in its plain form, in a list of its own, with the instruction that exempts it. The rule of item 2 does not apply to that list. An instruction of the user that covers one run goes to the one subagent that does that run, and to no other. Do not dispatch fewer subagents to protect the machine. The queue protects it. Subagents that wait in the queue cost time, not memory. On a machine on which the wrapper cannot run, the next section says how to dispatch. From a2bce5068a046e8bdac92fdf3eaa62660f0ac1ad 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:12:10 +0100 Subject: [PATCH 05/13] fix(skills/bounding-heavy-commands): read --check only where an option can stand The parser took any --check before the '--' as the check option, also when it was the value of another option, such as the name of --exclusive --check. It now skips the value of each option that takes one. Co-Authored-By: Claude Opus 5.5 --- .../bounding-heavy-commands/scripts/bounded_run.py | 14 ++++++++++++-- .../scripts/tests/test_bounded_run.py | 4 ++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 3feaab8..3a5542f 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -81,6 +81,7 @@ PREFIX = "bounded-run" EXIT_WRAPPER = 125 ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE" +VALUE_OPTIONS = ("--memory", "--cpus", "--exclusive", "--measure-rows", "--label") SLOT_MIB = 2048 MINIMUM_RESERVE_MIB = 2048 MINIMUM_HEADROOM_MIB = 1024 @@ -1060,6 +1061,15 @@ def __init__(self) -> None: self.budgets: List[int] = [] +def _check_option_given(flags: Sequence[str]) -> bool: + position = 0 + while position < len(flags): + if flags[position] == "--check": + return True + position += 2 if flags[position] in VALUE_OPTIONS else 1 + return False + + def _parse_check(flags: Sequence[str], has_command: bool) -> Options: options = Options() options.check = True @@ -1082,7 +1092,7 @@ def parse_arguments(argv: Sequence[str]) -> Options: options = Options() arguments = list(argv) split = arguments.index("--") if "--" in arguments else len(arguments) - if "--check" in arguments[:split]: + if _check_option_given(arguments[:split]): return _parse_check(arguments[:split], split < len(arguments)) if "--" not in arguments: raise WrapperError("the '--' before the command is missing\n" + USAGE) @@ -1095,7 +1105,7 @@ def parse_arguments(argv: Sequence[str]) -> Options: if flag == "--measure": options.measure = True continue - if flag not in ("--memory", "--cpus", "--exclusive", "--measure-rows", "--label"): + if flag not in VALUE_OPTIONS: 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)) 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 8c1a979..03fbbf0 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2119,6 +2119,10 @@ def test_a_command_after_the_check_option_is_a_command_of_a_run(self): options = bounded_run.parse_arguments(["--memory", "2G", "--", "tool", "--check"]) self.assertEqual((options.check, options.command), (False, ["tool", "--check"])) + def test_the_value_of_an_option_is_not_the_check_option(self): + options = bounded_run.parse_arguments(["--exclusive", "--check", "--", "tool"]) + self.assertEqual((options.check, options.exclusive, options.command), (False, ["--check"], ["tool"])) + def test_rejects_a_command_and_the_other_options(self): for arguments in ( ["--check", "--", "tool"], From 4387485cf1c64bd034964bfef141a476763d9b7a 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:21:43 +0100 Subject: [PATCH 06/13] fix(skills/bounding-heavy-commands): print the headroom of each budget on its line of the check The first line of the check printed the headroom of a small budget, while each starts answer used the headroom of its own budget, which is 0 for a budget of the whole queue. So a check could print headroom=1024M and starts=yes for a budget that the free memory holds only without that headroom. The headroom now stands on each budget line, and the first line no longer has one. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 6 ++-- .../scripts/bounded_run.py | 16 +++++------ .../scripts/tests/test_bounded_run.py | 28 +++++++++---------- 3 files changed, 25 insertions(+), 25 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 84edec6..ca2fad5 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -59,12 +59,12 @@ bounded-run: row label= cpus= budget=M peak=M exact= exit A check prints its lines in a fixed form too: ``` -bounded-run: check slots= slot=M free-slots= free=M unused=M headroom=M line= +bounded-run: check slots= slot=M free-slots= free=M unused=M line= bounded-run: check held unit= budget=M used=M age=s dir= command= -bounded-run: check budget=M slots= starts= +bounded-run: check budget=M slots= headroom=M starts= ``` -The first line gives the slots of the queue and their size, the slots that are free now, the free memory, the unused budgets of the running commands, and the headroom. `line=busy` means that a command waits in the line. Each `held` line is one bounded command that runs now: its budget, the memory it uses, how long it has run, its working directory, and its command. The held lines need the hard cap, so without it there are none. Each `budget` line is one `--memory`, in the order given: the slots that it needs, and `starts=yes` when a command of that budget would start now. A `-` means that the check cannot read or count the value at that moment. +The first line gives the slots of the queue and their size, the slots that are free now, the free memory, and the unused budgets of the running commands. `line=busy` means that a command waits in the line. Each `held` line is one bounded command that runs now: its budget, the memory it uses, how long it has run, its working directory, and its command. The held lines need the hard cap, so without it there are none. Each `budget` line is one `--memory`, in the order given: the slots that it needs, the headroom that the wait keeps free beside that budget, and `starts=yes` when a command of that budget would start now. A `-` means that the check cannot read or count the value at that moment. 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). diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 3a5542f..100d980 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -24,9 +24,9 @@ running bounded command where the hard cap is available, and one line for each --memory, in the order given: - bounded-run: check slots=N slot=MIBM free-slots=N|- free=MIBM|- unused=MIBM|- headroom=MIBM line=free|busy - bounded-run: check held unit=NAME budget=MIBM|- used=MIBM|- age=Ns|- dir=PATH|- command=TEXT|- - bounded-run: check budget=MIBM slots=N starts=yes|no + bounded-run: check slots=N slot=M free-slots=N|- free=M|- unused=M|- line=free|busy + bounded-run: check held unit=NAME budget=M|- used=M|- age=Ns|- dir=PATH|- command=TEXT|- + bounded-run: check budget=M slots=N headroom=M starts=yes|no A '-' stands for a value that the check cannot read or count here. starts=yes means that a run of that budget would start now. It is not a reservation. @@ -1351,21 +1351,21 @@ def read_outstanding() -> Optional[int]: outstanding = read_outstanding() else: available, outstanding = settings.free_mib, None - headroom = headroom_mib(settings.total_mib, 0, most) def mib(value: Optional[int]) -> str: return "-" if value is None else "%dM" % value - log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s headroom=%dM line=%s" % ( + log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s line=%s" % ( count, settings.slot_mib, "-" if free_slots is None else free_slots, mib(available), mib(outstanding), - headroom, "free" if line is not None else "busy")) + "free" if line is not None else "busy")) for held in held_commands(scopes, skip) if scopes is not None else []: log("check held " + held) for budget in budgets: needed = slots_needed(budget, settings.slot_mib, count) + headroom = headroom_mib(settings.total_mib, min(budget, most), most) starts = (line is not None and free_slots is not None and free_slots >= needed - and memory_fits(min(budget, most), available, outstanding, headroom_mib(settings.total_mib, min(budget, most), most))) - log("check budget=%dM slots=%d starts=%s" % (budget, needed, "yes" if starts else "no")) + and memory_fits(min(budget, most), available, outstanding, headroom)) + log("check budget=%dM slots=%d headroom=%dM starts=%s" % (budget, needed, headroom, "yes" if starts else "no")) return 0 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 03fbbf0..91ddce6 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1994,17 +1994,17 @@ def check(self, budgets=(), available=16384, outstanding=None): def test_reports_the_slots_the_memory_and_the_line(self): self.assertEqual(self.check(), [ - "check slots=4 slot=2048M free-slots=4 free=16384M unused=- headroom=1024M line=free", + "check slots=4 slot=2048M free-slots=4 free=16384M unused=- line=free", ]) def test_a_budget_of_the_whole_queue_starts_when_the_memory_of_the_queue_is_free(self): - self.assertEqual(self.check(["8G"], available=8192)[-1], "check budget=8192M slots=4 starts=yes") + self.assertEqual(self.check(["8G"], available=8192)[-1], "check budget=8192M slots=4 headroom=0M starts=yes") def test_the_free_memory_for_the_tests_replaces_the_measured_one(self): self.environ["BOUNDED_RUN_FREE_MIB"] = "4096" lines = self.check(["2G"], available=0, outstanding=65536) self.assertIn(" free=4096M unused=- ", lines[0]) - self.assertEqual(lines[-1], "check budget=2048M slots=1 starts=yes") + self.assertEqual(lines[-1], "check budget=2048M slots=1 headroom=1024M starts=yes") def test_counts_the_slots_that_running_commands_hold(self): self.hold("slot-000.lock") @@ -2025,37 +2025,37 @@ def test_a_waiter_in_the_line_makes_the_line_busy_and_no_budget_starts(self): self.hold("line.lock") lines = self.check(["2G"]) self.assertTrue(lines[0].endswith(" line=busy"), lines) - self.assertEqual(lines[1], "check budget=2048M slots=1 starts=no") + self.assertEqual(lines[1], "check budget=2048M slots=1 headroom=1024M starts=no") def test_a_count_of_slots_that_another_command_takes_at_that_moment_is_not_given(self): self.hold("reserve.lock") lines = self.check(["2G"]) self.assertIn(" free-slots=- ", lines[0]) - self.assertEqual(lines[1], "check budget=2048M slots=1 starts=no") + self.assertEqual(lines[1], "check budget=2048M slots=1 headroom=1024M starts=no") def test_each_budget_gets_its_slots_and_its_answer_in_the_order_given(self): self.hold("slot-000.lock") self.hold("slot-001.lock") lines = self.check(["2G", "4096M", "5G"]) self.assertEqual(lines[1:], [ - "check budget=2048M slots=1 starts=yes", - "check budget=4096M slots=2 starts=yes", - "check budget=5120M slots=3 starts=no", + "check budget=2048M slots=1 headroom=1024M starts=yes", + "check budget=4096M slots=2 headroom=1024M starts=yes", + "check budget=5120M slots=3 headroom=1024M starts=no", ]) def test_a_budget_starts_only_when_the_free_memory_less_the_unused_budgets_and_the_headroom_holds_it(self): lines = self.check(["2G", "4G"], available=6000, outstanding=900) - self.assertEqual(lines[0], "check slots=4 slot=2048M free-slots=4 free=6000M unused=900M headroom=1024M line=free") - self.assertEqual(lines[1:], ["check budget=2048M slots=1 starts=yes", "check budget=4096M slots=2 starts=no"]) + self.assertEqual(lines[0], "check slots=4 slot=2048M free-slots=4 free=6000M unused=900M line=free") + self.assertEqual(lines[1:], ["check budget=2048M slots=1 headroom=1024M starts=yes", "check budget=4096M slots=2 headroom=1024M starts=no"]) def test_a_budget_starts_when_the_free_memory_cannot_be_read_as_the_wait_does(self): lines = self.check(["2G"], available=None) self.assertIn(" free=- ", lines[0]) - self.assertEqual(lines[1], "check budget=2048M slots=1 starts=yes") + self.assertEqual(lines[1], "check budget=2048M slots=1 headroom=1024M starts=yes") def test_a_budget_larger_than_the_queue_needs_every_slot_and_the_memory_of_the_queue(self): lines = self.check(["64G"], available=9300) - self.assertEqual(lines[1], "check budget=65536M slots=4 starts=yes") + self.assertEqual(lines[1], "check budget=65536M slots=4 headroom=0M starts=yes") def test_counts_the_unused_budgets_beside_the_scope_of_the_probe(self): self.environ.pop("BOUNDED_RUN_NO_CAP") @@ -2766,8 +2766,8 @@ def test_prints_the_check_lines_on_the_error_stream_and_exits_0(self): self.wait_for_event("start", "holder") code, output, errors = self.check(["--memory", "2G", "--memory", "4G"]) self.assertEqual((code, output), (0, ""), errors) - self.assertRegex(errors, r"^bounded-run: check slots=2 slot=2048M free-slots=1 free=(\d+M|-) unused=- headroom=1024M line=free\n") - self.assertRegex(errors, r"\nbounded-run: check budget=2048M slots=1 starts=(yes|no)\nbounded-run: check budget=4096M slots=2 starts=no\n$") + self.assertRegex(errors, r"^bounded-run: check slots=2 slot=2048M free-slots=1 free=(\d+M|-) unused=- line=free\n") + self.assertRegex(errors, r"\nbounded-run: check budget=2048M slots=1 headroom=1024M starts=(yes|no)\nbounded-run: check budget=4096M slots=2 headroom=0M starts=no\n$") holder.kill() def test_a_command_starts_at_once_after_the_check(self): From 8294f57cb689fc240965c37b70fcd64202d38f51 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:21:43 +0100 Subject: [PATCH 07/13] fix(skills/bounding-heavy-commands): read the unused budgets before the free memory in the check The wait reads them in this order, so that a command that grows between the two reads can only make the free memory look smaller. The check now reads them in the same order, so its answer does not start a command that the wait would hold. 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 100d980..c6b17d0 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1347,8 +1347,8 @@ def read_outstanding() -> Optional[int]: return None if scopes is None else unused_budget_mib(scopes, skip) if settings.free_mib is None: - available = read_available() outstanding = read_outstanding() + available = read_available() else: available, outstanding = settings.free_mib, None From 11a2a75a9464e401703519ecc8b350262c5ff469 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:32:35 +0100 Subject: [PATCH 08/13] fix(skills/bounding-heavy-commands): put the hard-cap skip back on the hard-cap tests The process tests of the check went in between the skip decorator and HardCapTest. So the check tests, which run with no cap, were skipped where no cap exists, and the hard-cap tests ran there and failed. Co-Authored-By: Claude Opus 5.5 --- .../scripts/tests/test_bounded_run.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 91ddce6..6a67ff6 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2747,10 +2747,6 @@ def test_a_first_measurement_starts_while_small_commands_keep_arriving(self): ) -@unittest.skipUnless( - bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None, - "no hard cap on this machine", -) class CheckProcessTest(WrapperProcessCase): def check(self, arguments): process = subprocess.Popen( @@ -2781,6 +2777,10 @@ def test_a_fault_of_the_call_gives_125(self): self.assertNotIn("check slots=", errors) +@unittest.skipUnless( + bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None, + "no hard cap on this machine", +) class HardCapTest(WrapperProcessCase): def setUp(self): super().setUp() From c3f0ef70860933dfec8ebe4a22ca9949ea46e541 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:32:35 +0100 Subject: [PATCH 09/13] fix(skills/bounding-heavy-commands): count the larger of two unused-budget reads around the free memory in the check The wait now reads the unused budgets before and after the free memory and counts the larger value. The check does the same, so its answer does not start a command that the wait would hold. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 4 +++- .../scripts/tests/test_bounded_run.py | 8 +++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index c6b17d0..f3261c2 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1347,8 +1347,10 @@ def read_outstanding() -> Optional[int]: return None if scopes is None else unused_budget_mib(scopes, skip) if settings.free_mib is None: - outstanding = read_outstanding() + before = read_outstanding() available = read_available() + after = read_outstanding() + outstanding = None if before is None or after is None else max(before, after) else: available, outstanding = settings.free_mib, None 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 6a67ff6..cf66e82 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2057,6 +2057,12 @@ def test_a_budget_larger_than_the_queue_needs_every_slot_and_the_memory_of_the_q lines = self.check(["64G"], available=9300) self.assertEqual(lines[1], "check budget=65536M slots=4 headroom=0M starts=yes") + def test_counts_the_larger_of_the_unused_budgets_read_before_and_after_the_free_memory(self): + unused = [100, 900] + options = bounded_run.parse_arguments(["--check"]) + bounded_run.check(options.budgets, self.environ, read_available=lambda: 6000, read_outstanding=lambda: unused.pop(0)) + self.assertIn(" unused=900M ", self.lines[0]) + def test_counts_the_unused_budgets_beside_the_scope_of_the_probe(self): self.environ.pop("BOUNDED_RUN_NO_CAP") output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" @@ -2071,7 +2077,7 @@ def unused(parent, skip): mock.patch.object(bounded_run, "unused_budget_mib", unused), \ mock.patch.object(bounded_run, "held_commands", return_value=[]): self.assertEqual(bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000), 0) - self.assertEqual(calls, ["/sys/fs/cgroup/user.slice/app.slice"]) + self.assertEqual(set(calls), {"/sys/fs/cgroup/user.slice/app.slice"}) self.assertIn(" unused=700M ", self.lines[0]) def test_names_each_held_command_after_the_state_line(self): From 696a5d0e6a693461ab481d3ce0057c6c7f380e83 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:42:58 +0100 Subject: [PATCH 10/13] fix(skills/bounding-heavy-commands): print a control character of a held command as a question mark The held lines of the check folded whitespace but kept other control characters, so an argument or a path with a terminal escape sequence went to the terminal as it was and could change what the check showed. Each character that is not printable is now a question mark. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 11 ++++++++--- .../scripts/tests/test_bounded_run.py | 5 +++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index f3261c2..6d56c99 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -764,6 +764,12 @@ def _process_age_seconds(pid: int, proc_root: str, ticks: int) -> Optional[int]: return None +def _one_line(text: str) -> str: + # The check prints one line for each command: a line break in an argument or a path would split the line, + # and a control character would act on the terminal. + return "".join(character if character.isprintable() else "?" for character in " ".join(text.split())) + + def _held_command(pid: int, proc_root: str) -> Optional[str]: text = _read_text(os.path.join(proc_root, str(pid), "cmdline")) if not text: @@ -773,8 +779,7 @@ def _held_command(pid: int, proc_root: str) -> Optional[str]: at = arguments.index("--inside-cap") if arguments[at + 3:at + 4] == ["--"]: arguments = arguments[at + 4:] - # The check prints one line for each command, so a line break inside an argument becomes a space. - return " ".join(" ".join(arguments).split())[:HELD_COMMAND_CHARACTERS] + return _one_line(" ".join(arguments))[:HELD_COMMAND_CHARACTERS] def held_commands(parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None) -> List[str]: @@ -805,7 +810,7 @@ def mib(text: Optional[str]) -> str: except OSError: working = None if working is not None: - working = " ".join(working.split()) + working = _one_line(working) command = _held_command(pid, proc_root) if pid is not None else None held.append("unit=%s budget=%s used=%s age=%s dir=%s command=%s" % ( name[:-len(".scope")], mib(limit), mib(current), "-" if age is None else "%ds" % age, 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 cf66e82..9cdaa47 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1137,6 +1137,11 @@ def test_a_directory_with_a_line_break_stays_on_one_line(self): self.process(100, self.inside("tool"), cwd="/work/two\nlines") self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=120s dir=/work/two lines command=tool"]) + def test_control_characters_of_the_command_and_the_directory_become_question_marks(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, self.inside("printf", "\x1b[2Jdone"), cwd="/work/\x1b[31mred") + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=120s dir=/work/?[31mred command=printf ?[2Jdone"]) + def test_a_command_without_the_prefix_of_the_wrapper_is_given_whole(self): self.scope("bounded-run-100-aaaaaa.scope") self.process(100, ["sleep", "60"]) From 6a01bb4eaea9114998c7c4676d166e61571f5d5b 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:04:28 +0100 Subject: [PATCH 11/13] fix(skills/bounding-heavy-commands): name the command that a check runs inside among the held commands The check skipped its own scope for the held lines as it does for the count of unused budgets. So a check run from inside a bounded command did not name that command, although the held lines name every running bounded command. The held lines now skip only the probe scopes. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 2 +- .../scripts/tests/test_bounded_run.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 6d56c99..1fc2a32 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1365,7 +1365,7 @@ def mib(value: Optional[int]) -> str: log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s line=%s" % ( count, settings.slot_mib, "-" if free_slots is None else free_slots, mib(available), mib(outstanding), "free" if line is not None else "busy")) - for held in held_commands(scopes, skip) if scopes is not None else []: + for held in held_commands(scopes, ()) if scopes is not None else []: log("check held " + held) for budget in budgets: needed = slots_needed(budget, settings.slot_mib, count) 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 9cdaa47..af175ed 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2103,6 +2103,23 @@ def held(parent, skip): self.assertEqual(self.lines[1], "check held unit=bounded-run-7-abcdef budget=4096M used=100M age=5s dir=/w command=tool") self.assertTrue(self.lines[2].startswith("check budget=2048M "), self.lines) + def test_a_check_inside_a_bounded_command_names_that_command_too(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + skips = [] + + def held(parent, skip): + skips.append(list(skip)) + return [] + + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ + mock.patch.object(bounded_run, "own_scope_name", return_value="bounded-run-2-111111.scope"), \ + mock.patch.object(bounded_run, "unused_budget_mib", return_value=0), \ + mock.patch.object(bounded_run, "held_commands", held): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + self.assertEqual(skips, [[]]) + def test_no_held_line_without_a_cap(self): self.hold("slot-000.lock") self.assertFalse(any(line.startswith("check held") for line in self.check(["2G"]))) From ebcc7d973d76f860bf5f4f95d62846fed83c83da 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:55:45 +0100 Subject: [PATCH 12/13] fix(skills/bounding-heavy-commands): read the queue state of the check after the cap probe The check counted the free slots and read the line before it probed the cap, and a probe can take up to 15 seconds per try. The slots and the line could then be half a minute old when the check answered. The probe now comes first. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 5 +++-- .../scripts/tests/test_bounded_run.py | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 1fc2a32..65075d5 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1338,13 +1338,14 @@ def check( uid = os.getuid() directory = lock_directory(environ, uid) ensure_lock_directory(directory, uid) + unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) + # The probe can take seconds, so the state of the queue is read after it. + choice = None if settings.no_cap else choose_cap_prefix(settings.slot_mib, None, unit, probe_cap) # A waiter tries for slots only while it holds the turn lock, so a count under that lock never makes a free slot look held to it. free_slots = _free_slots(directory, count, wait=False) line = _try_lock(os.path.join(directory, "line.lock")) if line is not None: os.close(line) - unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) - choice = None if settings.no_cap else choose_cap_prefix(settings.slot_mib, None, unit, probe_cap) scopes = scope_parent_directory(choice[1]) if choice is not None else None skip = [name for name in (own_scope_name(),) if name is not None] if read_outstanding is None: 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 af175ed..c3dca13 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2120,6 +2120,25 @@ def held(parent, skip): bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) self.assertEqual(skips, [[]]) + def test_the_slots_and_the_line_are_read_after_the_cap_probe(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + events = [] + real_free_slots = bounded_run._free_slots + + def probe(prefix): + events.append("probe") + return None + + def free_slots(*arguments, **keywords): + events.append("slots") + return real_free_slots(*arguments, **keywords) + + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap", probe), mock.patch.object(bounded_run, "_free_slots", free_slots): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + self.assertEqual(events[-1], "slots") + self.assertIn("probe", events) + def test_no_held_line_without_a_cap(self): self.hold("slot-000.lock") self.assertFalse(any(line.startswith("check held") for line in self.check(["2G"]))) From 60c2cf141cb2e75a5411e643efb256972b52b4f6 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 10:04:28 +0100 Subject: [PATCH 13/13] fix(skills/bounding-heavy-commands): count the scope that a check runs in among the unused budgets A check run from inside a bounded command left that command's unused budget out, so it could answer starts=yes where a wrapper that starts on its own counts that budget and waits. The check now counts every bounded scope. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 4 ++-- .../scripts/tests/test_bounded_run.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 65075d5..ad2b6c7 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1347,10 +1347,10 @@ def check( if line is not None: os.close(line) scopes = scope_parent_directory(choice[1]) if choice is not None else None - skip = [name for name in (own_scope_name(),) if name is not None] if read_outstanding is None: + # A wrapper that starts on its own counts every bounded scope, also the one that this check runs in. def read_outstanding() -> Optional[int]: - return None if scopes is None else unused_budget_mib(scopes, skip) + return None if scopes is None else unused_budget_mib(scopes, ()) if settings.free_mib is None: before = read_outstanding() 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 c3dca13..7e9b38d 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2103,6 +2103,23 @@ def held(parent, skip): self.assertEqual(self.lines[1], "check held unit=bounded-run-7-abcdef budget=4096M used=100M age=5s dir=/w command=tool") self.assertTrue(self.lines[2].startswith("check budget=2048M "), self.lines) + def test_a_check_inside_a_bounded_command_counts_its_unused_budget_too(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + skips = [] + + def unused(parent, skip): + skips.append(list(skip)) + return 0 + + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ + mock.patch.object(bounded_run, "own_scope_name", return_value="bounded-run-2-111111.scope"), \ + mock.patch.object(bounded_run, "unused_budget_mib", unused), \ + mock.patch.object(bounded_run, "held_commands", return_value=[]): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + self.assertEqual(skips, [[], []]) + def test_a_check_inside_a_bounded_command_names_that_command_too(self): self.environ.pop("BOUNDED_RUN_NO_CAP") output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n"