From 77ad36f869b872415c536305382f45e22bb2be4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:42:05 +0100 Subject: [PATCH 01/10] fix(skills/bounding-heavy-commands): count unused budgets and never start on a full machine The wait for free memory compared the free memory now with the new budget. It ignored the part of their budgets that running bounded commands had not used yet, it trusted a reserve fixed at the start, and after BOUNDED_RUN_MEMORY_WAIT_SECONDS it started the command anyway. Together these let the queue give out more memory than the machine had (#55). - The cap probe now prints its own cgroup. Every scope that systemd-run makes for this user with no slice option lands in the same slice, so the probe finds the siblings with no state file. The wait subtracts the sum of memory.max - memory.current over the bounded-run scopes there, skipping probe scopes, the new unit, the scope the wrapper runs in, and scopes with no limit. Without a cap or cgroup v2 nothing is subtracted, and the log says so. - The wait also keeps a headroom of max(1 GiB, a tenth of the memory) for the programs outside the queue. - The wait has no time limit. BOUNDED_RUN_MEMORY_WAIT_SECONDS is now the time between two "still waiting" lines. A machine whose free memory cannot be read still starts the command. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 4 +- .../scripts/bounded_run.py | 130 +++++++-- .../scripts/tests/test_bounded_run.py | 257 ++++++++++++++---- 3 files changed, 319 insertions(+), 72 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index da8dd0b..9f49533 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -41,11 +41,11 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--exclusive ` | A resource that only one command may hold at a time, such as a fixed port. You choose the name. The wrapper keeps the names of each repository apart, and all worktrees of one repository share them. Repeat the option for each resource. | | `--measure` | Also print a suggested budget. Discovery uses it. With no `--memory`, the command runs alone in the queue. | -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. Each line that the wrapper prints starts with `bounded-run:`. Its exit code is the command's exit code. Exit code 125, with a `bounded-run:` line that names a fault and with no line for the budget and the peak, means that the wrapper itself failed (see §When the wrapper cannot run). +The wrapper does four things in sequence. It waits for its turn in the queue. It waits until the memory of its budget is free. It runs the command. It prints the budget and the measured peak on the error stream. For the wait, the free memory is the memory that the machine has free now, less the part of their budgets that the running bounded commands do not use yet, less a headroom for the programs outside the queue. The headroom is a tenth of the memory of the machine, and at least 1 GiB. The wait has no time limit: the command does not start before its memory is free, and the wrapper prints a line at intervals while it waits. Each line that the wrapper prints starts with `bounded-run:`. Its exit code is the command's exit code. Exit code 125, with a `bounded-run:` line that names a fault and with no line for the budget and the peak, means that the wrapper itself failed (see §When the wrapper cannot run). The wrapper sets `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB` in the environment of the command, from `--cpus` and `--memory`. A recorded command line can read them and hand them to the toolchain's own parallelism and memory settings. You do not set them: you change them with the two options. -On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. When a recorded command ends with exit code 137 and the wrapper reports a peak near the budget, the cap stopped it: the command grew. Measure it again with `--measure` and `--memory` at two times the budget, and correct the record. +On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. Without the cap, the wait does not count the unused budgets of the running commands. When a recorded command ends with exit code 137 and the wrapper reports a peak near the budget, the cap stopped it: the command grew. Measure it again with `--measure` and `--memory` at two times the budget, and correct the record. ## The record diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 85e7167..413ef78 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -20,7 +20,7 @@ BOUNDED_RUN_SLOT_MIB size of one memory slot (default 2048) BOUNDED_RUN_RESERVE_MIB memory that the queue never gives out - BOUNDED_RUN_MEMORY_WAIT_SECONDS time limit of the wait for free memory (default 300) + BOUNDED_RUN_MEMORY_WAIT_SECONDS time between two lines of the wait for free memory (default 300) Values for the tests of this script, and for its maintainers: @@ -57,6 +57,7 @@ ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE" SLOT_MIB = 2048 MINIMUM_RESERVE_MIB = 2048 +MINIMUM_HEADROOM_MIB = 1024 POLL_SECONDS = 2.0 MEMORY_WAIT_SECONDS = 300.0 SAMPLE_SECONDS = 1.0 @@ -187,6 +188,11 @@ def default_reserve_mib(total_mib: int) -> int: return max(MINIMUM_RESERVE_MIB, total_mib // 4) +def headroom_mib(total_mib: int) -> int: + """Returns the memory that the wait for free memory keeps free for the programs outside the queue.""" + return max(MINIMUM_HEADROOM_MIB, total_mib // 10) + + def slot_count(total_mib: int, slot_mib: int, reserve_mib: int) -> int: return max(1, (total_mib - reserve_mib) // slot_mib) @@ -454,23 +460,32 @@ def available_memory_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/c def wait_for_memory( - budget_mib: int, limit_seconds: float, poll_seconds: float, + 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, sleep: Callable[[float], None] = time.sleep, -) -> bool: +) -> 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. + """ waited = 0.0 + next_line = 0.0 while True: available = read_available() if available is None: log("cannot read the free memory; starting") - return True - if available >= budget_mib: - log("%d MiB free, budget %d MiB; starting" % (available, budget_mib)) - return True - if waited >= limit_seconds: - log("WARNING: only %d MiB free after %ds, budget %d MiB; starting" % (available, waited, budget_mib)) - return False - log("%d MiB free, budget %d MiB; waiting (%d of %ds)" % (available, budget_mib, waited, limit_seconds)) + return + outstanding = read_outstanding() + counted = "unused running budgets not counted here" if outstanding is None else "%d MiB of running budgets unused" % outstanding + state = "%d MiB free, %s, %d MiB headroom, budget %d MiB" % (available, counted, headroom_mib, budget_mib) + if available - (outstanding or 0) - headroom_mib >= budget_mib: + log(state + "; starting") + return + if waited >= next_line: + log(state + ("; waiting" if waited == 0 else "; still waiting after %ds" % waited)) + next_line = waited + interval_seconds sleep(poll_seconds) waited += poll_seconds @@ -488,32 +503,87 @@ def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool return prefix + ["--"] -def cap_usable( +def probe_cap( prefix: Sequence[str], platform: str = sys.platform, which: Callable[[str], Optional[str]] = shutil.which, run: Callable[..., "subprocess.CompletedProcess"] = subprocess.run, -) -> bool: +) -> Optional[str]: + """Runs a short command under the prefix. Returns None when the prefix does not work here, else the + text of /proc/self/cgroup inside the probe scope, which can be empty.""" if not platform.startswith("linux") or which("systemd-run") is None: - return False + return None try: - done = run(list(prefix) + ["true"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15) + done = run(list(prefix) + ["cat", "/proc/self/cgroup"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=15) except (OSError, subprocess.TimeoutExpired): - return False - return done.returncode == 0 + return None + if done.returncode != 0: + return None + return done.stdout or "" def choose_cap_prefix( budget_mib: int, cpus: Optional[int], unit: str, - usable: Callable[[Sequence[str]], bool], -) -> Optional[List[str]]: - """Returns the prefix of the hard cap for the unit, or None when no cap is usable here.""" + probe: Callable[[Sequence[str]], Optional[str]], +) -> Optional[Tuple[List[str], str]]: + """Returns the prefix of the hard cap for the unit and the output of its probe, or None when no cap is usable here.""" # A scope unit accepts OOMPolicy= from systemd 253; an older systemd rejects the whole prefix. for oom_policy in (True, False): - if usable(cap_prefix(budget_mib, cpus, unit + "-probe", oom_policy)): - return cap_prefix(budget_mib, cpus, unit, oom_policy) + found = probe(cap_prefix(budget_mib, cpus, unit + "-probe", oom_policy)) + if found is not None: + return cap_prefix(budget_mib, cpus, unit, oom_policy), found return None +def _unified_path(cgroup_text: str) -> Optional[str]: + for line in cgroup_text.splitlines(): + if line.startswith("0::"): + return line.strip()[3:] + return None + + +def scope_parent_directory(probe_output: str, cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]: + """Returns the directory that holds the scope of the probe, or None without a cgroup version 2 line.""" + path = _unified_path(probe_output) + return None if path is None else os.path.dirname(cgroup_root + path) + + +def own_scope_name(proc_root: str = "/proc") -> Optional[str]: + """Returns the name of the cgroup of this process, or None when it cannot be read.""" + try: + with open(os.path.join(proc_root, "self", "cgroup")) as handle: + path = _unified_path(handle.read()) + except OSError: + return None + return None if path is None else os.path.basename(path) + + +def unused_budget_mib(parent: str, skip: Sequence[str]) -> int: + """Returns the part of their budgets that the bounded commands whose scopes are in parent do not use yet. + + Probe scopes, the scopes named in skip, and scopes with no memory limit add nothing. + """ + try: + names = os.listdir(parent) + except OSError: + return 0 + unused = 0 + for name in names: + if not name.startswith(PREFIX + "-") or not name.endswith(".scope") or name.endswith("-probe.scope") or name in skip: + continue + try: + with open(os.path.join(parent, name, "memory.max")) as handle: + limit = handle.read().strip() + with open(os.path.join(parent, name, "memory.current")) as handle: + current = int(handle.read().strip()) + if limit == "max": + continue + unused += max(0, int(limit) - current) + except (OSError, ValueError): + # A scope ends between the listing and the read. + continue + return unused // (1024 * 1024) + + def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]: try: with open(os.path.join(proc_root, str(pid), "cgroup")) as handle: @@ -825,8 +895,17 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive] unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) - prefix = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, cap_usable) + choice = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, probe_cap) + prefix = choice[0] if choice is not None else None capped = prefix is not None + # Every scope of the user that systemd-run makes with no slice option goes to the slice of the probe. + scopes = scope_parent_directory(choice[1]) if choice is not None else None + # A wrapper that runs inside a bounded scope does its work in the budget of that scope. + skip = [name for name in (unit + ".scope", own_scope_name()) if name is not None] + + def read_outstanding() -> Optional[int]: + return None if scopes is None else unused_budget_mib(scopes, skip) + peak_file = os.path.join(directory, "peak-%s" % unit) if prefix is not None: inside = [sys.executable, os.path.abspath(__file__), "--inside-cap", peak_file, unit, "--"] @@ -858,7 +937,10 @@ def read_sample() -> Optional[int]: 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) + wait_for_memory( + wait_budget, settings.memory_wait_seconds, settings.poll_seconds, + headroom_mib=headroom_mib(settings.total_mib), read_outstanding=read_outstanding, + ) code, maxrss = run_command(command, child_environ, start_tracker) tracked = trackers[0].finish() if trackers else None finally: 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 1095d51..ba85c8a 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -748,32 +748,158 @@ def setUp(self): self.log = patcher.start() self.addCleanup(patcher.stop) - def wait(self, values, limit): + def wait(self, values, limit, outstanding=None, headroom=0): readings = list(values) sleeps = [] - result = bounded_run.wait_for_memory( - 4096, limit, 5.0, read_available=lambda: readings.pop(0), sleep=sleeps.append, + bounded_run.wait_for_memory( + 4096, limit, 5.0, headroom_mib=headroom, read_available=lambda: readings.pop(0), + read_outstanding=lambda: outstanding, sleep=sleeps.append, ) - return result, sleeps + return sleeps + + def lines(self): + return [call[0][0] for call in self.log.call_args_list] def test_starts_at_once_when_the_memory_is_free(self): - self.assertEqual(self.wait([8000], 300), (True, [])) + self.assertEqual(self.wait([8000], 300), []) def test_waits_until_the_memory_is_free(self): - self.assertEqual(self.wait([1000, 2000, 5000], 300), (True, [5.0, 5.0])) + self.assertEqual(self.wait([1000, 2000, 5000], 300), [5.0, 5.0]) - def test_starts_after_the_time_limit(self): - self.assertEqual(self.wait([1000, 1000, 1000], 10), (False, [5.0, 5.0])) + def test_does_not_start_after_the_time_limit_while_the_memory_is_not_free(self): + self.assertEqual(self.wait([1000] * 7 + [5000], 10), [5.0] * 7) + lines = self.lines() + self.assertTrue(lines[-1].endswith("; starting"), lines) + self.assertFalse(any(line.endswith("; starting") for line in lines[:-1]), lines) - def test_a_limit_of_zero_does_not_wait(self): - self.assertEqual(self.wait([1000], 0), (False, [])) + def test_a_limit_of_zero_does_not_start_while_the_memory_is_not_free(self): + self.assertEqual(self.wait([1000, 1000, 5000], 0), [5.0, 5.0]) - def test_a_start_after_the_time_limit_is_a_warning(self): - self.wait([1000], 0) - self.assertTrue(self.log.call_args[0][0].startswith("WARNING: ")) + def test_the_time_limit_is_the_time_between_two_lines_of_the_wait(self): + self.wait([1000] * 7 + [5000], 10) + waiting = [line for line in self.lines() if "waiting" in line] + self.assertEqual(len(waiting), 4, waiting) + self.assertIn("still waiting", waiting[1]) def test_starts_when_the_memory_is_not_readable(self): - self.assertEqual(self.wait([None], 300), (True, [])) + self.assertEqual(self.wait([None], 300), []) + self.assertEqual(self.lines(), ["cannot read the free memory; starting"]) + + def test_the_headroom_is_not_given_out(self): + self.assertEqual(self.wait([5000, 5200], 300, headroom=1024), [5.0]) + + def test_a_line_of_the_wait_names_each_part_of_the_count(self): + self.wait([4000, 8000], 300, outstanding=1500, headroom=1024) + self.assertEqual( + self.lines()[0], + "4000 MiB free, 1500 MiB of running budgets unused, 1024 MiB headroom, budget 4096 MiB; waiting", + ) + + def test_a_line_of_the_wait_says_when_the_unused_budgets_are_not_counted(self): + self.wait([8000], 300, outstanding=None, headroom=1024) + self.assertEqual( + self.lines()[0], + "8000 MiB free, unused running budgets not counted here, 1024 MiB headroom, budget 4096 MiB; starting", + ) + + +class HeadroomTest(unittest.TestCase): + def test_a_tenth_of_the_memory(self): + self.assertEqual(bounded_run.headroom_mib(27703), 2770) + + def test_never_less_than_the_minimum(self): + self.assertEqual(bounded_run.headroom_mib(4096), 1024) + + +class UnusedBudgetTest(unittest.TestCase): + """Gives unused_budget_mib a slice of the cgroup filesystem in a temporary directory.""" + + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.slice = os.path.join(self.base.name, "app.slice") + os.makedirs(self.slice) + + def scope(self, name, limit, current): + directory = os.path.join(self.slice, name) + os.makedirs(directory) + if limit is not None: + Path(directory, "memory.max").write_text(limit + "\n") + if current is not None: + Path(directory, "memory.current").write_text(current + "\n") + + def unused(self, skip=()): + return bounded_run.unused_budget_mib(self.slice, skip) + + def test_adds_the_unused_part_of_each_budget(self): + self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), str(1024 * 1024 ** 2)) + self.scope("bounded-run-11-bbbbbb.scope", str(2048 * 1024 ** 2), str(512 * 1024 ** 2)) + self.assertEqual(self.unused(), 5120 + 1536) + + def test_a_scope_above_its_budget_adds_nothing(self): + self.scope("bounded-run-10-aaaaaa.scope", str(1024 * 1024 ** 2), str(2048 * 1024 ** 2)) + self.assertEqual(self.unused(), 0) + + def test_skips_the_probe_scopes(self): + self.scope("bounded-run-10-aaaaaa-probe.scope", str(6144 * 1024 ** 2), "0") + self.assertEqual(self.unused(), 0) + + def test_skips_the_scopes_that_the_caller_names(self): + self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), "0") + self.scope("bounded-run-11-bbbbbb.scope", str(2048 * 1024 ** 2), "0") + self.assertEqual(self.unused(skip=["bounded-run-10-aaaaaa.scope"]), 2048) + + def test_skips_a_scope_with_no_budget(self): + self.scope("bounded-run-10-aaaaaa.scope", "max", "0") + self.assertEqual(self.unused(), 0) + + def test_skips_units_of_other_programs(self): + self.scope("editor-1.scope", str(6144 * 1024 ** 2), "0") + self.scope("bounded-run-10-aaaaaa.service", str(6144 * 1024 ** 2), "0") + self.assertEqual(self.unused(), 0) + + def test_skips_a_scope_that_ends_while_it_is_read(self): + self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), None) + self.scope("bounded-run-11-bbbbbb.scope", None, None) + self.assertEqual(self.unused(), 0) + + def test_no_slice_gives_nothing(self): + self.assertEqual(bounded_run.unused_budget_mib(os.path.join(self.base.name, "gone"), ()), 0) + + def test_the_slice_is_the_parent_of_the_probe_scope(self): + self.assertEqual( + bounded_run.scope_parent_directory("0::/user.slice/user@1000.service/app.slice/unit-1-probe.scope\n", "/cg"), + "/cg/user.slice/user@1000.service/app.slice", + ) + + def test_the_scope_of_this_process(self): + with tempfile.TemporaryDirectory() as proc: + os.mkdir(os.path.join(proc, "self")) + Path(proc, "self", "cgroup").write_text("0::/user.slice/app.slice/bounded-run-2-111111.scope\n") + self.assertEqual(bounded_run.own_scope_name(proc_root=proc), "bounded-run-2-111111.scope") + + def test_no_scope_of_this_process_without_its_cgroup(self): + with tempfile.TemporaryDirectory() as proc: + self.assertIsNone(bounded_run.own_scope_name(proc_root=proc)) + + def test_no_slice_without_a_cgroup_version_2_line(self): + self.assertIsNone(bounded_run.scope_parent_directory("", "/cg")) + self.assertIsNone(bounded_run.scope_parent_directory("4:memory:/user.slice/unit-1-probe.scope\n", "/cg")) + + def test_a_running_command_that_uses_little_of_a_large_budget_holds_back_the_next(self): + self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), str(1024 * 1024 ** 2)) + sleeps = [] + + def sleep(seconds): + sleeps.append(seconds) + shutil.rmtree(os.path.join(self.slice, "bounded-run-10-aaaaaa.scope")) + + with mock.patch.object(bounded_run, "log"): + bounded_run.wait_for_memory( + 4096, 300, 5.0, headroom_mib=1024, read_available=lambda: 8000, + read_outstanding=lambda: self.unused(), sleep=sleep, + ) + self.assertEqual(sleeps, [5.0]) class CapTest(unittest.TestCase): @@ -795,28 +921,28 @@ def test_prefix_without_the_oom_policy(self): def choose(self, answers): probes = [] - def usable(prefix): + def probe(prefix): probes.append(list(prefix)) return answers[len(probes) - 1] - return bounded_run.choose_cap_prefix(1024, 2, "unit-1", usable), probes + return bounded_run.choose_cap_prefix(1024, 2, "unit-1", probe), probes def test_uses_the_oom_policy_when_the_first_probe_passes(self): - prefix, probes = self.choose([True]) - self.assertEqual(prefix, bounded_run.cap_prefix(1024, 2, "unit-1")) + choice, probes = self.choose(["0::/app.slice/unit-1-probe.scope\n"]) + self.assertEqual(choice, (bounded_run.cap_prefix(1024, 2, "unit-1"), "0::/app.slice/unit-1-probe.scope\n")) self.assertEqual(len(probes), 1) self.assertIn("OOMPolicy=continue", probes[0]) self.assertNotIn("unit-1", probes[0]) def test_uses_the_prefix_without_the_oom_policy_when_only_the_second_probe_passes(self): - prefix, probes = self.choose([False, True]) - self.assertEqual(prefix, bounded_run.cap_prefix(1024, 2, "unit-1", oom_policy=False)) + choice, probes = self.choose([None, ""]) + self.assertEqual(choice, (bounded_run.cap_prefix(1024, 2, "unit-1", oom_policy=False), "")) self.assertEqual(len(probes), 2) self.assertNotIn("OOMPolicy=continue", probes[1]) def test_no_cap_when_both_probes_fail(self): - prefix, probes = self.choose([False, False]) - self.assertIsNone(prefix) + choice, probes = self.choose([None, None]) + self.assertIsNone(choice) self.assertEqual(len(probes), 2) def test_no_command_runs_on_a_different_system(self): @@ -826,47 +952,50 @@ def run(command, **keywords): calls.append(command) return subprocess.CompletedProcess(command, 0) - def usable(prefix): - return bounded_run.cap_usable(prefix, platform="darwin", which=lambda name: "/usr/bin/systemd-run", run=run) + def probe(prefix): + return bounded_run.probe_cap(prefix, platform="darwin", which=lambda name: "/usr/bin/systemd-run", run=run) - self.assertIsNone(bounded_run.choose_cap_prefix(1024, 2, "unit-1", usable)) + self.assertIsNone(bounded_run.choose_cap_prefix(1024, 2, "unit-1", probe)) self.assertEqual(calls, []) - def probe(self, platform, tool, code=0, error=None): + def probe(self, platform, tool, code=0, error=None, output=None): calls = [] def run(command, **keywords): calls.append(command) if error is not None: raise error - return subprocess.CompletedProcess(command, code) + return subprocess.CompletedProcess(command, code, stdout=output) - usable = bounded_run.cap_usable( + found = bounded_run.probe_cap( bounded_run.cap_prefix(1024, 2, "unit-1"), platform=platform, which=lambda name: tool, run=run, ) - return usable, calls + return found, calls - def test_usable_when_the_probe_succeeds(self): - usable, calls = self.probe("linux", "/usr/bin/systemd-run") - self.assertTrue(usable) - self.assertEqual(calls[0][-1], "true") + def test_the_probe_gives_the_cgroup_of_its_scope(self): + found, calls = self.probe("linux", "/usr/bin/systemd-run", output="0::/app.slice/unit-1.scope\n") + self.assertEqual(found, "0::/app.slice/unit-1.scope\n") + self.assertEqual(calls[0][-2:], ["cat", "/proc/self/cgroup"]) self.assertIn("CPUQuota=200%", calls[0]) + def test_a_probe_with_no_output_is_usable(self): + self.assertEqual(self.probe("linux", "/usr/bin/systemd-run")[0], "") + def test_not_usable_when_the_probe_fails(self): - self.assertFalse(self.probe("linux", "/usr/bin/systemd-run", code=1)[0]) + self.assertIsNone(self.probe("linux", "/usr/bin/systemd-run", code=1)[0]) def test_not_usable_when_the_probe_does_not_return(self): error = subprocess.TimeoutExpired("systemd-run", 15) - self.assertFalse(self.probe("linux", "/usr/bin/systemd-run", error=error)[0]) + self.assertIsNone(self.probe("linux", "/usr/bin/systemd-run", error=error)[0]) def test_not_usable_without_the_tool(self): - usable, calls = self.probe("linux", None) - self.assertFalse(usable) + found, calls = self.probe("linux", None) + self.assertIsNone(found) self.assertEqual(calls, []) def test_not_usable_on_a_different_system(self): - usable, calls = self.probe("darwin", "/usr/bin/systemd-run") - self.assertFalse(usable) + found, calls = self.probe("darwin", "/usr/bin/systemd-run") + self.assertIsNone(found) self.assertEqual(calls, []) @@ -1220,7 +1349,7 @@ def test_a_child_of_this_process_runs_with_no_pipe(self): class BoundedCleanupTest(unittest.TestCase): - """Calls bounded() in this process, with run_command and cap_usable replaced by stubs. + """Calls bounded() in this process, with run_command and probe_cap replaced by stubs. No real command, no real cgroup, and no real subprocess run outside the stubs. """ @@ -1256,7 +1385,7 @@ def fake_run_command(command, environ, on_start=None): options.memory = "2G" options.command = [sys.executable, "-c", "pass"] - with mock.patch.object(bounded_run, "cap_usable", return_value=True), \ + with mock.patch.object(bounded_run, "probe_cap", return_value=""), \ mock.patch.object(bounded_run, "run_command", fake_run_command): with self.assertRaises(RuntimeError): bounded_run.bounded(options, self.environ) @@ -1280,14 +1409,51 @@ def fake_run_command(command, environ, on_start=None): options.memory = "64G" options.command = [sys.executable, "-c", "pass"] - with mock.patch.object(bounded_run, "cap_usable", return_value=True), \ - mock.patch.object(bounded_run, "wait_for_memory", side_effect=lambda budget, *rest: waits.append(budget)), \ + with mock.patch.object(bounded_run, "probe_cap", return_value=""), \ + mock.patch.object(bounded_run, "wait_for_memory", side_effect=lambda budget, *rest, **keywords: waits.append(budget)), \ mock.patch.object(bounded_run, "run_command", fake_run_command): self.assertEqual(bounded_run.bounded(options, self.environ), 0) self.assertEqual(waits, [4096]) self.assertIn("MemoryMax=4096M", commands[0]) + def wait_arguments(self, probe_output): + waits = [] + options = bounded_run.Options() + options.memory = "1G" + options.command = [sys.executable, "-c", "pass"] + with mock.patch.object(bounded_run, "probe_cap", return_value=probe_output), \ + mock.patch.object(bounded_run, "own_scope_name", return_value="bounded-run-2-111111.scope"), \ + mock.patch.object(bounded_run, "wait_for_memory", side_effect=lambda *arguments, **keywords: waits.append(keywords)), \ + mock.patch.object(bounded_run, "run_command", return_value=(0, 0)): + self.assertEqual(bounded_run.bounded(options, self.environ), 0) + return waits[0] + + def test_the_wait_keeps_a_headroom_of_the_memory_of_the_machine(self): + self.assertEqual(self.wait_arguments(None)["headroom_mib"], bounded_run.headroom_mib(4096)) + + def test_the_wait_counts_the_unused_budgets_beside_the_scope_of_the_probe(self): + calls = [] + + def unused(parent, skip): + calls.append((parent, list(skip))) + return 777 + + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + keywords = self.wait_arguments(output) + with mock.patch.object(bounded_run, "unused_budget_mib", unused): + self.assertEqual(keywords["read_outstanding"](), 777) + parent, skip = calls[0] + self.assertEqual(parent, "/sys/fs/cgroup/user.slice/app.slice") + self.assertIn("bounded-run-2-111111.scope", skip) + self.assertTrue(any(re.match(r"^bounded-run-%d-[0-9a-f]{6}\.scope$" % os.getpid(), name) for name in skip), skip) + + def test_the_wait_counts_no_unused_budget_without_a_cap(self): + self.assertIsNone(self.wait_arguments(None)["read_outstanding"]()) + + def test_the_wait_counts_no_unused_budget_without_a_cgroup_version_2(self): + self.assertIsNone(self.wait_arguments("")["read_outstanding"]()) + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" @@ -1774,9 +1940,8 @@ def test_a_measurement_with_a_budget_takes_the_slots_of_the_budget(self): def test_a_first_measurement_waits_for_the_memory_of_the_default_budget_only(self): reads = [] - def wait(budget, limit, poll): + def wait(budget, limit, poll, **rest): reads.append(budget) - return True options = bounded_run.Options() options.measure = True @@ -1819,7 +1984,7 @@ def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self): @unittest.skipUnless( - bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.cap_usable) is not None, + bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None, "no hard cap on this machine", ) class HardCapTest(WrapperProcessCase): From 8983a30488e11538664ae158d044961ea55895e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:43:45 +0100 Subject: [PATCH 02/10] fix(skills/bounding-heavy-commands): count a server that a heavy command uses A test suite that talks to a server outside the queue moves its load to that server. A runner that reuses a development server already listening on its port makes that server compile and grow, and no budget or cap covers it. In a baseline test, an agent saw that the growth was outside the budget and ran the suite anyway, because the skill had no rule for it. The skill now treats such a server as a part of the heavy command: give the run a port of its own so that the runner starts the server inside the bounded command, or start the server through the wrapper. Never run against a server outside the queue, and never stop it. Refs #55 Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 9f49533..28e6864 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -28,6 +28,8 @@ Skip for commands that only read (listing files, searching, version-control quer A command that does not end, such as a server or a watch mode, holds its memory in the queue until it stops. Start it through the wrapper, and stop it when your work with it is done. +A server that a heavy command talks to is a part of that command: a development server, a database, or a container that a test suite sends its requests to. The work of the suite grows the server, and the budget of the suite does not count a server outside it. When the test runner can start the server itself, let it: give the run a port that no running server uses, so that the server starts inside the bounded command and its budget covers it. When the server must run on its own, start it through the wrapper. Do not run a heavy command against a server that runs outside the queue, also when it already listens on the port: an agent or a person started it without the wrapper, and the queue cannot count it. Do not stop that server either, because it belongs to someone else. Use a port of your own. + ## The wrapper ``` @@ -158,6 +160,7 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "The port was in use, I'll back off once and retry" | Two commands wanted one resource. Record it as `--exclusive` and run through the wrapper. | | "My command timed out, the tests must hang" | It was waiting in the queue. Run it in the background with no short timeout. | | "The subagent will find the test command on its own" | It will find the plain one. Put the bounded command lines in its prompt. | +| "The server is already running on the port, the tests can reuse it" | The queue does not count a server that runs outside it, and the tests make it grow. Give the run a port of its own, so that the runner starts the server inside the bounded command. | | "Four subagents is too many for this machine, I'll dispatch two" | The queue limits the commands. Fewer subagents only makes the work slower. | | "Project memory is off, so there is no record to keep" | Discover in this session and keep the result in context. The rule does not depend on the memory. | | "The wrapper cannot run here, so none of this applies" | The fallback applies: one heavy command at a time, toolchain parallelism at half or less, and say so. | From 85def65d074729ca2e62bb3d2c58cc1ec2a9b687 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:14:25 +0100 Subject: [PATCH 03/10] fix(skills/bounding-heavy-commands): let a whole-queue budget start and keep the tests off the machine's load A budget of the whole queue could never start. The wait needed the budget plus a headroom of max(1 GiB, a tenth of the memory) free, and the queue already leaves a reserve of max(2 GiB, a quarter of the memory) outside it. On a 27703 MiB machine a budget of the 20480 MiB queue needed about 23250 MiB free, which a machine with a desktop never has, so the command waited forever. headroom_mib now takes the budget and the memory of the queue and never lets the two together need more than the queue, so the headroom shrinks to zero as the budget nears the whole queue and the reserve is the floor for what stays outside. The tests depended on the load of the real machine. The wrappers that the process tests start, and the in-process bounded() tests, read the real free memory, and with the hard cap they counted the unused budgets of every real bounded-run scope of the user. On a busy machine they waited past their timeouts. The new test-only variable BOUNDED_RUN_FREE_MIB, listed in the usage text with the other values for the tests, gives the wait a fixed free memory and counts no unused budgets. The tests of the counting itself still use fake cgroup trees and do not set it. Refs #55 Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 2 +- .../scripts/bounded_run.py | 23 +++++-- .../scripts/tests/test_bounded_run.py | 67 +++++++++++++++++-- 3 files changed, 81 insertions(+), 11 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 28e6864..94b1a06 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -43,7 +43,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--exclusive ` | A resource that only one command may hold at a time, such as a fixed port. You choose the name. The wrapper keeps the names of each repository apart, and all worktrees of one repository share them. Repeat the option for each resource. | | `--measure` | Also print a suggested budget. Discovery uses it. With no `--memory`, the command runs alone in the queue. | -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 wait has no time limit: the command does not start before its memory is free, and the wrapper prints a line at intervals while it waits. Each line that the wrapper prints starts with `bounded-run:`. Its exit code is the command's exit code. Exit code 125, with a `bounded-run:` line that names a fault and with no line for the budget and the peak, means that the wrapper itself failed (see §When the wrapper cannot run). +The wrapper does four things in sequence. It waits for its turn in the queue. It waits until the memory of its budget is free. It runs the command. It prints the budget and the measured peak on the error stream. For the wait, the free memory is the memory that the machine has free now, less the part of their budgets that the running bounded commands do not use yet, less a headroom for the programs outside the queue. The headroom is a tenth of the memory of the machine, and at least 1 GiB. The budget and the headroom together never need more than the memory of the queue, so a budget of the whole queue does not wait for a headroom. The wait has no time limit: the command does not start before its memory is free, and the wrapper prints a line at intervals while it waits. Each line that the wrapper prints starts with `bounded-run:`. Its exit code is the command's exit code. Exit code 125, with a `bounded-run:` line that names a fault and with no line for the budget and the peak, means that the wrapper itself failed (see §When the wrapper cannot run). The wrapper sets `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB` in the environment of the command, from `--cpus` and `--memory`. A recorded command line can read them and hand them to the toolchain's own parallelism and memory settings. You do not set them: you change them with the two options. diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 413ef78..8f444ab 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -25,6 +25,7 @@ Values for the tests of this script, and for its maintainers: BOUNDED_RUN_TOTAL_MIB memory of the machine, in place of the measured value + BOUNDED_RUN_FREE_MIB free memory for the wait, in place of the measured free memory less the unused budgets BOUNDED_RUN_POLL_SECONDS time between two tries for the slots (default 2) BOUNDED_RUN_SAMPLE_SECONDS time between two memory samples (default 1) BOUNDED_RUN_LOCK_DIR directory of the lock files, as an absolute path @@ -188,9 +189,13 @@ def default_reserve_mib(total_mib: int) -> int: return max(MINIMUM_RESERVE_MIB, total_mib // 4) -def headroom_mib(total_mib: int) -> int: - """Returns the memory that the wait for free memory keeps free for the programs outside the queue.""" - return max(MINIMUM_HEADROOM_MIB, total_mib // 10) +def headroom_mib(total_mib: int, budget_mib: int, queue_mib: int) -> int: + """Returns the memory that the wait for free memory keeps free beside the budget for the programs outside the queue. + + The budget and the headroom together never need more than queue_mib, so a budget of the whole queue gets no headroom. + """ + # The reserve of the queue already keeps memory for the programs outside it. + return max(0, min(max(MINIMUM_HEADROOM_MIB, total_mib // 10), queue_mib - budget_mib)) def slot_count(total_mib: int, slot_mib: int, reserve_mib: int) -> int: @@ -225,6 +230,8 @@ def __init__(self, environ: Mapping[str, str], read_total: Callable[[], int] = t self.memory_wait_seconds = _number(environ, "BOUNDED_RUN_MEMORY_WAIT_SECONDS", MEMORY_WAIT_SECONDS) self.sample_seconds = _number(environ, "BOUNDED_RUN_SAMPLE_SECONDS", SAMPLE_SECONDS) self.no_cap = bool(environ.get("BOUNDED_RUN_NO_CAP")) + free = environ.get("BOUNDED_RUN_FREE_MIB") + self.free_mib = int(_number(environ, "BOUNDED_RUN_FREE_MIB", 0)) if free else None if self.slot_mib <= 0: raise WrapperError("BOUNDED_RUN_SLOT_MIB must be more than zero") # A loop that sleeps for zero seconds never ends its wait and takes a full processor. @@ -903,8 +910,13 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: # A wrapper that runs inside a bounded scope does its work in the budget of that scope. skip = [name for name in (unit + ".scope", own_scope_name()) if name is not None] + def read_available() -> Optional[int]: + return available_memory_mib() if settings.free_mib is None else settings.free_mib + def read_outstanding() -> Optional[int]: - return None if scopes is None else unused_budget_mib(scopes, skip) + if settings.free_mib is not None or scopes is None: + return None + return unused_budget_mib(scopes, skip) peak_file = os.path.join(directory, "peak-%s" % unit) if prefix is not None: @@ -939,7 +951,8 @@ def read_sample() -> Optional[int]: try: wait_for_memory( wait_budget, settings.memory_wait_seconds, settings.poll_seconds, - headroom_mib=headroom_mib(settings.total_mib), read_outstanding=read_outstanding, + headroom_mib=headroom_mib(settings.total_mib, wait_budget, most), + read_available=read_available, read_outstanding=read_outstanding, ) code, maxrss = run_command(command, child_environ, start_tracker) tracked = trackers[0].finish() 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 ba85c8a..435d748 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -60,6 +60,10 @@ def test_says_who_the_test_values_are_for(self): self.assertIn("Values for the tests of this script, and for its maintainers:", text) self.assertNotIn("diagnosis", text) + def test_lists_the_free_memory_for_the_tests(self): + values = bounded_run.__doc__.split("Values for the tests of this script, and for its maintainers:")[1] + self.assertIn("BOUNDED_RUN_FREE_MIB", values) + class SizeTest(unittest.TestCase): def test_reads_gibibytes(self): @@ -228,6 +232,10 @@ def test_defaults(self): self.assertEqual(settings.poll_seconds, 2.0) self.assertEqual(settings.memory_wait_seconds, 300.0) self.assertFalse(settings.no_cap) + self.assertIsNone(settings.free_mib) + + def test_a_set_free_memory(self): + self.assertEqual(bounded_run.Settings({"BOUNDED_RUN_FREE_MIB": "3000"}, read_total=lambda: 1).free_mib, 3000) def test_overrides(self): settings = bounded_run.Settings({ @@ -805,10 +813,16 @@ def test_a_line_of_the_wait_says_when_the_unused_budgets_are_not_counted(self): class HeadroomTest(unittest.TestCase): def test_a_tenth_of_the_memory(self): - self.assertEqual(bounded_run.headroom_mib(27703), 2770) + self.assertEqual(bounded_run.headroom_mib(27703, 2048, 20480), 2770) def test_never_less_than_the_minimum(self): - self.assertEqual(bounded_run.headroom_mib(4096), 1024) + self.assertEqual(bounded_run.headroom_mib(4096, 1024, 4096), 1024) + + def test_no_headroom_for_a_budget_of_the_whole_queue(self): + self.assertEqual(bounded_run.headroom_mib(27703, 20480, 20480), 0) + + 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 UnusedBudgetTest(unittest.TestCase): @@ -1372,6 +1386,7 @@ def setUp(self): "BOUNDED_RUN_POLL_SECONDS": "0.05", "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", "BOUNDED_RUN_SAMPLE_SECONDS": "0.1", + "BOUNDED_RUN_FREE_MIB": "1048576", }) def test_the_peak_file_is_removed_when_the_run_fails_after_the_start(self): @@ -1417,20 +1432,61 @@ def fake_run_command(command, environ, on_start=None): self.assertEqual(waits, [4096]) self.assertIn("MemoryMax=4096M", commands[0]) - def wait_arguments(self, probe_output): + def wait_arguments(self, probe_output, environ=None): waits = [] options = bounded_run.Options() options.memory = "1G" options.command = [sys.executable, "-c", "pass"] + if environ is None: + environ = dict(self.environ) + del environ["BOUNDED_RUN_FREE_MIB"] with mock.patch.object(bounded_run, "probe_cap", return_value=probe_output), \ mock.patch.object(bounded_run, "own_scope_name", return_value="bounded-run-2-111111.scope"), \ mock.patch.object(bounded_run, "wait_for_memory", side_effect=lambda *arguments, **keywords: waits.append(keywords)), \ mock.patch.object(bounded_run, "run_command", return_value=(0, 0)): - self.assertEqual(bounded_run.bounded(options, self.environ), 0) + self.assertEqual(bounded_run.bounded(options, environ), 0) return waits[0] def test_the_wait_keeps_a_headroom_of_the_memory_of_the_machine(self): - self.assertEqual(self.wait_arguments(None)["headroom_mib"], bounded_run.headroom_mib(4096)) + self.assertEqual(self.wait_arguments(None)["headroom_mib"], bounded_run.headroom_mib(4096, 1024, 4096)) + + def run_with_free_memory(self, memory, total, free): + options = bounded_run.Options() + options.memory = memory + options.command = [sys.executable, "-c", "pass"] + environ = dict(self.environ, BOUNDED_RUN_TOTAL_MIB=str(total), BOUNDED_RUN_RESERVE_MIB="", BOUNDED_RUN_FREE_MIB=str(free)) + + real_wait = bounded_run.wait_for_memory + + def sleep(seconds): + raise AssertionError("the command waits") + + def wait(*arguments, **keywords): + return real_wait(*arguments, sleep=sleep, **keywords) + + with mock.patch.object(bounded_run, "probe_cap", return_value=None), \ + mock.patch.object(bounded_run, "wait_for_memory", wait), \ + mock.patch.object(bounded_run, "run_command", return_value=(0, 0)): + return bounded_run.bounded(options, environ) + + def test_a_budget_of_the_whole_queue_starts_when_the_memory_of_the_queue_is_free(self): + 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): + 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_starts_with_its_headroom_free(self): + self.assertEqual(self.run_with_free_memory("2G", 27703, 2048 + bounded_run.headroom_mib(27703, 2048, 20480)), 0) + + def test_a_set_free_memory_replaces_the_free_memory_and_the_unused_budgets(self): + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + keywords = self.wait_arguments(output, dict(self.environ, BOUNDED_RUN_FREE_MIB="3000")) + with mock.patch.object(bounded_run, "unused_budget_mib", side_effect=AssertionError("unused")), \ + mock.patch.object(bounded_run, "available_memory_mib", side_effect=AssertionError("available")): + self.assertEqual(keywords["read_available"](), 3000) + self.assertIsNone(keywords["read_outstanding"]()) def test_the_wait_counts_the_unused_budgets_beside_the_scope_of_the_probe(self): calls = [] @@ -1473,6 +1529,7 @@ def setUp(self): "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", "BOUNDED_RUN_SAMPLE_SECONDS": "0.1", "BOUNDED_RUN_NO_CAP": "1", + "BOUNDED_RUN_FREE_MIB": "1048576", "EVENTS": self.events, }) self.processes = [] From e6d6456bab38cf947c8b041220d871612552abf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:43:35 +0100 Subject: [PATCH 04/10] fix(skills/bounding-heavy-commands): let one wrapper at a time check the memory and start Two wrappers that hold different slots could both read the free memory before either command had a scope, both pass the check, and together promise more memory than the machine has. The check now runs under a lock file that all wrappers share. The wrapper keeps the lock until the scope of its command is in the slice where the next check counts it, or for at most 5 seconds. A wrapper that waits for memory frees the lock between two readings, so a command that fits can still start. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 42 ++++++++++- .../scripts/tests/test_bounded_run.py | 70 ++++++++++++++++++- 2 files changed, 110 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 8f444ab..33414d7 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -62,6 +62,7 @@ POLL_SECONDS = 2.0 MEMORY_WAIT_SECONDS = 300.0 SAMPLE_SECONDS = 1.0 +SCOPE_WAIT_SECONDS = 5.0 MARGIN_EXACT = 0.25 MARGIN_APPROXIMATE = 0.5 BUDGET_STEP_MIB = 256 @@ -471,15 +472,19 @@ def wait_for_memory( read_available: Callable[[], Optional[int]] = available_memory_mib, read_outstanding: Callable[[], Optional[int]] = lambda: None, sleep: Callable[[float], None] = time.sleep, + lock: Callable[[], None] = lambda: None, + unlock: Callable[[], None] = lambda: None, ) -> 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. + The call returns with lock held: the caller calls unlock once the new command counts in read_outstanding. """ waited = 0.0 next_line = 0.0 while True: + lock() available = read_available() if available is None: log("cannot read the free memory; starting") @@ -493,6 +498,7 @@ def wait_for_memory( if waited >= next_line: log(state + ("; waiting" if waited == 0 else "; still waiting after %ds" % waited)) next_line = waited + interval_seconds + unlock() sleep(poll_seconds) waited += poll_seconds @@ -591,6 +597,18 @@ def unused_budget_mib(parent: str, skip: Sequence[str]) -> int: return unused // (1024 * 1024) +def wait_for_scope(parent: str, unit: str, limit_seconds: float, sleep: Callable[[float], None] = time.sleep) -> bool: + """Returns True when the scope of the unit is in parent, or False when it is not there after limit_seconds.""" + path = os.path.join(parent, unit + ".scope") + waited = 0.0 + while not os.path.isdir(path): + if waited >= limit_seconds: + return False + sleep(0.02) + waited += 0.02 + return True + + def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]: try: with open(os.path.join(proc_root, str(pid), "cgroup")) as handle: @@ -946,6 +964,26 @@ def read_sample() -> Optional[int]: tracker.start() trackers.append(tracker) + # Without one lock over the check and the start, two wrappers with different slots both pass the check before either scope counts. + memory_lock_path = os.path.join(directory, "memory.lock") + memory_lock: List[int] = [] + + def lock_memory() -> None: + descriptor = _lock(memory_lock_path, wait=True) + if descriptor is not None: + memory_lock.append(descriptor) + + def unlock_memory() -> None: + while memory_lock: + os.close(memory_lock.pop()) + + def on_start(pid: int) -> None: + start_tracker(pid) + if scopes is not None and memory_lock: + if not wait_for_scope(scopes, unit, SCOPE_WAIT_SECONDS): + log("the scope of the command did not appear after %ds; the next command may not count its budget" % SCOPE_WAIT_SECONDS) + unlock_memory() + reported: Optional[int] = None reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds) try: @@ -953,10 +991,12 @@ def read_sample() -> Optional[int]: 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, ) - code, maxrss = run_command(command, child_environ, start_tracker) + code, maxrss = run_command(command, child_environ, on_start) tracked = trackers[0].finish() if trackers else None finally: + unlock_memory() 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 435d748..de02049 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -9,6 +9,7 @@ import subprocess import sys import tempfile +import threading import time import unittest from pathlib import Path @@ -793,6 +794,20 @@ def test_starts_when_the_memory_is_not_readable(self): self.assertEqual(self.wait([None], 300), []) self.assertEqual(self.lines(), ["cannot read the free memory; starting"]) + def test_each_reading_holds_the_lock_and_the_call_returns_with_it_held(self): + events = [] + readings = [1000, 5000] + + def read(): + events.append("read") + return readings.pop(0) + + bounded_run.wait_for_memory( + 4096, 300, 5.0, read_available=read, sleep=lambda seconds: events.append("sleep"), + lock=lambda: events.append("lock"), unlock=lambda: events.append("unlock"), + ) + self.assertEqual(events, ["lock", "read", "unlock", "sleep", "lock", "read"]) + def test_the_headroom_is_not_given_out(self): self.assertEqual(self.wait([5000, 5200], 300, headroom=1024), [5.0]) @@ -1504,6 +1519,59 @@ def unused(parent, skip): self.assertIn("bounded-run-2-111111.scope", skip) self.assertTrue(any(re.match(r"^bounded-run-%d-[0-9a-f]{6}\.scope$" % os.getpid(), name) for name in skip), skip) + def run_with_scopes(self, appear_after): + """Runs bounded() with a capped command whose scope appears in a temporary slice after appear_after seconds, or never when None. + + Returns whether the memory lock was free while the scope did not exist yet, and whether it was free when the command started. + """ + scopes = os.path.join(self.base.name, "slice") + os.makedirs(scopes) + lock_path = os.path.join(self.directory, "memory.lock") + free = {} + + def lock_is_free(): + descriptor = bounded_run._try_lock(lock_path) + if descriptor is None: + return False + os.close(descriptor) + return True + + def fake_run_command(command, environ, on_start=None): + unit = command[command.index("--inside-cap") + 2] + + def appear(): + time.sleep(0.2) + free["before the scope"] = lock_is_free() + if appear_after is not None: + os.mkdir(os.path.join(scopes, unit + ".scope")) + + thread = threading.Thread(target=appear) + thread.start() + on_start(os.getpid()) + thread.join() + free["at the start"] = lock_is_free() + 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="0::/slice/bounded-run-1-000000-probe.scope\n"), \ + mock.patch.object(bounded_run, "scope_parent_directory", return_value=scopes), \ + mock.patch.object(bounded_run, "SCOPE_WAIT_SECONDS", 0.5), \ + mock.patch.object(bounded_run, "run_command", fake_run_command): + self.assertEqual(bounded_run.bounded(options, self.environ), 0) + return free + + def test_the_next_memory_check_waits_until_the_scope_of_the_command_counts(self): + free = self.run_with_scopes(appear_after=0.2) + self.assertEqual(free, {"before the scope": False, "at the start": True}) + + def test_a_scope_that_never_appears_frees_the_memory_check_after_a_time_limit(self): + started = time.monotonic() + free = self.run_with_scopes(appear_after=None) + self.assertEqual(free, {"before the scope": False, "at the start": True}) + self.assertLess(time.monotonic() - started, 5) + def test_the_wait_counts_no_unused_budget_without_a_cap(self): self.assertIsNone(self.wait_arguments(None)["read_outstanding"]()) @@ -1856,7 +1924,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 4 inherited 0\n", errors) + self.assertEqual(output, "locks 5 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 1576d9ded849eef9d8accbd1ff7e4a947e47f485 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:08:16 +0100 Subject: [PATCH 05/10] fix(skills/bounding-heavy-commands): keep the memory lock until the new scope has its limit systemd makes the directory of a scope before it writes memory.max, and the count of unused budgets skips a scope whose limit is still max. The wrapper freed the memory lock when the directory appeared, so the next check could run before the new budget counted. The wrapper now waits until memory.max holds a number and memory.current can be read, which is what the count needs. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 17 +++++++++-- .../scripts/tests/test_bounded_run.py | 29 ++++++++++++------- 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 33414d7..7fde3ca 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -597,11 +597,24 @@ def unused_budget_mib(parent: str, skip: Sequence[str]) -> int: return unused // (1024 * 1024) +def _scope_counts(path: str) -> bool: + try: + with open(os.path.join(path, "memory.max")) as handle: + limit = handle.read().strip() + with open(os.path.join(path, "memory.current")) as handle: + int(handle.read().strip()) + except (OSError, ValueError): + return False + return limit.isdigit() + + def wait_for_scope(parent: str, unit: str, limit_seconds: float, sleep: Callable[[float], None] = time.sleep) -> bool: - """Returns True when the scope of the unit is in parent, or False when it is not there after limit_seconds.""" + """Returns True when the scope of the unit is in parent with its memory limit, as unused_budget_mib counts it, + or False when it is not there after limit_seconds.""" path = os.path.join(parent, unit + ".scope") waited = 0.0 - while not os.path.isdir(path): + # systemd makes the directory of the scope before it writes the limit. + while not _scope_counts(path): if waited >= limit_seconds: return False sleep(0.02) 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 de02049..f77e6ec 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1519,10 +1519,11 @@ def unused(parent, skip): self.assertIn("bounded-run-2-111111.scope", skip) self.assertTrue(any(re.match(r"^bounded-run-%d-[0-9a-f]{6}\.scope$" % os.getpid(), name) for name in skip), skip) - def run_with_scopes(self, appear_after): - """Runs bounded() with a capped command whose scope appears in a temporary slice after appear_after seconds, or never when None. + def run_with_scopes(self, appears): + """Runs bounded() with a capped command whose scope appears in a temporary slice in two steps, or never when appears is false. - Returns whether the memory lock was free while the scope did not exist yet, and whether it was free when the command started. + The scope appears first with no memory limit, then with its limit. Returns whether the memory lock was free before the + scope, before its limit, and when the command started. """ scopes = os.path.join(self.base.name, "slice") os.makedirs(scopes) @@ -1537,13 +1538,19 @@ def lock_is_free(): return True def fake_run_command(command, environ, on_start=None): - unit = command[command.index("--inside-cap") + 2] + scope = os.path.join(scopes, command[command.index("--inside-cap") + 2] + ".scope") def appear(): time.sleep(0.2) free["before the scope"] = lock_is_free() - if appear_after is not None: - os.mkdir(os.path.join(scopes, unit + ".scope")) + if appears: + os.mkdir(scope) + Path(scope, "memory.max").write_text("max\n") + time.sleep(0.2) + free["before the limit"] = lock_is_free() + if appears: + Path(scope, "memory.current").write_text("0\n") + Path(scope, "memory.max").write_text("%d\n" % (1024 * 1024 ** 2)) thread = threading.Thread(target=appear) thread.start() @@ -1557,19 +1564,19 @@ def appear(): options.command = [sys.executable, "-c", "pass"] with mock.patch.object(bounded_run, "probe_cap", return_value="0::/slice/bounded-run-1-000000-probe.scope\n"), \ mock.patch.object(bounded_run, "scope_parent_directory", return_value=scopes), \ - mock.patch.object(bounded_run, "SCOPE_WAIT_SECONDS", 0.5), \ + mock.patch.object(bounded_run, "SCOPE_WAIT_SECONDS", 1.0), \ mock.patch.object(bounded_run, "run_command", fake_run_command): self.assertEqual(bounded_run.bounded(options, self.environ), 0) return free def test_the_next_memory_check_waits_until_the_scope_of_the_command_counts(self): - free = self.run_with_scopes(appear_after=0.2) - self.assertEqual(free, {"before the scope": False, "at the start": True}) + free = self.run_with_scopes(appears=True) + self.assertEqual(free, {"before the scope": False, "before the limit": False, "at the start": True}) def test_a_scope_that_never_appears_frees_the_memory_check_after_a_time_limit(self): started = time.monotonic() - free = self.run_with_scopes(appear_after=None) - self.assertEqual(free, {"before the scope": False, "at the start": True}) + free = self.run_with_scopes(appears=False) + self.assertEqual(free, {"before the scope": False, "before the limit": False, "at the start": True}) self.assertLess(time.monotonic() - started, 5) def test_the_wait_counts_no_unused_budget_without_a_cap(self): From 9b6ab6bf8a5a6026cd417cb3e8e777d9fad955a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:19:24 +0100 Subject: [PATCH 06/10] fix(skills/bounding-heavy-commands): read the unused budgets before the free memory A running command that grows between the two reads lowers both values. With the free memory read first, the check could pair an old, high free memory with a new, low unused budget, and start a command that neither true state lets start. In the new order, growth between the reads can only make the free memory look smaller. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 3 ++- .../scripts/tests/test_bounded_run.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 7fde3ca..1bc1ccc 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -485,11 +485,12 @@ def wait_for_memory( next_line = 0.0 while True: lock() + # A running command that grows between the two reads lowers both values. In this order the growth can only make the free memory look smaller. + outstanding = read_outstanding() available = read_available() if available is None: log("cannot read the free memory; starting") return - outstanding = read_outstanding() counted = "unused running budgets not counted here" if outstanding is None else "%d MiB of running budgets unused" % outstanding state = "%d MiB free, %s, %d MiB headroom, budget %d MiB" % (available, counted, headroom_mib, budget_mib) if available - (outstanding or 0) - headroom_mib >= budget_mib: 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 f77e6ec..6441453 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -808,6 +808,22 @@ def read(): ) self.assertEqual(events, ["lock", "read", "unlock", "sleep", "lock", "read"]) + def test_reads_the_unused_budgets_before_the_free_memory(self): + events = [] + + def read_available(): + events.append("free") + return 8000 + + def read_outstanding(): + events.append("unused") + return 0 + + bounded_run.wait_for_memory( + 4096, 300, 5.0, read_available=read_available, read_outstanding=read_outstanding, sleep=lambda seconds: None, + ) + self.assertEqual(events, ["unused", "free"]) + def test_the_headroom_is_not_given_out(self): self.assertEqual(self.wait([5000, 5200], 300, headroom=1024), [5.0]) From 0b368dba3b5e674154a865197467047baf6413c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:19:25 +0100 Subject: [PATCH 07/10] docs(skills/bounding-heavy-commands): say that the wait counts no unused budget on cgroup version 1 The count of unused budgets reads the cgroup version 2 tree. On a system with cgroup version 1 the hard cap can work while the wait counts nothing, and the skill named only the case with no cap. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 94b1a06..e9ccd15 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -47,7 +47,7 @@ The wrapper does four things in sequence. It waits for its turn in the queue. It The wrapper sets `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB` in the environment of the command, from `--cpus` and `--memory`. A recorded command line can read them and hand them to the toolchain's own parallelism and memory settings. You do not set them: you change them with the two options. -On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. Without the cap, the wait does not count the unused budgets of the running commands. When a recorded command ends with exit code 137 and the wrapper reports a peak near the budget, the cap stopped it: the command grew. Measure it again with `--measure` and `--memory` at two times the budget, and correct the record. +On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. Without the cap, and on a system with cgroup version 1, the wait does not count the unused budgets of the running commands. When a recorded command ends with exit code 137 and the wrapper reports a peak near the budget, the cap stopped it: the command grew. Measure it again with `--measure` and `--memory` at two times the budget, and correct the record. ## The record From f047dacea36e4d184dcf0988d33c3607b651a671 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:28:16 +0100 Subject: [PATCH 08/10] fix(skills/bounding-heavy-commands): count the larger of two unused-budget reads around the free memory The order of the reads made the check safe only while running commands grew. A command that freed memory between the two reads raised the free memory and left the unused count too small. The wait now reads the unused budgets before and after the free memory and counts the larger value, which is safe in both directions. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 7 +++++-- .../scripts/tests/test_bounded_run.py | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 1bc1ccc..ca0dff2 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -485,12 +485,15 @@ def wait_for_memory( next_line = 0.0 while True: lock() - # A running command that grows between the two reads lowers both values. In this order the growth can only make the free memory look smaller. - outstanding = read_outstanding() + # 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 + after = read_outstanding() + outstanding = None if before is None or after is None else max(before, after) counted = "unused running budgets not counted here" if outstanding is None else "%d MiB of running budgets unused" % outstanding state = "%d MiB free, %s, %d MiB headroom, budget %d MiB" % (available, counted, headroom_mib, budget_mib) if available - (outstanding or 0) - headroom_mib >= budget_mib: 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 6441453..3c9b5d2 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -808,7 +808,7 @@ def read(): ) self.assertEqual(events, ["lock", "read", "unlock", "sleep", "lock", "read"]) - def test_reads_the_unused_budgets_before_the_free_memory(self): + def test_reads_the_unused_budgets_before_and_after_the_free_memory(self): events = [] def read_available(): @@ -822,7 +822,19 @@ def read_outstanding(): bounded_run.wait_for_memory( 4096, 300, 5.0, read_available=read_available, read_outstanding=read_outstanding, sleep=lambda seconds: None, ) - self.assertEqual(events, ["unused", "free"]) + self.assertEqual(events, ["unused", "free", "unused"]) + + def test_counts_the_larger_of_the_unused_budgets_read_before_and_after_the_free_memory(self): + for first, second in ((1000, 3000), (3000, 1000)): + with self.subTest(first=first, second=second): + unused = [first, second, 0, 0] + readings = [4000, 8000] + sleeps = [] + bounded_run.wait_for_memory( + 2048, 300, 5.0, read_available=lambda: readings.pop(0), read_outstanding=lambda: unused.pop(0), + sleep=sleeps.append, + ) + self.assertEqual(sleeps, [5.0]) def test_the_headroom_is_not_given_out(self): self.assertEqual(self.wait([5000, 5200], 300, headroom=1024), [5.0]) From a02633dced4bd6f9a0f13197a93370ad62dc298b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:39:41 +0100 Subject: [PATCH 09/10] fix(skills/bounding-heavy-commands): end the wait for a scope on a real-time deadline The wait added up the sleep time that it asked for. On a machine under memory pressure a sleep can take much longer, so the memory lock, which blocks every wrapper, could stay held far past its 5 seconds. The wait now ends at a monotonic deadline. Co-Authored-By: Claude Opus 5.5 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 10 ++++++---- .../scripts/tests/test_bounded_run.py | 9 +++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index ca0dff2..d56ddea 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -612,17 +612,19 @@ def _scope_counts(path: str) -> bool: return limit.isdigit() -def wait_for_scope(parent: str, unit: str, limit_seconds: float, sleep: Callable[[float], None] = time.sleep) -> bool: +def wait_for_scope( + parent: str, unit: str, limit_seconds: float, + sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic, +) -> bool: """Returns True when the scope of the unit is in parent with its memory limit, as unused_budget_mib counts it, or False when it is not there after limit_seconds.""" path = os.path.join(parent, unit + ".scope") - waited = 0.0 + deadline = clock() + limit_seconds # systemd makes the directory of the scope before it writes the limit. while not _scope_counts(path): - if waited >= limit_seconds: + if clock() >= deadline: return False sleep(0.02) - waited += 0.02 return True diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 3c9b5d2..823f621 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -943,6 +943,15 @@ def test_no_slice_without_a_cgroup_version_2_line(self): self.assertIsNone(bounded_run.scope_parent_directory("", "/cg")) self.assertIsNone(bounded_run.scope_parent_directory("4:memory:/user.slice/unit-1-probe.scope\n", "/cg")) + def test_the_wait_for_a_scope_ends_after_its_time_limit_of_real_time(self): + now = [0.0] + + def slow_sleep(seconds): + now[0] += 10 * seconds + + self.assertFalse(bounded_run.wait_for_scope(self.slice, "bounded-run-1-000000", 1.0, sleep=slow_sleep, clock=lambda: now[0])) + self.assertLessEqual(now[0], 1.2) + def test_a_running_command_that_uses_little_of_a_large_budget_holds_back_the_next(self): self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), str(1024 * 1024 ** 2)) sleeps = [] From a373e3cae7c7e5bb358f07da3b6b272a73c706a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Wed, 30 Sep 2026 02:50:00 +0100 Subject: [PATCH 10/10] fix(skills/bounding-heavy-commands): space the lines of the memory wait by real time BOUNDED_RUN_MEMORY_WAIT_SECONDS is now the time between two "still waiting" lines, but the wait added up the sleep time that it asked for. Under memory pressure a sleep can take much longer, so the lines came further apart and understated the time waited. The wait now reads a monotonic clock. Co-Authored-By: Claude Opus 5.5 --- .../scripts/bounded_run.py | 11 ++++++----- .../scripts/tests/test_bounded_run.py | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index d56ddea..544546e 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -474,6 +474,7 @@ def wait_for_memory( sleep: Callable[[float], None] = time.sleep, lock: Callable[[], None] = lambda: None, unlock: Callable[[], None] = lambda: None, + clock: Callable[[], float] = time.monotonic, ) -> None: """Returns when the free memory, less the unused budgets of running commands and the headroom, holds the budget. @@ -481,8 +482,8 @@ def wait_for_memory( 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. """ - waited = 0.0 - next_line = 0.0 + started = clock() + next_line: Optional[float] = None while True: lock() # A running command that grows or shrinks during the reads moves both values. The larger of the two unused @@ -499,12 +500,12 @@ def wait_for_memory( if available - (outstanding or 0) - headroom_mib >= budget_mib: log(state + "; starting") return - if waited >= next_line: - log(state + ("; waiting" if waited == 0 else "; still waiting after %ds" % waited)) + 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)) next_line = waited + interval_seconds unlock() sleep(poll_seconds) - waited += poll_seconds def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool = True) -> List[str]: 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 823f621..5b15c0f 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -757,12 +757,18 @@ def setUp(self): self.log = patcher.start() self.addCleanup(patcher.stop) - def wait(self, values, limit, outstanding=None, headroom=0): + def wait(self, values, limit, outstanding=None, headroom=0, oversleep=1): readings = list(values) sleeps = [] + now = [0.0] + + def sleep(seconds): + sleeps.append(seconds) + now[0] += seconds * oversleep + bounded_run.wait_for_memory( 4096, limit, 5.0, headroom_mib=headroom, read_available=lambda: readings.pop(0), - read_outstanding=lambda: outstanding, sleep=sleeps.append, + read_outstanding=lambda: outstanding, sleep=sleep, clock=lambda: now[0], ) return sleeps @@ -790,6 +796,12 @@ def test_the_time_limit_is_the_time_between_two_lines_of_the_wait(self): self.assertEqual(len(waiting), 4, waiting) self.assertIn("still waiting", waiting[1]) + def test_the_time_between_two_lines_is_real_time(self): + self.wait([1000] * 3 + [5000], 100, oversleep=10) + waiting = [line for line in self.lines() if "waiting" in line] + self.assertEqual(len(waiting), 2, waiting) + self.assertTrue(waiting[1].endswith("; still waiting after 100s"), waiting) + def test_starts_when_the_memory_is_not_readable(self): self.assertEqual(self.wait([None], 300), []) self.assertEqual(self.lines(), ["cannot read the free memory; starting"])