Skip to content

Commit e81ae76

Browse files
sourcehawkclaude
andcommitted
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 <noreply@anthropic.com>
1 parent 0b9b5e8 commit e81ae76

3 files changed

Lines changed: 319 additions & 72 deletions

File tree

‎skills/bounding-heavy-commands/SKILL.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru
4141
| `--exclusive <name>` | A resource that only one command may hold at a time, such as a fixed port. You choose the name. The wrapper keeps the names of each repository apart, and all worktrees of one repository share them. Repeat the option for each resource. |
4242
| `--measure` | Also print a suggested budget. Discovery uses it. With no `--memory`, the command runs alone in the queue. |
4343

44-
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).
44+
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).
4545

4646
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.
4747

48-
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.
48+
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.
4949

5050
## The record
5151

‎skills/bounding-heavy-commands/scripts/bounded_run.py‎

Lines changed: 106 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
2121
BOUNDED_RUN_SLOT_MIB size of one memory slot (default 2048)
2222
BOUNDED_RUN_RESERVE_MIB memory that the queue never gives out
23-
BOUNDED_RUN_MEMORY_WAIT_SECONDS time limit of the wait for free memory (default 300)
23+
BOUNDED_RUN_MEMORY_WAIT_SECONDS time between two lines of the wait for free memory (default 300)
2424
2525
Values for the tests of this script, and for its maintainers:
2626
@@ -57,6 +57,7 @@
5757
ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE"
5858
SLOT_MIB = 2048
5959
MINIMUM_RESERVE_MIB = 2048
60+
MINIMUM_HEADROOM_MIB = 1024
6061
POLL_SECONDS = 2.0
6162
MEMORY_WAIT_SECONDS = 300.0
6263
SAMPLE_SECONDS = 1.0
@@ -187,6 +188,11 @@ def default_reserve_mib(total_mib: int) -> int:
187188
return max(MINIMUM_RESERVE_MIB, total_mib // 4)
188189

189190

191+
def headroom_mib(total_mib: int) -> int:
192+
"""Returns the memory that the wait for free memory keeps free for the programs outside the queue."""
193+
return max(MINIMUM_HEADROOM_MIB, total_mib // 10)
194+
195+
190196
def slot_count(total_mib: int, slot_mib: int, reserve_mib: int) -> int:
191197
return max(1, (total_mib - reserve_mib) // slot_mib)
192198

@@ -454,23 +460,32 @@ def available_memory_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/c
454460

455461

456462
def wait_for_memory(
457-
budget_mib: int, limit_seconds: float, poll_seconds: float,
463+
budget_mib: int, interval_seconds: float, poll_seconds: float, headroom_mib: int = 0,
458464
read_available: Callable[[], Optional[int]] = available_memory_mib,
465+
read_outstanding: Callable[[], Optional[int]] = lambda: None,
459466
sleep: Callable[[float], None] = time.sleep,
460-
) -> bool:
467+
) -> None:
468+
"""Returns when the free memory, less the unused budgets of running commands and the headroom, holds the budget.
469+
470+
There is no time limit, so the call can block for as long as the machine is full. Returns at once when
471+
the free memory cannot be read. read_outstanding gives None where the unused budgets cannot be counted.
472+
"""
461473
waited = 0.0
474+
next_line = 0.0
462475
while True:
463476
available = read_available()
464477
if available is None:
465478
log("cannot read the free memory; starting")
466-
return True
467-
if available >= budget_mib:
468-
log("%d MiB free, budget %d MiB; starting" % (available, budget_mib))
469-
return True
470-
if waited >= limit_seconds:
471-
log("WARNING: only %d MiB free after %ds, budget %d MiB; starting" % (available, waited, budget_mib))
472-
return False
473-
log("%d MiB free, budget %d MiB; waiting (%d of %ds)" % (available, budget_mib, waited, limit_seconds))
479+
return
480+
outstanding = read_outstanding()
481+
counted = "unused running budgets not counted here" if outstanding is None else "%d MiB of running budgets unused" % outstanding
482+
state = "%d MiB free, %s, %d MiB headroom, budget %d MiB" % (available, counted, headroom_mib, budget_mib)
483+
if available - (outstanding or 0) - headroom_mib >= budget_mib:
484+
log(state + "; starting")
485+
return
486+
if waited >= next_line:
487+
log(state + ("; waiting" if waited == 0 else "; still waiting after %ds" % waited))
488+
next_line = waited + interval_seconds
474489
sleep(poll_seconds)
475490
waited += poll_seconds
476491

@@ -488,32 +503,87 @@ def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool
488503
return prefix + ["--"]
489504

490505

491-
def cap_usable(
506+
def probe_cap(
492507
prefix: Sequence[str], platform: str = sys.platform,
493508
which: Callable[[str], Optional[str]] = shutil.which,
494509
run: Callable[..., "subprocess.CompletedProcess"] = subprocess.run,
495-
) -> bool:
510+
) -> Optional[str]:
511+
"""Runs a short command under the prefix. Returns None when the prefix does not work here, else the
512+
text of /proc/self/cgroup inside the probe scope, which can be empty."""
496513
if not platform.startswith("linux") or which("systemd-run") is None:
497-
return False
514+
return None
498515
try:
499-
done = run(list(prefix) + ["true"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
516+
done = run(list(prefix) + ["cat", "/proc/self/cgroup"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=15)
500517
except (OSError, subprocess.TimeoutExpired):
501-
return False
502-
return done.returncode == 0
518+
return None
519+
if done.returncode != 0:
520+
return None
521+
return done.stdout or ""
503522

504523

505524
def choose_cap_prefix(
506525
budget_mib: int, cpus: Optional[int], unit: str,
507-
usable: Callable[[Sequence[str]], bool],
508-
) -> Optional[List[str]]:
509-
"""Returns the prefix of the hard cap for the unit, or None when no cap is usable here."""
526+
probe: Callable[[Sequence[str]], Optional[str]],
527+
) -> Optional[Tuple[List[str], str]]:
528+
"""Returns the prefix of the hard cap for the unit and the output of its probe, or None when no cap is usable here."""
510529
# A scope unit accepts OOMPolicy= from systemd 253; an older systemd rejects the whole prefix.
511530
for oom_policy in (True, False):
512-
if usable(cap_prefix(budget_mib, cpus, unit + "-probe", oom_policy)):
513-
return cap_prefix(budget_mib, cpus, unit, oom_policy)
531+
found = probe(cap_prefix(budget_mib, cpus, unit + "-probe", oom_policy))
532+
if found is not None:
533+
return cap_prefix(budget_mib, cpus, unit, oom_policy), found
514534
return None
515535

516536

537+
def _unified_path(cgroup_text: str) -> Optional[str]:
538+
for line in cgroup_text.splitlines():
539+
if line.startswith("0::"):
540+
return line.strip()[3:]
541+
return None
542+
543+
544+
def scope_parent_directory(probe_output: str, cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]:
545+
"""Returns the directory that holds the scope of the probe, or None without a cgroup version 2 line."""
546+
path = _unified_path(probe_output)
547+
return None if path is None else os.path.dirname(cgroup_root + path)
548+
549+
550+
def own_scope_name(proc_root: str = "/proc") -> Optional[str]:
551+
"""Returns the name of the cgroup of this process, or None when it cannot be read."""
552+
try:
553+
with open(os.path.join(proc_root, "self", "cgroup")) as handle:
554+
path = _unified_path(handle.read())
555+
except OSError:
556+
return None
557+
return None if path is None else os.path.basename(path)
558+
559+
560+
def unused_budget_mib(parent: str, skip: Sequence[str]) -> int:
561+
"""Returns the part of their budgets that the bounded commands whose scopes are in parent do not use yet.
562+
563+
Probe scopes, the scopes named in skip, and scopes with no memory limit add nothing.
564+
"""
565+
try:
566+
names = os.listdir(parent)
567+
except OSError:
568+
return 0
569+
unused = 0
570+
for name in names:
571+
if not name.startswith(PREFIX + "-") or not name.endswith(".scope") or name.endswith("-probe.scope") or name in skip:
572+
continue
573+
try:
574+
with open(os.path.join(parent, name, "memory.max")) as handle:
575+
limit = handle.read().strip()
576+
with open(os.path.join(parent, name, "memory.current")) as handle:
577+
current = int(handle.read().strip())
578+
if limit == "max":
579+
continue
580+
unused += max(0, int(limit) - current)
581+
except (OSError, ValueError):
582+
# A scope ends between the listing and the read.
583+
continue
584+
return unused // (1024 * 1024)
585+
586+
517587
def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]:
518588
try:
519589
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:
825895
exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive]
826896

827897
unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6))
828-
prefix = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, cap_usable)
898+
choice = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, probe_cap)
899+
prefix = choice[0] if choice is not None else None
829900
capped = prefix is not None
901+
# Every scope of the user that systemd-run makes with no slice option goes to the slice of the probe.
902+
scopes = scope_parent_directory(choice[1]) if choice is not None else None
903+
# A wrapper that runs inside a bounded scope does its work in the budget of that scope.
904+
skip = [name for name in (unit + ".scope", own_scope_name()) if name is not None]
905+
906+
def read_outstanding() -> Optional[int]:
907+
return None if scopes is None else unused_budget_mib(scopes, skip)
908+
830909
peak_file = os.path.join(directory, "peak-%s" % unit)
831910
if prefix is not None:
832911
inside = [sys.executable, os.path.abspath(__file__), "--inside-cap", peak_file, unit, "--"]
@@ -858,7 +937,10 @@ def read_sample() -> Optional[int]:
858937
reported: Optional[int] = None
859938
reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds)
860939
try:
861-
wait_for_memory(wait_budget, settings.memory_wait_seconds, settings.poll_seconds)
940+
wait_for_memory(
941+
wait_budget, settings.memory_wait_seconds, settings.poll_seconds,
942+
headroom_mib=headroom_mib(settings.total_mib), read_outstanding=read_outstanding,
943+
)
862944
code, maxrss = run_command(command, child_environ, start_tracker)
863945
tracked = trackers[0].finish() if trackers else None
864946
finally:

0 commit comments

Comments
 (0)