From eee18aa53567aca86689ba1699ca03455e487945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:05:45 +0100 Subject: [PATCH 01/15] feat(skills/bounding-heavy-commands): hold a run file while a bounded command runs (#84) Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 45 +++++++++++++++++ .../scripts/tests/test_bounded_run.py | 49 ++++++++++++++++++- 2 files changed, 93 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 8800161..a8041b6 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -405,6 +405,11 @@ def exclusive_file_name(repository: str, name: str) -> str: return "exclusive-%s-%s.lock" % (repository, name) +def run_file_name(unit: str) -> str: + """Returns the name of the file that a bounded command holds locked while it runs.""" + return "run-%s.lock" % unit + + class Reservation: def __init__(self, descriptors: Sequence[int]) -> None: self.descriptors = list(descriptors) @@ -463,6 +468,32 @@ def _try_lock(path: str) -> Optional[int]: return _lock(path, wait=False) +def running_commands(directory: str) -> int: + """Returns the number of bounded commands that run now: the run files that a process holds locked. + + A run file that no process holds is left over from a wrapper that was killed, and is removed. + """ + try: + names = os.listdir(directory) + except OSError: + return 0 + running = 0 + for name in names: + if not (name.startswith("run-") and name.endswith(".lock")): + continue + path = os.path.join(directory, name) + descriptor = _try_lock(path) + if descriptor is None: + running += 1 + continue + try: + os.unlink(path) + except OSError: + pass + os.close(descriptor) + return running + + def _lock_error(path: str, error: OSError) -> WrapperError: error_text = error.strerror if error.strerror else str(error) return WrapperError("cannot lock %s: %s. The lock directory must be on a filesystem that supports file locks." % (path, error_text)) @@ -1454,7 +1485,14 @@ def unlock_memory() -> None: while memory_lock: os.close(memory_lock.pop()) + run_path = os.path.join(directory, run_file_name(unit)) + run_lock: List[int] = [] + def on_start(pid: int) -> None: + # Taken before the memory lock is released, so a waiter that counts under that lock sees this command. + descriptor = _try_lock(run_path) + if descriptor is not None: + run_lock.append(descriptor) start_tracker(pid) if scopes is not None and memory_lock: if not wait_for_scope(scopes, unit, SCOPE_WAIT_SECONDS): @@ -1475,6 +1513,13 @@ def on_start(pid: int) -> None: held = trackers[0].held if trackers else None finally: unlock_memory() + if run_lock: + try: + os.unlink(run_path) + except OSError: + pass + while run_lock: + os.close(run_lock.pop()) if capped: reported = read_peak_file(peak_file) reservation.release() 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 b6a8241..3bcb61b 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -692,6 +692,35 @@ def test_two_directories_have_different_ids(self): self.assertNotEqual(bounded_run.repository_id(first), bounded_run.repository_id(second)) +class RunningCountTest(unittest.TestCase): + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.directory = self.base.name + + def hold(self, name): + descriptor = bounded_run._try_lock(os.path.join(self.directory, name)) + self.addCleanup(os.close, descriptor) + + def test_counts_no_command_in_an_empty_directory(self): + self.assertEqual(bounded_run.running_commands(self.directory), 0) + + def test_counts_each_run_file_that_a_process_holds(self): + self.hold(bounded_run.run_file_name("bounded-run-1-000001")) + self.hold(bounded_run.run_file_name("bounded-run-2-000002")) + self.assertEqual(bounded_run.running_commands(self.directory), 2) + + def test_slot_files_are_not_running_commands(self): + self.hold("slot-000.lock") + self.assertEqual(bounded_run.running_commands(self.directory), 0) + + def test_a_run_file_that_no_process_holds_is_removed_and_not_counted(self): + path = os.path.join(self.directory, bounded_run.run_file_name("bounded-run-3-000003")) + open(path, "w").close() + self.assertEqual(bounded_run.running_commands(self.directory), 0) + self.assertFalse(os.path.exists(path)) + + class MemoryReadTest(unittest.TestCase): def test_reads_the_available_memory_of_meminfo(self): text = "MemTotal: 32000000 kB\nMemFree: 1000000 kB\nMemAvailable: 8388608 kB\n" @@ -1979,6 +2008,24 @@ def test_the_wait_counts_no_unused_budget_without_a_cgroup_version_2(self): self.assertIsNone(self.wait_arguments("")["read_outstanding"]()) + def test_the_command_holds_a_run_file_while_it_runs_and_removes_it_after(self): + seen = [] + + def fake_run_command(command, environ, on_start=None): + on_start(os.getpid()) + seen.append(bounded_run.running_commands(self.directory)) + return 0, 0 + + options = bounded_run.Options() + options.memory = "1G" + options.command = [sys.executable, "-c", "pass"] + with mock.patch.object(bounded_run, "probe_cap", return_value=None), \ + mock.patch.object(bounded_run, "run_command", fake_run_command): + self.assertEqual(bounded_run.bounded(options, self.environ), 0) + self.assertEqual(seen, [1]) + self.assertEqual([name for name in os.listdir(self.directory) if name.startswith("run-")], []) + + class MeasuredRowTest(unittest.TestCase): """Calls bounded() in this process, with run_command replaced by a stub and no hard cap. @@ -2846,7 +2893,7 @@ def test_the_command_does_not_inherit_the_locks(self): ) process = self.wrapper(["--memory", "4G", "--exclusive", "port"], [sys.executable, "-c", script]) output, errors = process.communicate(timeout=60) - self.assertEqual(output, "locks 6 inherited 0\n", errors) + self.assertEqual(output, "locks 7 inherited 0\n", errors) def test_commands_with_the_same_exclusive_name_take_turns(self): workers = [self.worker("w%d" % index, "2G", hold="0.3", options=["--exclusive", "port-8080"]) for index in range(3)] # brief; the test waits for each to end From 0dec2ab24b683cb8745b1d4db7a758038656ce72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:06:38 +0100 Subject: [PATCH 02/15] feat(skills/bounding-heavy-commands): compute the largest budget that fits now (#84) Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 9 +++++++ .../scripts/tests/test_bounded_run.py | 27 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index a8041b6..f417991 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -658,6 +658,15 @@ def memory_fits(budget_mib: int, available: Optional[int], outstanding: Optional return available is None or available - (outstanding or 0) - headroom_mib >= budget_mib +def largest_fit_mib(available: int, outstanding: Optional[int], total_mib: int, queue_mib: int) -> int: + """Returns the largest budget, in steps of BUDGET_STEP_MIB, that would start now with its own headroom, or 0.""" + free = available - (outstanding or 0) + budget = min(queue_mib, max(0, free)) // BUDGET_STEP_MIB * BUDGET_STEP_MIB + while budget > 0 and not memory_fits(budget, free, None, headroom_mib(total_mib, budget, queue_mib)): + budget -= BUDGET_STEP_MIB + return budget + + 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, 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 3bcb61b..c243816 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -984,6 +984,33 @@ def test_the_budget_and_the_headroom_never_need_more_than_the_queue(self): self.assertEqual(bounded_run.headroom_mib(27703, 19000, 20480), 1480) +class FitTest(unittest.TestCase): + # 28000 MiB machine: reserve 7000, queue 20480, headroom 2800 below the queue. + def fit(self, available, outstanding=None): + return bounded_run.largest_fit_mib(available, outstanding, 28000, 20480) + + def test_the_budget_and_its_headroom_fit_in_the_free_memory(self): + self.assertEqual(self.fit(14000), 11008) + + def test_each_value_starts_and_the_next_step_does_not(self): + for available in (1500, 4000, 14000, 21000): + with self.subTest(available=available): + fits = self.fit(available) + headroom = bounded_run.headroom_mib(28000, fits, 20480) + self.assertTrue(fits == 0 or bounded_run.memory_fits(fits, available, None, headroom)) + larger = fits + bounded_run.BUDGET_STEP_MIB + self.assertFalse(larger <= 20480 and bounded_run.memory_fits(larger, available, None, bounded_run.headroom_mib(28000, larger, 20480))) + + def test_nothing_fits_below_the_headroom(self): + self.assertEqual(self.fit(2000), 0) + + def test_the_whole_queue_needs_no_headroom(self): + self.assertEqual(self.fit(20480), 20480) + + def test_the_unused_budgets_are_not_free(self): + self.assertEqual(self.fit(14000, outstanding=4000), self.fit(10000)) + + class UnusedBudgetTest(unittest.TestCase): """Gives unused_budget_mib a slice of the cgroup filesystem in a temporary directory.""" From 22cfbf34e4243dee9dc6b0faa9be632bdbf981c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:07:21 +0100 Subject: [PATCH 03/15] feat(skills/bounding-heavy-commands): stop the memory wait when no bounded command runs (#84) Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 19 ++++++++++-- .../scripts/tests/test_bounded_run.py | 29 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index f417991..c298508 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -667,10 +667,20 @@ def largest_fit_mib(available: int, outstanding: Optional[int], total_mib: int, return budget +class NoMemory(Exception): + """The budget does not fit in the free memory, and no bounded command runs that can free it.""" + + def __init__(self, available: int, outstanding: Optional[int]) -> None: + super().__init__("no memory") + self.available = available + self.outstanding = outstanding + + 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, read_outstanding: Callable[[], Optional[int]] = lambda: None, + read_running: Callable[[], Optional[int]] = lambda: None, sleep: Callable[[float], None] = time.sleep, lock: Callable[[], None] = lambda: None, unlock: Callable[[], None] = lambda: None, @@ -678,8 +688,10 @@ def wait_for_memory( ) -> None: """Returns when the free memory, less the unused budgets of running commands and the headroom, holds the budget. - There is no time limit, so the call can block for as long as the machine is full. Returns at once when - the free memory cannot be read. read_outstanding gives None where the unused budgets cannot be counted. + There is no time limit while another bounded command runs, so the call can block for as long as the machine + is full. Raises NoMemory, with lock released, when none runs, because then nothing in the queue frees memory. + read_running gives the number of bounded commands that run, or None where it is not known: the call waits. + Returns at once when the free memory cannot be read. read_outstanding gives None where the unused budgets cannot be counted. The call returns with lock held: the caller calls unlock once the new command counts in read_outstanding. """ started = clock() @@ -700,6 +712,9 @@ def wait_for_memory( if memory_fits(budget_mib, available, outstanding, headroom_mib): log(state + "; starting") return + if read_running() == 0: + unlock() + raise NoMemory(available, outstanding) waited = clock() - started if next_line is None or waited >= next_line: log(state + ("; waiting" if next_line is None else "; still waiting after %ds" % waited)) 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 c243816..499d1ca 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -970,6 +970,35 @@ def test_a_line_of_the_wait_says_when_the_unused_budgets_are_not_counted(self): ) + def test_stops_when_the_memory_is_not_free_and_no_bounded_command_runs(self): + with self.assertRaises(bounded_run.NoMemory) as raised: + bounded_run.wait_for_memory(4096, 300, 5.0, read_available=lambda: 1000, read_running=lambda: 0, + sleep=lambda seconds: self.fail("waits")) + self.assertEqual(raised.exception.available, 1000) + + def test_waits_while_another_bounded_command_runs(self): + readings = [1000, 5000] + sleeps = [] + bounded_run.wait_for_memory(4096, 300, 5.0, read_available=lambda: readings.pop(0), read_running=lambda: 1, + sleep=sleeps.append) + self.assertEqual(sleeps, [5.0]) + + def test_starts_when_the_memory_is_free_and_no_bounded_command_runs(self): + bounded_run.wait_for_memory(4096, 300, 5.0, read_available=lambda: 8000, read_running=lambda: 0, + sleep=lambda seconds: self.fail("waits")) + + def test_starts_when_the_memory_is_not_readable_and_no_bounded_command_runs(self): + bounded_run.wait_for_memory(4096, 300, 5.0, read_available=lambda: None, read_running=lambda: 0, + sleep=lambda seconds: self.fail("waits")) + + def test_stops_with_the_lock_released(self): + events = [] + with self.assertRaises(bounded_run.NoMemory): + bounded_run.wait_for_memory(4096, 300, 5.0, read_available=lambda: 1000, read_running=lambda: 0, + lock=lambda: events.append("lock"), unlock=lambda: events.append("unlock")) + self.assertEqual(events, ["lock", "unlock"]) + + class HeadroomTest(unittest.TestCase): def test_a_tenth_of_the_memory(self): self.assertEqual(bounded_run.headroom_mib(27703, 2048, 20480), 2770) From 18cd48b45170e3817960bc00530b94219d95f644 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:07:35 +0100 Subject: [PATCH 04/15] fix(skills/bounding-heavy-commands): tell the agent what to do when the wrapper exits 75 (#84) Exit code 75 means that no other bounded command ran, so programs outside the queue hold the memory and the same budget fails again. The skill now gives the next move: the largest recorded row within fits, or a report to the user for a measurement or when no row fits. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 121beb0..d354364 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -48,7 +48,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--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: +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. While another bounded command runs, 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. When no other bounded command runs, nothing in the queue can free memory, so the wrapper does not wait. It prints `bounded-run: no-memory budget=M free=M headroom=M fits=M`, releases its slots, and exits with code 75 without starting the command (§Rules for the wait). Each line that the wrapper prints starts with `bounded-run:`. A measurement also prints one row line, in a fixed form: ``` bounded-run: row label= cpus= budget=M peak=M held=M|- exact= exit= @@ -59,12 +59,12 @@ bounded-run: row label= cpus= budget=M peak=M held=M|- exact=< A check prints its lines in a fixed form too: ``` -bounded-run: check slots= slot=M free-slots= free=M unused=M cpus= cpus-used= cpus-headroom= cpus-free= line= +bounded-run: check slots= slot=M free-slots= free=M unused=M cpus= cpus-used= cpus-headroom= cpus-free= line= fits=M bounded-run: check held unit= budget=M used=M cpus= age=s dir= command= 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, the processors of the machine, the processors that the running bounded commands can use together (`cpus-used`), the processors that the check keeps for the programs outside the queue (`cpus-headroom`, a tenth of `cpus`, rounded up), and the processors that are left for a new bounded command (`cpus-free`: `cpus` less `cpus-headroom` and `cpus-used`, and at least 0). `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, the processors it can use, how long it has run, its working directory, and its command. The held lines, `cpus-used`, and `cpus-free` need the hard cap, so without it there are no held lines and `cpus-used` and `cpus-free` are `-`. 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 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, the processors of the machine, the processors that the running bounded commands can use together (`cpus-used`), the processors that the check keeps for the programs outside the queue (`cpus-headroom`, a tenth of `cpus`, rounded up), and the processors that are left for a new bounded command (`cpus-free`: `cpus` less `cpus-headroom` and `cpus-used`, and at least 0). `line=busy` means that a command waits in the line. `fits` is the largest budget that would start now, with its own headroom. Each `held` line is one bounded command that runs now: its budget, the memory it uses, the processors it can use, how long it has run, its working directory, and its command. The held lines, `cpus-used`, and `cpus-free` need the hard cap, so without it there are no held lines and `cpus-used` and `cpus-free` are `-`. 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). @@ -160,6 +160,11 @@ A command that the project adds later gets its entry when an agent first needs i 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. +Exit code 75 is not a wait and not a full queue. It means that no other bounded command ran, so programs outside the queue hold the memory that the budget needs, and the command did not start. The same budget gives 75 again. Do this instead: + +1. For a recorded command, run the largest row of its entry whose budget is not more than `fits`, with the `--cpus` and the `--memory` of that row. A recorded row is a measurement, not a lowered `--memory`. +2. When no row fits, or the run was a measurement, run nothing. Tell the user that programs outside the queue hold the memory, and give the `budget`, `free`, and `fits` values of the line. 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). @@ -185,7 +190,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. When `cpus-free` is `-`, use the largest row with `starts=yes`. Otherwise, use the largest row with `starts=yes` whose `--cpus` is not more than `cpus-free`, and when no such row fits, use the smallest row with `starts=yes`. When no row has `starts=yes`, use the default row. 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." +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. When `cpus-free` is `-`, use the largest row with `starts=yes`. Otherwise, use the largest row with `starts=yes` whose `--cpus` is not more than `cpus-free`, and when no such row fits, use the smallest row with `starts=yes`. When no row has `starts=yes`, use the default row. 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. Exit code 75 with a `bounded-run: no-memory` line means that the command did not start, and that the same budget gives 75 again: run the largest row of this prompt whose budget is not more than `fits`, or, when no row fits, report the line. 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. @@ -213,6 +218,7 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "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. | | "Running both in parallel is what makes the deadline possible" | Through the wrapper a parallel start is safe, but the queue decides if the two run together. Do not promise a time that depends on it. | +| "It exited 75, I'll run it again and let it wait in the queue" | 75 means that no bounded command holds the memory, so the same budget gives 75 again. Run the largest recorded row within `fits`, or tell the user. | | "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is a measurement of the command plus a margin. Lowering it moves the failure inside the command. | | "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no variable whose name starts with `BOUNDED_RUN_`. | | "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock files alone. | From 17989dcea1a12ae8d00867e50a86fd3116d7978a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:11:47 +0100 Subject: [PATCH 05/15] feat(skills/bounding-heavy-commands): exit 75 when no bounded command can free the budget (#84) Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 39 +++++++++++++++---- .../scripts/tests/test_bounded_run.py | 34 +++++++++++++++- 2 files changed, 65 insertions(+), 8 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index c298508..38cbb55 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -6,7 +6,15 @@ 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. A stop signal to this script +script failed before the command gave a result. Exit code 75 means that the +budget did not fit in the free memory while no other bounded command ran, so +nothing in the queue could free it. The command did not start, and the script +printed one line in a fixed form: + + bounded-run: no-memory budget=M free=M headroom=M fits=M + +free is the free memory less the unused budgets of the running commands, +and fits is the largest budget that would start now, or 0M. A stop signal to this script (SIGHUP, SIGINT, SIGQUIT, or SIGTERM) stops the command, and then this script ends by the same signal. So a Ctrl-C at the terminal, which reaches the shell too, stops a line of joined commands; a signal sent to this script alone does @@ -98,6 +106,7 @@ PREFIX = "bounded-run" EXIT_WRAPPER = 125 +EXIT_NO_MEMORY = 75 ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE" VALUE_OPTIONS = ("--memory", "--cpus", "--exclusive", "--measure-rows", "--label") SLOT_MIB = 2048 @@ -1397,6 +1406,9 @@ def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int: if code in STOP_CODES: log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) return result or code + if code == EXIT_NO_MEMORY: + log("no memory for the row at --cpus %d; the rows after it are not measured" % cpus) + return result or code if code == 0: memory = "%dM" % suggested else: @@ -1523,15 +1535,28 @@ def on_start(pid: int) -> None: log("the scope of the command did not appear after %ds; the next command may not count its budget" % SCOPE_WAIT_SECONDS) unlock_memory() + def read_running() -> int: + running = running_commands(directory) + # A command of an older wrapper holds no run file, but under the hard cap it runs in a bounded scope. + if scopes is not None: + running = max(running, len(_bounded_scopes(scopes, skip))) + return running + reported: Optional[int] = None reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds) try: - wait_for_memory( - wait_budget, settings.memory_wait_seconds, settings.poll_seconds, - headroom_mib=headroom_mib(settings.total_mib, wait_budget, most), - read_available=read_available, read_outstanding=read_outstanding, - lock=lock_memory, unlock=unlock_memory, - ) + try: + wait_for_memory( + wait_budget, settings.memory_wait_seconds, settings.poll_seconds, + headroom_mib=headroom_mib(settings.total_mib, wait_budget, most), + read_available=read_available, read_outstanding=read_outstanding, + read_running=read_running, lock=lock_memory, unlock=unlock_memory, + ) + except NoMemory as stop: + log("no-memory budget=%dM free=%dM headroom=%dM fits=%dM" % ( + wait_budget, stop.available - (stop.outstanding or 0), headroom_mib(settings.total_mib, wait_budget, most), + largest_fit_mib(stop.available, stop.outstanding, settings.total_mib, most))) + return EXIT_NO_MEMORY, 0 code, maxrss = run_command(command, child_environ, on_start) tracked = trackers[0].finish() if trackers else None held = trackers[0].held if trackers else 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 499d1ca..7a39235 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1845,6 +1845,7 @@ def setUp(self): self.base = tempfile.TemporaryDirectory() self.addCleanup(self.base.cleanup) self.directory = os.path.join(self.base.name, "locks") + os.makedirs(self.directory, 0o700, exist_ok=True) self.environ = dict(os.environ) self.environ.pop("BOUNDED_RUN_ACTIVE", None) self.environ.pop("BOUNDED_RUN_NO_CAP", None) @@ -1966,10 +1967,16 @@ def test_a_budget_of_the_whole_queue_starts_when_the_memory_of_the_queue_is_free queue = bounded_run.queue_mib(27703, 2048, bounded_run.default_reserve_mib(27703)) self.assertEqual(self.run_with_free_memory("%dM" % queue, 27703, queue), 0) - def test_a_small_budget_waits_for_its_headroom(self): + def test_a_small_budget_waits_for_its_headroom_while_another_command_runs(self): + descriptor = bounded_run._try_lock(os.path.join(self.directory, bounded_run.run_file_name("bounded-run-9-000009"))) + self.addCleanup(os.close, descriptor) with self.assertRaisesRegex(AssertionError, "the command waits"): self.run_with_free_memory("2G", 27703, 2048 + bounded_run.headroom_mib(27703, 2048, 20480) - 1) + def test_a_small_budget_stops_without_its_headroom_when_no_command_runs(self): + self.assertEqual(self.run_with_free_memory("2G", 27703, 2048 + bounded_run.headroom_mib(27703, 2048, 20480) - 1), + bounded_run.EXIT_NO_MEMORY) + def test_a_small_budget_starts_with_its_headroom_free(self): self.assertEqual(self.run_with_free_memory("2G", 27703, 2048 + bounded_run.headroom_mib(27703, 2048, 20480)), 0) @@ -2082,6 +2089,20 @@ def fake_run_command(command, environ, on_start=None): self.assertEqual([name for name in os.listdir(self.directory) if name.startswith("run-")], []) + def test_a_row_that_stops_for_memory_ends_the_rows(self): + codes = iter([(bounded_run.EXIT_NO_MEMORY, 0)]) + calls = [] + + def once(row, environ): + calls.append(row.cpus) + return next(codes) + + options = bounded_run.parse_arguments(["--measure-rows", "8,4", "--", "true"]) + with mock.patch.object(bounded_run, "bounded_once", once): + self.assertEqual(bounded_run.bounded(options, self.environ), bounded_run.EXIT_NO_MEMORY) + self.assertEqual(calls, [8]) + + class MeasuredRowTest(unittest.TestCase): """Calls bounded() in this process, with run_command replaced by a stub and no hard cap. @@ -2743,6 +2764,17 @@ def peak_concurrency(self): class WrapperProcessTest(WrapperProcessCase): + def test_a_budget_that_does_not_fit_with_no_command_running_exits_75_and_frees_its_slots(self): + environ = dict(self.environ, BOUNDED_RUN_TOTAL_MIB="28000", BOUNDED_RUN_FREE_MIB="14000") + environ.pop("BOUNDED_RUN_RESERVE_MIB", None) + done = subprocess.run([sys.executable, WRAPPER, "--memory", "12288M", "--", "true"], env=environ, + capture_output=True, text=True, timeout=30) + self.assertEqual(done.returncode, 75, done.stderr) + self.assertIn("bounded-run: no-memory budget=12288M free=14000M headroom=2800M fits=11008M", done.stderr) + reservation = bounded_run.try_reserve(os.path.join(self.base.name, "locks"), 10, 10, []) + self.assertIsNotNone(reservation) + reservation.release() + def test_passes_the_exit_code(self): process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "import sys; sys.exit(7)"]) self.assertEqual(process.wait(timeout=60), 7) From 657515efce259c5641431fbc3f75711c314a1390 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:11:47 +0100 Subject: [PATCH 06/15] feat(skills/bounding-heavy-commands): show the largest budget that fits in the check (#84) Co-Authored-By: Claude Opus 5.5 --- .../bounding-heavy-commands/scripts/bounded_run.py | 10 ++++++---- .../scripts/tests/test_bounded_run.py | 14 ++++++++++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 38cbb55..74e68dc 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -44,7 +44,7 @@ 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=M free-slots=N|- free=M|- unused=M|- cpus=N cpus-used=N|- cpus-headroom=N cpus-free=N|- line=free|busy + bounded-run: check slots=N slot=M free-slots=N|- free=M|- unused=M|- cpus=N cpus-used=N|- cpus-headroom=N cpus-free=N|- line=free|busy fits=M|- bounded-run: check held unit=NAME budget=M|- used=M|- cpus=N|- age=Ns|- dir=PATH|- command=TEXT|- bounded-run: check budget=M slots=N headroom=M starts=yes|no @@ -54,7 +54,8 @@ part of one command. cpus-headroom is the processors kept for the programs outside the queue, a tenth of cpus rounded up. cpus-free is cpus less cpus-headroom and cpus-used, and at least 0. starts=yes means that a run of -that budget would start now. It is not a reservation. +that budget would start now. It is not a reservation. fits is the largest +budget that would start now, in steps of 256M, or 0M when none does. 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 @@ -1633,10 +1634,11 @@ def mib(value: Optional[int]) -> str: return "-" if value is None else "%dM" % value spare = cpu_headroom(machine) - log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s cpus=%d cpus-used=%s cpus-headroom=%d cpus-free=%s line=%s" % ( + log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s cpus=%d cpus-used=%s cpus-headroom=%d cpus-free=%s line=%s fits=%s" % ( count, settings.slot_mib, "-" if free_slots is None else free_slots, mib(available), mib(outstanding), machine, "-" if used is None else used, spare, "-" if used is None else max(0, machine - spare - used), - "free" if line is not None else "busy")) + "free" if line is not None else "busy", + "-" if available is None else "%dM" % largest_fit_mib(available, outstanding, settings.total_mib, most))) for held in held_commands(scopes, ()) if scopes is not None else []: log("check held " + held) for budget in budgets: 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 7a39235..0299ca2 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2384,9 +2384,15 @@ 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=- cpus=16 cpus-used=- cpus-headroom=2 cpus-free=- line=free", + "check slots=4 slot=2048M free-slots=4 free=16384M unused=- cpus=16 cpus-used=- cpus-headroom=2 cpus-free=- line=free fits=8192M", ]) + def test_the_largest_budget_that_fits_now(self): + self.assertTrue(self.check(available=4000)[0].endswith(" fits=2816M")) + + def test_no_fit_when_the_free_memory_is_not_readable(self): + self.assertTrue(self.check(available=None)[0].endswith(" fits=-")) + 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 headroom=0M starts=yes") @@ -2414,7 +2420,7 @@ def test_a_command_can_take_every_free_slot_after_the_check(self): 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.assertTrue(" line=busy " in lines[0], lines) 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): @@ -2435,7 +2441,7 @@ def test_each_budget_gets_its_slots_and_its_answer_in_the_order_given(self): 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 cpus=16 cpus-used=- cpus-headroom=2 cpus-free=- line=free") + self.assertEqual(lines[0], "check slots=4 slot=2048M free-slots=4 free=6000M unused=900M cpus=16 cpus-used=- cpus-headroom=2 cpus-free=- line=free fits=3840M") 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): @@ -3257,7 +3263,7 @@ 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=- cpus=\d+ cpus-used=- cpus-headroom=\d+ cpus-free=- line=free\n") + self.assertRegex(errors, r"^bounded-run: check slots=2 slot=2048M free-slots=1 free=(\d+M|-) unused=- cpus=\d+ cpus-used=- cpus-headroom=\d+ cpus-free=- line=free fits=(\d+M|-)\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() From eb037406eda6290aae4fe71c4d05f7c93df403e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:16:45 +0100 Subject: [PATCH 07/15] fix(skills/bounding-heavy-commands): give exit 75 its own section and a precise fits (#84) The steps after exit 75 sat between the wait rules and their bullets, so the bullets read as part of them. They now have their own section, which needs the no-memory line, since a command can exit 75 by itself. fits counts memory only; starts also counts the slots and the line. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index d354364..0cdb7ab 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -64,7 +64,7 @@ bounded-run: check held unit= budget=M used=M cpus= age=s dir= 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, the processors of the machine, the processors that the running bounded commands can use together (`cpus-used`), the processors that the check keeps for the programs outside the queue (`cpus-headroom`, a tenth of `cpus`, rounded up), and the processors that are left for a new bounded command (`cpus-free`: `cpus` less `cpus-headroom` and `cpus-used`, and at least 0). `line=busy` means that a command waits in the line. `fits` is the largest budget that would start now, with its own headroom. Each `held` line is one bounded command that runs now: its budget, the memory it uses, the processors it can use, how long it has run, its working directory, and its command. The held lines, `cpus-used`, and `cpus-free` need the hard cap, so without it there are no held lines and `cpus-used` and `cpus-free` are `-`. 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 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, the processors of the machine, the processors that the running bounded commands can use together (`cpus-used`), the processors that the check keeps for the programs outside the queue (`cpus-headroom`, a tenth of `cpus`, rounded up), and the processors that are left for a new bounded command (`cpus-free`: `cpus` less `cpus-headroom` and `cpus-used`, and at least 0). `line=busy` means that a command waits in the line. `fits` is the largest budget whose memory, with its own headroom, is free now. It does not count the slots or the line; `starts` counts all three. Each `held` line is one bounded command that runs now: its budget, the memory it uses, the processors it can use, how long it has run, its working directory, and its command. The held lines, `cpus-used`, and `cpus-free` need the hard cap, so without it there are no held lines and `cpus-used` and `cpus-free` are `-`. 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). @@ -93,7 +93,7 @@ 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. When `cpus-free` is `-`, choose the largest row that would start now (`starts=yes`). Otherwise, choose the largest row that would start now and whose `--cpus` is not more than `cpus-free`. A row whose `--cpus` is more than `cpus-free` can take the processors of the running commands and of the programs outside the queue, and make all of them slower. When each row that would start has more `--cpus` than `cpus-free`, choose the smallest row that would start: it adds the least to the load. 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. +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. When `cpus-free` is `-`, choose the largest row that would start now (`starts=yes`). Otherwise, choose the largest row that would start now and whose `--cpus` is not more than `cpus-free`. A row whose `--cpus` is more than `cpus-free` can take the processors of the running commands and of the programs outside the queue, and make all of them slower. When each row that would start has more `--cpus` than `cpus-free`, choose the smallest row that would start: it adds the least to the load. 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. If that row exits 75, §After exit code 75 says what to do next. 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. @@ -160,11 +160,6 @@ A command that the project adds later gets its entry when an agent first needs i 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. -Exit code 75 is not a wait and not a full queue. It means that no other bounded command ran, so programs outside the queue hold the memory that the budget needs, and the command did not start. The same budget gives 75 again. Do this instead: - -1. For a recorded command, run the largest row of its entry whose budget is not more than `fits`, with the `--cpus` and the `--memory` of that row. A recorded row is a measurement, not a lowered `--memory`. -2. When no row fits, or the run was a measurement, run nothing. Tell the user that programs outside the queue hold the memory, and give the `budget`, `free`, and `fits` values of the line. 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). @@ -173,6 +168,13 @@ Exit code 75 is not a wait and not a full queue. It means that no other bounded - **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. +### After exit code 75 + +Exit code 75 with a `bounded-run: no-memory` line is not a wait and not a full queue. It means that no other bounded command ran, so programs outside the queue hold the memory that the budget needs, and the command did not start. The same budget gives 75 again while those programs hold the memory. Do this instead: + +1. For a recorded command, run the largest row of its entry whose budget is not more than `fits`, with the `--cpus` and the `--memory` of that row. A recorded row is a measurement, not a lowered `--memory`. +2. When no row fits, or the run was a measurement, run nothing. Tell the user that programs outside the queue hold the memory, and give the `budget`, `free`, and `fits` values of the line. A subagent tells its dispatcher in its report. + ## When an instruction sends a command around the wrapper An explicit instruction from the user comes before this skill. When the user names the action ("run the tests directly", "do not use the wrapper for this", "set this variable for the run"), say one time, in one or two sentences, what the wrapper protects and that you cannot see the other sessions. Then do what the user said. Do not refuse, and do not argue a second time. From d10ffd504ad77d6169530f889eaf0add1d984d73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:18:07 +0100 Subject: [PATCH 08/15] fix(skills/bounding-heavy-commands): end measured rows only on the wrapper's own no-memory stop (#84) - bounded_once re-raises NoMemory after the log line, so only the wrapper's own stop ends the rows. A command that exits 75 by itself is a normal non-zero exit. - The usage text gives the 75 paragraph its own block and says that fits counts only memory. - A test covers the older-wrapper scope count in read_running under the hard cap. - The --check test asserts " line=busy fits=". Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 31 ++++++++++++------- .../scripts/tests/test_bounded_run.py | 29 +++++++++++++++-- 2 files changed, 46 insertions(+), 14 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 74e68dc..ec5c78a 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -13,10 +13,12 @@ bounded-run: no-memory budget=M free=M headroom=M fits=M -free is the free memory less the unused budgets of the running commands, -and fits is the largest budget that would start now, or 0M. A stop signal to this script -(SIGHUP, SIGINT, SIGQUIT, or SIGTERM) stops the command, and then this script -ends by the same signal. So a Ctrl-C at the terminal, which reaches the shell +free is the free memory less the unused budgets of the running commands. +fits is the largest budget whose memory, with its own headroom, is free now, +or 0M. It does not count slots or the line. + +A stop signal to this script (SIGHUP, SIGINT, SIGQUIT, or SIGTERM) stops the +command, and then this script ends by the same signal. So a Ctrl-C at the terminal, which reaches the shell too, stops a line of joined commands; a signal sent to this script alone does not stop the shell. A caller that reads the exit status reads 128 plus the signal. @@ -1383,7 +1385,10 @@ def _raise_stopped(signum: int, frame: object) -> None: def bounded(options: Options, environ: Mapping[str, str]) -> int: if not options.rows: - return bounded_once(options, environ)[0] + try: + return bounded_once(options, environ)[0] + except NoMemory: + return EXIT_NO_MEMORY # run_command sets its own handlers while a row runs and puts these back after it. previous = {signum: signal.signal(signum, _raise_stopped) for signum in (signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT)} try: @@ -1402,14 +1407,15 @@ def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int: row = Options() row.memory, row.cpus, row.exclusive, row.measure, row.label, row.command = ( memory, cpus, options.exclusive, True, options.label, options.command) - code, suggested = bounded_once(row, environ) + try: + code, suggested = bounded_once(row, environ) + except NoMemory: + log("no memory for the row at --cpus %d; the rows after it are not measured" % cpus) + return result or EXIT_NO_MEMORY measured += 1 if code in STOP_CODES: log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) return result or code - if code == EXIT_NO_MEMORY: - log("no memory for the row at --cpus %d; the rows after it are not measured" % cpus) - return result or code if code == 0: memory = "%dM" % suggested else: @@ -1425,7 +1431,10 @@ def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int: def bounded_once(options: Options, environ: Mapping[str, str]) -> Tuple[int, int]: - """Runs the command one time. Returns the exit code and the suggested budget in MiB.""" + """Runs the command one time. Returns the exit code and the suggested budget in MiB. + + Raises NoMemory, after the line of the stop, when the budget does not fit and no bounded command runs. + """ settings = Settings(environ) if options.memory is not None: budget = parse_size_mib(options.memory) @@ -1557,7 +1566,7 @@ def read_running() -> int: log("no-memory budget=%dM free=%dM headroom=%dM fits=%dM" % ( wait_budget, stop.available - (stop.outstanding or 0), headroom_mib(settings.total_mib, wait_budget, most), largest_fit_mib(stop.available, stop.outstanding, settings.total_mib, most))) - return EXIT_NO_MEMORY, 0 + raise code, maxrss = run_command(command, child_environ, on_start) tracked = trackers[0].finish() if trackers else None held = trackers[0].held if trackers else 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 0299ca2..7c20d01 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2090,18 +2090,41 @@ def fake_run_command(command, environ, on_start=None): def test_a_row_that_stops_for_memory_ends_the_rows(self): - codes = iter([(bounded_run.EXIT_NO_MEMORY, 0)]) calls = [] def once(row, environ): calls.append(row.cpus) - return next(codes) + raise bounded_run.NoMemory(0, None) options = bounded_run.parse_arguments(["--measure-rows", "8,4", "--", "true"]) with mock.patch.object(bounded_run, "bounded_once", once): self.assertEqual(bounded_run.bounded(options, self.environ), bounded_run.EXIT_NO_MEMORY) self.assertEqual(calls, [8]) + def test_a_row_whose_command_exits_75_by_itself_does_not_end_the_rows(self): + answers = iter([(bounded_run.EXIT_NO_MEMORY, 100), (0, 50)]) + calls = [] + + def once(row, environ): + calls.append(row.cpus) + return next(answers) + + options = bounded_run.parse_arguments(["--measure-rows", "8,4", "--", "true"]) + with mock.patch.object(bounded_run, "bounded_once", once): + self.assertEqual(bounded_run.bounded(options, self.environ), bounded_run.EXIT_NO_MEMORY) + self.assertEqual(calls, [8, 4]) + + def test_the_wait_counts_a_scope_of_an_older_wrapper_as_a_running_command(self): + scopes = os.path.join(self.base.name, "slice") + os.makedirs(os.path.join(scopes, "bounded-run-7-abcdef.scope")) + os.makedirs(os.path.join(scopes, "bounded-run-2-111111.scope")) + output = "0::/slice/bounded-run-1-000000-probe.scope\n" + with mock.patch.object(bounded_run, "scope_parent_directory", return_value=scopes): + keywords = self.wait_arguments(output) + self.assertGreaterEqual(keywords["read_running"](), 1) + os.rmdir(os.path.join(scopes, "bounded-run-7-abcdef.scope")) + self.assertEqual(keywords["read_running"](), 0) + class MeasuredRowTest(unittest.TestCase): """Calls bounded() in this process, with run_command replaced by a stub and no hard cap. @@ -2420,7 +2443,7 @@ def test_a_command_can_take_every_free_slot_after_the_check(self): 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(" line=busy " in lines[0], lines) + self.assertTrue(" line=busy fits=" in lines[0], lines) 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): From bd9f1194171db8765a864dca59234316191ce9cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:20:05 +0100 Subject: [PATCH 09/15] fix(skills/bounding-heavy-commands): point the wait rules at the right section (#84) The new section after exit 75 made "see the next section" point at it. Name the section instead. The Red Flags row now says that the same budget fails again only while programs outside the queue hold the memory, as the section does. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 0cdb7ab..9310fbd 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -158,7 +158,7 @@ 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. 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. +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 (§When an instruction sends a command around the wrapper), 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. @@ -220,7 +220,7 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "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. | | "Running both in parallel is what makes the deadline possible" | Through the wrapper a parallel start is safe, but the queue decides if the two run together. Do not promise a time that depends on it. | -| "It exited 75, I'll run it again and let it wait in the queue" | 75 means that no bounded command holds the memory, so the same budget gives 75 again. Run the largest recorded row within `fits`, or tell the user. | +| "It exited 75, I'll run it again and let it wait in the queue" | 75 means that no bounded command holds the memory, so the same budget gives 75 again while programs outside the queue hold it. Run the largest recorded row within `fits`, or tell the user. | | "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is a measurement of the command plus a margin. Lowering it moves the failure inside the command. | | "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no variable whose name starts with `BOUNDED_RUN_`. | | "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock files alone. | From 5b12fd902b88fcab1c4425442f9be835e48e4400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:20:05 +0100 Subject: [PATCH 10/15] docs(skills/bounding-heavy-commands): describe fits as free memory in every place (#84) The check section and largest_fit_mib still said that fits would start now, but it counts memory only. Also rewrap the stop-signal paragraph. Co-Authored-By: Claude Opus 5.5 --- .../bounding-heavy-commands/scripts/bounded_run.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index ec5c78a..bf44446 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -18,10 +18,10 @@ or 0M. It does not count slots or the line. A stop signal to this script (SIGHUP, SIGINT, SIGQUIT, or SIGTERM) stops the -command, and then this script ends by the same signal. So a Ctrl-C at the terminal, which reaches the shell -too, stops a line of joined commands; a signal sent to this script alone does -not stop the shell. A caller that reads the exit status reads 128 plus the -signal. +command, and then this script ends by the same signal. So a Ctrl-C at the +terminal, which reaches the shell too, stops a line of joined commands; a +signal sent to this script alone does not stop the shell. A caller that reads +the exit status reads 128 plus the signal. A run without --cpus gets half of the processors of the machine, rounded down and at least 1. The command reads its processors in BOUNDED_RUN_CPUS, @@ -57,7 +57,8 @@ outside the queue, a tenth of cpus rounded up. cpus-free is cpus less cpus-headroom and cpus-used, and at least 0. starts=yes means that a run of that budget would start now. It is not a reservation. fits is the largest -budget that would start now, in steps of 256M, or 0M when none does. +budget whose memory, with its own headroom, is free now, in steps of 256M, +or 0M when none is; it does not count slots or the line. 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 @@ -671,7 +672,7 @@ def memory_fits(budget_mib: int, available: Optional[int], outstanding: Optional def largest_fit_mib(available: int, outstanding: Optional[int], total_mib: int, queue_mib: int) -> int: - """Returns the largest budget, in steps of BUDGET_STEP_MIB, that would start now with its own headroom, or 0.""" + """Returns the largest budget, in steps of BUDGET_STEP_MIB, whose memory with its own headroom is free, or 0.""" free = available - (outstanding or 0) budget = min(queue_mib, max(0, free)) // BUDGET_STEP_MIB * BUDGET_STEP_MIB while budget > 0 and not memory_fits(budget, free, None, headroom_mib(total_mib, budget, queue_mib)): From d41434eb4f830874b4014ce9cb1d5ec826bd3159 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:32:19 +0100 Subject: [PATCH 11/15] fix(skills/bounding-heavy-commands): read the memory again before a no-memory stop (#84) The last bounded command can end between the read of the free memory and the count of running commands, since it ends without the memory lock. The wait now reads the memory again after a count of 0, and starts when the budget fits. A row that stops for memory after a failed row now exits 75, as its line says. The usage text says that a command can exit 75 by itself, and the lock test accepts the count from before the run file exists. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 51 +++++++++++++------ .../scripts/tests/test_bounded_run.py | 27 +++++++++- 2 files changed, 60 insertions(+), 18 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index bf44446..01e4702 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -6,13 +6,15 @@ 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. Exit code 75 means that the -budget did not fit in the free memory while no other bounded command ran, so -nothing in the queue could free it. The command did not start, and the script -printed one line in a fixed form: +script failed before the command gave a result. Exit code 75 with the line +below means that the budget did not fit in the free memory while no other +bounded command ran, so nothing in the queue could free it, and the command +did not start. The script printed one line in a fixed form: bounded-run: no-memory budget=M free=M headroom=M fits=M +A command can also exit 75 by itself, without the line. + free is the free memory less the unused budgets of the running commands. fits is the largest budget whose memory, with its own headroom, is free now, or 0M. It does not count slots or the line. @@ -39,7 +41,9 @@ largest runs with the default budget where the hard cap is available, and alone in the queue where it is not. Each smaller one runs with the suggested budget of the one before it, or with the budget of the one before it when that -run did not exit 0. The exit code is the first exit code that is not 0. +run did not exit 0. A row that stops with the no-memory line ends the list +with exit code 75. Otherwise 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, one held line for each @@ -707,30 +711,45 @@ def wait_for_memory( Returns at once when the free memory cannot be read. read_outstanding gives None where the unused budgets cannot be counted. The call returns with lock held: the caller calls unlock once the new command counts in read_outstanding. """ - started = clock() - next_line: Optional[float] = None - while True: - lock() + def read() -> Tuple[Optional[int], Optional[int]]: # A running command that grows or shrinks during the reads moves both values. The larger of the two unused # counts around the free memory is the one that matches it or errs on the safe side. before = read_outstanding() available = read_available() if available is None: - log("cannot read the free memory; starting") - return + return None, None after = read_outstanding() - outstanding = None if before is None or after is None else max(before, after) + return available, None if before is None or after is None else max(before, after) + + def state(available: int, outstanding: Optional[int]) -> str: 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) + return "%d MiB free, %s, %d MiB headroom, budget %d MiB" % (available, counted, headroom_mib, budget_mib) + + started = clock() + next_line: Optional[float] = None + while True: + lock() + available, outstanding = read() + if available is None: + log("cannot read the free memory; starting") + return if memory_fits(budget_mib, available, outstanding, headroom_mib): - log(state + "; starting") + log(state(available, outstanding) + "; starting") return if read_running() == 0: + # A command ends without the memory lock, so the last one can free its memory after the reads above. + available, outstanding = read() + if available is None: + log("cannot read the free memory; starting") + return + if memory_fits(budget_mib, available, outstanding, headroom_mib): + log(state(available, outstanding) + "; starting") + return unlock() raise NoMemory(available, outstanding) waited = clock() - started if next_line is None or waited >= next_line: - log(state + ("; waiting" if next_line is None else "; still waiting after %ds" % waited)) + log(state(available, outstanding) + ("; waiting" if next_line is None else "; still waiting after %ds" % waited)) next_line = waited + interval_seconds unlock() sleep(poll_seconds) @@ -1412,7 +1431,7 @@ def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int: code, suggested = bounded_once(row, environ) except NoMemory: log("no memory for the row at --cpus %d; the rows after it are not measured" % cpus) - return result or EXIT_NO_MEMORY + return EXIT_NO_MEMORY measured += 1 if code in STOP_CODES: log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) 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 7c20d01..4b57f39 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -998,6 +998,19 @@ def test_stops_with_the_lock_released(self): lock=lambda: events.append("lock"), unlock=lambda: events.append("unlock")) self.assertEqual(events, ["lock", "unlock"]) + def test_starts_when_the_last_bounded_command_ends_between_the_reads(self): + readings = [1000, 8000] + bounded_run.wait_for_memory(4096, 300, 5.0, read_available=lambda: readings.pop(0), read_running=lambda: 0, + sleep=lambda seconds: self.fail("waits")) + self.assertEqual(readings, []) + + def test_a_stop_gives_the_free_memory_read_after_the_count(self): + readings = [1000, 2000] + with self.assertRaises(bounded_run.NoMemory) as raised: + bounded_run.wait_for_memory(4096, 300, 5.0, read_available=lambda: readings.pop(0), read_running=lambda: 0, + sleep=lambda seconds: self.fail("waits")) + self.assertEqual(raised.exception.available, 2000) + class HeadroomTest(unittest.TestCase): def test_a_tenth_of_the_memory(self): @@ -2088,7 +2101,6 @@ def fake_run_command(command, environ, on_start=None): self.assertEqual(seen, [1]) self.assertEqual([name for name in os.listdir(self.directory) if name.startswith("run-")], []) - def test_a_row_that_stops_for_memory_ends_the_rows(self): calls = [] @@ -2101,6 +2113,16 @@ def once(row, environ): self.assertEqual(bounded_run.bounded(options, self.environ), bounded_run.EXIT_NO_MEMORY) self.assertEqual(calls, [8]) + def test_a_row_that_stops_for_memory_after_a_failed_row_exits_75(self): + def once(row, environ): + if row.cpus == 8: + return 1, 100 + raise bounded_run.NoMemory(0, None) + + options = bounded_run.parse_arguments(["--measure-rows", "8,4", "--", "true"]) + with mock.patch.object(bounded_run, "bounded_once", once): + self.assertEqual(bounded_run.bounded(options, self.environ), bounded_run.EXIT_NO_MEMORY) + def test_a_row_whose_command_exits_75_by_itself_does_not_end_the_rows(self): answers = iter([(bounded_run.EXIT_NO_MEMORY, 100), (0, 50)]) calls = [] @@ -3010,7 +3032,8 @@ def test_the_command_does_not_inherit_the_locks(self): ) process = self.wrapper(["--memory", "4G", "--exclusive", "port"], [sys.executable, "-c", script]) output, errors = process.communicate(timeout=60) - self.assertEqual(output, "locks 7 inherited 0\n", errors) + # The command can list the lock directory before the wrapper makes its run file. + self.assertIn(output, ("locks 6 inherited 0\n", "locks 7 inherited 0\n"), errors) def test_commands_with_the_same_exclusive_name_take_turns(self): workers = [self.worker("w%d" % index, "2G", hold="0.3", options=["--exclusive", "port-8080"]) for index in range(3)] # brief; the test waits for each to end From 5ca7705ab0f07f40185c3c12af403bbc2d2af00a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:32:19 +0100 Subject: [PATCH 12/15] fix(skills/bounding-heavy-commands): tie exit 75 to the no-memory line everywhere (#84) The Red Flags row read exit 75 alone as a memory stop, but a command can exit 75 by itself. The --measure-rows entry now says that a memory stop ends the list with 75. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 9310fbd..bcbfaae 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -44,7 +44,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--cpus ` | Processor limit, as a whole number. Taken from the record. Without it the wrapper uses half the machine's processors, rounded down, and at least 1. | | `--exclusive ` | A resource that only one command may hold at a time, such as a fixed port. You choose the name. The wrapper keeps the names of each repository apart, and all worktrees of one repository share them. Repeat the option for each resource. | | `--measure` | Also print a suggested budget. Discovery uses it. With no `--memory`, the command runs with the default budget where the hard cap is available, and alone in the queue where it is not. | -| `--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 with the default budget where the hard cap is available, and alone in the queue where it is not. Each smaller one runs with `--memory` at the suggested budget of the one before it. When the one before it did not exit 0, the smaller one runs with the same `--memory` as that one. Use it in place of `--cpus` and `--measure`. A stop signal ends the list. A stop signal to the wrapper then ends the wrapper by that signal. So a Ctrl-C, which reaches the shell too, stops a line of joined calls; a signal sent to the wrapper alone does not stop the shell's line. Otherwise the exit code is the first exit code of a row that is not 0. | +| `--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 with the default budget where the hard cap is available, and alone in the queue where it is not. Each smaller one runs with `--memory` at the suggested budget of the one before it. When the one before it did not exit 0, the smaller one runs with the same `--memory` as that one. Use it in place of `--cpus` and `--measure`. A stop signal ends the list. A stop signal to the wrapper then ends the wrapper by that signal. So a Ctrl-C, which reaches the shell too, stops a line of joined calls; a signal sent to the wrapper alone does not stop the shell's line. A row that stops with the `no-memory` line ends the list with exit code 75. Otherwise 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. | @@ -220,7 +220,7 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "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. | | "Running both in parallel is what makes the deadline possible" | Through the wrapper a parallel start is safe, but the queue decides if the two run together. Do not promise a time that depends on it. | -| "It exited 75, I'll run it again and let it wait in the queue" | 75 means that no bounded command holds the memory, so the same budget gives 75 again while programs outside the queue hold it. Run the largest recorded row within `fits`, or tell the user. | +| "It exited 75 with a `no-memory` line, I'll run it again and let it wait in the queue" | That line means that no bounded command holds the memory, so the same budget gives 75 again while programs outside the queue hold it. Run the largest recorded row within `fits`, or tell the user. | | "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is a measurement of the command plus a margin. Lowering it moves the failure inside the command. | | "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no variable whose name starts with `BOUNDED_RUN_`. | | "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock files alone. | From 7dbf8a126965a9044c881dd75aa28f189fba5cb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:41:40 +0100 Subject: [PATCH 13/15] fix(skills/bounding-heavy-commands): report what the wrapper saw, not who holds the memory (#84) Without the hard cap, a command of an older wrapper holds no run file, so a no-memory stop does not prove that programs outside the queue hold the memory. The text now says that the wrapper found no bounded command running, and the agent reports budget, free and fits. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 8 ++++---- skills/bounding-heavy-commands/scripts/bounded_run.py | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index bcbfaae..28b10b2 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -48,7 +48,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--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. While another bounded command runs, 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. When no other bounded command runs, nothing in the queue can free memory, so the wrapper does not wait. It prints `bounded-run: no-memory budget=M free=M headroom=M fits=M`, releases its slots, and exits with code 75 without starting the command (§Rules for the wait). Each line that the wrapper prints starts with `bounded-run:`. A measurement also prints one row line, in a fixed form: +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. While another bounded command runs, 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. When the wrapper finds no other bounded command running, nothing that it can count will free memory, so it does not wait. It prints `bounded-run: no-memory budget=M free=M headroom=M fits=M`, releases its slots, and exits with code 75 without starting the command (§Rules for the wait). Each line that the wrapper prints starts with `bounded-run:`. A measurement also prints one row line, in a fixed form: ``` bounded-run: row label= cpus= budget=M peak=M held=M|- exact= exit= @@ -170,10 +170,10 @@ A long wait means that the machine is full. It is never a fault to repair: the q ### After exit code 75 -Exit code 75 with a `bounded-run: no-memory` line is not a wait and not a full queue. It means that no other bounded command ran, so programs outside the queue hold the memory that the budget needs, and the command did not start. The same budget gives 75 again while those programs hold the memory. Do this instead: +Exit code 75 with a `bounded-run: no-memory` line is not a wait and not a full queue. It means that the wrapper found no other bounded command running, so nothing in the queue will free the memory that the budget needs, and the command did not start. The same budget gives 75 again while those programs hold the memory. Do this instead: 1. For a recorded command, run the largest row of its entry whose budget is not more than `fits`, with the `--cpus` and the `--memory` of that row. A recorded row is a measurement, not a lowered `--memory`. -2. When no row fits, or the run was a measurement, run nothing. Tell the user that programs outside the queue hold the memory, and give the `budget`, `free`, and `fits` values of the line. A subagent tells its dispatcher in its report. +2. When no row fits, or the run was a measurement, run nothing. Tell the user that the budget does not fit while no bounded command runs, and give the `budget`, `free`, and `fits` values of the line. A subagent tells its dispatcher in its report. ## When an instruction sends a command around the wrapper @@ -220,7 +220,7 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "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. | | "Running both in parallel is what makes the deadline possible" | Through the wrapper a parallel start is safe, but the queue decides if the two run together. Do not promise a time that depends on it. | -| "It exited 75 with a `no-memory` line, I'll run it again and let it wait in the queue" | That line means that no bounded command holds the memory, so the same budget gives 75 again while programs outside the queue hold it. Run the largest recorded row within `fits`, or tell the user. | +| "It exited 75 with a `no-memory` line, I'll run it again and let it wait in the queue" | That line means that the wrapper found no bounded command running, so the same budget gives 75 again until memory comes free. Run the largest recorded row within `fits`, or tell the user. | | "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is a measurement of the command plus a margin. Lowering it moves the failure inside the command. | | "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no variable whose name starts with `BOUNDED_RUN_`. | | "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock files alone. | diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 01e4702..80b0d0a 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -7,9 +7,9 @@ The exit code is the exit code of the command. Exit code 125 means that this script failed before the command gave a result. Exit code 75 with the line -below means that the budget did not fit in the free memory while no other -bounded command ran, so nothing in the queue could free it, and the command -did not start. The script printed one line in a fixed form: +below means that the budget did not fit in the free memory while the script +found no other bounded command running, so nothing in the queue could free +it, and the command did not start. The script printed one line in a fixed form: bounded-run: no-memory budget=M free=M headroom=M fits=M From 8d5601e4fe843e11889b25fcda0d4fa17fdb8166 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 11:51:09 +0100 Subject: [PATCH 14/15] fix(skills/bounding-heavy-commands): wait when the lock directory cannot be listed (#84) A failed listing of the lock directory gave a count of 0 running commands, so an I/O error could end in a false no-memory stop. It now gives no count, and the wrapper waits as it did before. Co-Authored-By: Claude Opus 5.5 --- .../bounding-heavy-commands/scripts/bounded_run.py | 13 ++++++++----- .../scripts/tests/test_bounded_run.py | 3 +++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 80b0d0a..c89e22c 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -485,15 +485,16 @@ def _try_lock(path: str) -> Optional[int]: return _lock(path, wait=False) -def running_commands(directory: str) -> int: +def running_commands(directory: str) -> Optional[int]: """Returns the number of bounded commands that run now: the run files that a process holds locked. - A run file that no process holds is left over from a wrapper that was killed, and is removed. + Returns None when the directory cannot be read. A run file that no process holds is left over from a + wrapper that was killed, and is removed. """ try: names = os.listdir(directory) except OSError: - return 0 + return None running = 0 for name in names: if not (name.startswith("run-") and name.endswith(".lock")): @@ -1565,11 +1566,13 @@ def on_start(pid: int) -> None: log("the scope of the command did not appear after %ds; the next command may not count its budget" % SCOPE_WAIT_SECONDS) unlock_memory() - def read_running() -> int: + def read_running() -> Optional[int]: running = running_commands(directory) # A command of an older wrapper holds no run file, but under the hard cap it runs in a bounded scope. if scopes is not None: - running = max(running, len(_bounded_scopes(scopes, skip))) + found = len(_bounded_scopes(scopes, skip)) + if found: + return max(running or 0, found) return running reported: Optional[int] = 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 4b57f39..b039179 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -705,6 +705,9 @@ def hold(self, name): def test_counts_no_command_in_an_empty_directory(self): self.assertEqual(bounded_run.running_commands(self.directory), 0) + def test_a_directory_that_cannot_be_read_gives_no_count(self): + self.assertIsNone(bounded_run.running_commands(os.path.join(self.directory, "missing"))) + def test_counts_each_run_file_that_a_process_holds(self): self.hold(bounded_run.run_file_name("bounded-run-1-000001")) self.hold(bounded_run.run_file_name("bounded-run-2-000002")) From ce14f071ca4cb09fad3f7822fbb720b8dcb825bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:33:55 +0100 Subject: [PATCH 15/15] fix(skills/bounding-heavy-commands): wait when the cgroup scopes cannot be listed (#84) A failed listing of the scopes counted as no bounded command running, but a command of an older wrapper shows only as a scope. The count is now unknown in that case unless a run file shows a running command, so the wrapper waits and does not stop with 75. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 17 +++++++++++++++-- .../scripts/tests/test_bounded_run.py | 7 +++++++ 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 c89e22c..5efaf7e 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -837,12 +837,22 @@ def own_scope_name(proc_root: str = "/proc") -> Optional[str]: return None if path is None else os.path.basename(path) +def bounded_scope_count(parent: str, skip: Sequence[str]) -> Optional[int]: + """Returns the number of scopes that _bounded_scopes names, or None when parent cannot be listed.""" + names = _listed_scopes(parent, skip) + return None if names is None else len(names) + + 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.""" + return _listed_scopes(parent, skip) or [] + + +def _listed_scopes(parent: str, skip: Sequence[str]) -> Optional[List[str]]: try: names = os.listdir(parent) except OSError: - return [] + return None 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 @@ -1570,7 +1580,10 @@ def read_running() -> Optional[int]: running = running_commands(directory) # A command of an older wrapper holds no run file, but under the hard cap it runs in a bounded scope. if scopes is not None: - found = len(_bounded_scopes(scopes, skip)) + found = bounded_scope_count(scopes, skip) + if found is None: + # Without the scopes, a command of an older wrapper cannot be seen, so only a run file proves a count. + return running or None if found: return max(running or 0, found) return running 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 b039179..38b2ee7 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2150,6 +2150,13 @@ def test_the_wait_counts_a_scope_of_an_older_wrapper_as_a_running_command(self): os.rmdir(os.path.join(scopes, "bounded-run-7-abcdef.scope")) self.assertEqual(keywords["read_running"](), 0) + def test_a_scope_listing_that_fails_gives_no_count_when_no_run_file_shows_a_command(self): + scopes = os.path.join(self.base.name, "missing-slice") + output = "0::/missing-slice/bounded-run-1-000000-probe.scope\n" + with mock.patch.object(bounded_run, "scope_parent_directory", return_value=scopes): + keywords = self.wait_arguments(output) + self.assertIsNone(keywords["read_running"]()) + class MeasuredRowTest(unittest.TestCase): """Calls bounded() in this process, with run_command replaced by a stub and no hard cap.