Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions skills/bounding-heavy-commands/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

```
Expand All @@ -41,11 +43,11 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru
| `--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. |
| `--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 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.

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, 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

Expand Down Expand Up @@ -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. |
209 changes: 182 additions & 27 deletions skills/bounding-heavy-commands/scripts/bounded_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@

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:

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
Expand Down Expand Up @@ -57,9 +58,11 @@
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
SCOPE_WAIT_SECONDS = 5.0
MARGIN_EXACT = 0.25
MARGIN_APPROXIMATE = 0.5
BUDGET_STEP_MIB = 256
Expand Down Expand Up @@ -187,6 +190,15 @@ def default_reserve_mib(total_mib: int) -> int:
return max(MINIMUM_RESERVE_MIB, total_mib // 4)


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:
return max(1, (total_mib - reserve_mib) // slot_mib)

Expand Down Expand Up @@ -219,6 +231,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.
Expand Down Expand Up @@ -454,25 +468,44 @@ 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:
waited = 0.0
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.

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.
"""
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
# 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 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
after = read_outstanding()
outstanding = None if before is None or after is None else max(before, after)
Comment thread
sourcehawk marked this conversation as resolved.
Resolved
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
Comment thread
sourcehawk marked this conversation as resolved.
Resolved
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]:
Expand All @@ -488,32 +521,114 @@ 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 _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, 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")
deadline = clock() + limit_seconds
# systemd makes the directory of the scope before it writes the limit.
while not _scope_counts(path):
if clock() >= deadline:
return False
sleep(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:
Expand Down Expand Up @@ -825,8 +940,22 @@ 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_available() -> Optional[int]:
return available_memory_mib() if settings.free_mib is None else settings.free_mib

def read_outstanding() -> Optional[int]:
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:
inside = [sys.executable, os.path.abspath(__file__), "--inside-cap", peak_file, unit, "--"]
Expand Down Expand Up @@ -855,13 +984,39 @@ 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:
wait_for_memory(wait_budget, settings.memory_wait_seconds, settings.poll_seconds)
code, maxrss = run_command(command, child_environ, start_tracker)
wait_for_memory(
wait_budget, settings.memory_wait_seconds, settings.poll_seconds,
headroom_mib=headroom_mib(settings.total_mib, wait_budget, most),
Comment thread
sourcehawk marked this conversation as resolved.
Resolved
read_available=read_available, read_outstanding=read_outstanding,
lock=lock_memory, unlock=unlock_memory,
)
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()
Expand Down
Loading
Loading