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
12 changes: 6 additions & 6 deletions skills/bounding-heavy-commands/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru
| Option | Meaning |
| --- | --- |
| `--memory <budget>` | Memory the command may use, such as `6G` or `4096M`. Taken from the record. Without it the wrapper uses its default budget, a quarter of the machine's memory. A measurement without it takes the whole queue where there is no hard cap. |
| `--cpus <n>` | Processor limit, as a whole number. Taken from the record. |
| `--cpus <n>` | Processor limit, as a whole number. Taken from the record. Without it the wrapper uses half the machine's processors, rounded down, and at least 1. |
| `--exclusive <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 with the default budget where the hard cap is available, and alone in the queue where it is not. |
| `--measure-rows <n>,<n>,...` | Measure the command one time at each `--cpus` of the list, one after the other, the largest first. The largest runs with the `--memory` of the call. With no `--memory`, it runs with the default budget where the hard cap is available, and alone in the queue where it is not. Each smaller one runs with `--memory` at the suggested budget of the one before it. When the one before it did not exit 0, the smaller one runs with the same `--memory` as that one. Use it in place of `--cpus` and `--measure`. A stop signal ends the list. A stop signal to the wrapper then ends the wrapper by that signal. So a Ctrl-C, which reaches the shell too, stops a line of joined calls; a signal sent to the wrapper alone does not stop the shell's line. Otherwise the exit code is the first exit code of a row that is not 0. |
Expand All @@ -59,12 +59,12 @@ bounded-run: row label=<name> cpus=<n> budget=<n>M peak=<n>M held=<n>M|- exact=<
A check prints its lines in a fixed form too:

```
bounded-run: check slots=<n> slot=<n>M free-slots=<n> free=<n>M unused=<n>M line=<free|busy>
bounded-run: check held unit=<name> budget=<n>M used=<n>M age=<n>s dir=<directory> command=<command>
bounded-run: check slots=<n> slot=<n>M free-slots=<n> free=<n>M unused=<n>M cpus=<n> cpus-used=<n> line=<free|busy>
bounded-run: check held unit=<name> budget=<n>M used=<n>M cpus=<n> age=<n>s dir=<directory> command=<command>
bounded-run: check budget=<n>M slots=<n> headroom=<n>M starts=<yes|no>
```

The first line gives the slots of the queue and their size, the slots that are free now, the free memory, and the unused budgets of the running commands. `line=busy` means that a command waits in the line. Each `held` line is one bounded command that runs now: its budget, the memory it uses, how long it has run, its working directory, and its command. The held lines need the hard cap, so without it there are none. Each `budget` line is one `--memory`, in the order given: the slots that it needs, the headroom that the wait keeps free beside that budget, and `starts=yes` when a command of that budget would start now. A `-` means that the check cannot read or count the value at that moment.
The first line gives the slots of the queue and their size, the slots that are free now, the free memory, the unused budgets of the running commands, the processors of the machine, and the processors that the running bounded commands can use together (`cpus-used`). `line=busy` means that a command waits in the line. Each `held` line is one bounded command that runs now: its budget, the memory it uses, the processors it can use, how long it has run, its working directory, and its command. The held lines and `cpus-used` need the hard cap, so without it there are no held lines and `cpus-used` is `-`. Each `budget` line is one `--memory`, in the order given: the slots that it needs, the headroom that the wait keeps free beside that budget, and `starts=yes` when a command of that budget would start now. A `-` means that the check cannot read or count the value at that moment.

The exit code of the wrapper is the command's exit code. Exit code 125, with a `bounded-run:` line that names a fault and with no line for the budget and the peak, means that the wrapper itself failed (see §When the wrapper cannot run).

Expand Down Expand Up @@ -93,7 +93,7 @@ A budget is valid only at the `--cpus` of its row. The same command at more proc

The table has one row for each `--cpus`. A measurement at a `--cpus` that has no row adds a row. A measurement at a `--cpus` that has a row replaces that row. Never delete a row because a different `--cpus` was measured. Two entries whose command lines differ only in the values of the wrapper's `--memory` and `--cpus`, before the `--`, are one entry: keep one, with the rows of both, and where both have a row at the same `--cpus`, keep the newer one. The row at the `--cpus` of the default row of the entry that you keep stays the default row, and no other row is marked as the default. Then write the `--cpus` and the budget of the default row into the command line. One row is the default row. A run uses it when nothing asks for a different one.

Before a run of a command whose entry has more than one row, choose the row with the check. Run the wrapper with `--check` and one `--memory` for the budget of each row. Choose the largest row that would start now (`starts=yes`). When no row would start now, choose the default row and let it wait in the queue: the smallest row runs slowest, and the line keeps the wait fair. Then run the chosen row through the wrapper, with the `--cpus` and the `--memory` of that row. An entry with one row needs no check.
Before a run of a command whose entry has more than one row, choose the row with the check. Run the wrapper with `--check` and one `--memory` for the budget of each row. Choose the largest row that would start now (`starts=yes`). A row whose `--cpus`, added to `cpus-used`, is more than `cpus` makes every running command slower, so when two rows would both start, prefer the largest one that fits in `cpus`. When no row would start now, choose the default row and let it wait in the queue: the smallest row runs slowest, and the line keeps the wait fair. Then run the chosen row through the wrapper, with the `--cpus` and the `--memory` of that row. An entry with one row needs no check.
Comment thread
sourcehawk marked this conversation as resolved.
Resolved

The check is a snapshot, not a reservation. Two sessions can see the same free slots at the same moment, so the chosen row still goes through the queue. A check never replaces the wrapper.

Expand Down Expand Up @@ -185,7 +185,7 @@ A subagent does not see your project memory. It knows the bounded commands only
On a machine on which the wrapper can run, every dispatch prompt for a subagent that will run a heavy command MUST include:

1. The bounded command line for each heavy command, copied from the record, with the `--cpus` and the budget of its default row. When its entry has more than one row, also the `--cpus` and the budget of each row, and its check line with one `--memory` for each row.
2. This rule, in these words: "Run the bounded commands as written. You can make three changes: the `--cpus` and the `--memory` of a row that this prompt gives for the command, a narrower argument at the end of the line, such as one test file, and one more `--exclusive <name>` option after a collision on a port or a lock, which you name in your report. When this prompt gives a command more than one row, run its check line before each run, and use the largest row with `starts=yes`, or the default row when no row has it. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited. After a long wait, run the same wrapper with `--check`, and name in your report each command of its `held` lines, with its directory and its age."
2. This rule, in these words: "Run the bounded commands as written. You can make three changes: the `--cpus` and the `--memory` of a row that this prompt gives for the command, a narrower argument at the end of the line, such as one test file, and one more `--exclusive <name>` option after a collision on a port or a lock, which you name in your report. When this prompt gives a command more than one row, run its check line before each run, and use the largest row with `starts=yes` whose `--cpus`, added to `cpus-used`, fits in `cpus`. When no such row fits, use the largest row with `starts=yes`, and when no row has it, use the default row. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited. After a long wait, run the same wrapper with `--check`, and name in your report each command of its `held` lines, with its directory and its age."
3. Each command that an instruction exempts from the wrapper, in its plain form, in a list of its own, with the instruction that exempts it. The rule of item 2 does not apply to that list. An instruction of the user that covers one run goes to the one subagent that does that run, and to no other.

Do not dispatch fewer subagents to protect the machine. The queue protects it. Subagents that wait in the queue cost time, not memory. On a machine on which the wrapper cannot run, the next section says how to dispatch.
Expand Down
81 changes: 70 additions & 11 deletions skills/bounding-heavy-commands/scripts/bounded_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
not stop the shell. A caller that reads the exit status reads 128 plus the
signal.

A run without --cpus gets half of the processors of the machine, rounded
down and at least 1. The command reads its processors in BOUNDED_RUN_CPUS,
and the hard cap, where it is available, holds the command to them.

A measurement prints one row line on the error stream, in a fixed form:

bounded-run: row label=NAME cpus=N budget=<n>M peak=<n>M held=<n>M|- exact=yes|no exit=CODE
Expand All @@ -32,12 +36,15 @@
running bounded command where the hard cap is available, and one line for
each --memory, in the order given:

bounded-run: check slots=N slot=<n>M free-slots=N|- free=<n>M|- unused=<n>M|- line=free|busy
bounded-run: check held unit=NAME budget=<n>M|- used=<n>M|- age=Ns|- dir=PATH|- command=TEXT|-
bounded-run: check slots=N slot=<n>M free-slots=N|- free=<n>M|- unused=<n>M|- cpus=N cpus-used=N|- line=free|busy
bounded-run: check held unit=NAME budget=<n>M|- used=<n>M|- cpus=N|- age=Ns|- dir=PATH|- command=TEXT|-
bounded-run: check budget=<n>M slots=N headroom=<n>M starts=yes|no

A '-' stands for a value that the check cannot read or count here. starts=yes
means that a run of that budget would start now. It is not a reservation.
A '-' stands for a value that the check cannot read or count here. cpus is
the processors of the machine. cpus-used is the sum of the processors that
the running bounded commands may use, and the cpus of a held line is the
part of one command. starts=yes means that a run of that budget would start
now. It is not a reservation.

A normal call sets none of the environment variables below. A person can
set the tuning values in the profile of the shell, so that every session
Expand Down Expand Up @@ -659,6 +666,15 @@ def wait_for_memory(
sleep(poll_seconds)


def machine_cpus() -> int:
return os.cpu_count() or 1


def default_cpus(machine: int) -> int:
"""Returns the processors of a run that gives no --cpus: half of the machine's, rounded down, and at least 1."""
return max(1, machine // 2)


def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool = True) -> List[str]:
prefix = [
"systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", unit,
Expand Down Expand Up @@ -759,6 +775,40 @@ def unused_budget_mib(parent: str, skip: Sequence[str]) -> int:
return unused // (1024 * 1024)


def _scope_cpus(directory: str, machine: int) -> Optional[int]:
"""Returns the processors that the quota of the scope in directory allows, rounded up, or None when it cannot be read.

A scope with no quota can use each processor of the machine.
"""
try:
quota, period = (_read_text(os.path.join(directory, "cpu.max")) or "").split()
if quota == "max":
return machine
return -(-int(quota) // int(period)) if int(period) > 0 else None
except ValueError:
return None


def cpus_in_use(parent: str, skip: Sequence[str], machine: Optional[int] = None) -> Optional[int]:
"""Returns the sum of the processors that the quotas of the bounded commands whose scopes are in parent allow.

Probe scopes and the scopes named in skip add nothing. Returns None when the quota of a running scope cannot be read.
"""
if machine is None:
machine = machine_cpus()
used = 0
for name in _bounded_scopes(parent, skip):
directory = os.path.join(parent, name)
cpus = _scope_cpus(directory, machine)
if not os.path.isdir(directory):
# The scope ended while it was read.
continue
if cpus is None:
return None
used += cpus
return used


def _scope_counts(path: str) -> bool:
try:
with open(os.path.join(path, "memory.max")) as handle:
Expand Down Expand Up @@ -823,13 +873,17 @@ def _held_command(pid: int, proc_root: str) -> Optional[str]:
return _one_line(" ".join(arguments))[:HELD_COMMAND_CHARACTERS]


def held_commands(parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None) -> List[str]:
def held_commands(
parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None, machine: Optional[int] = None,
) -> List[str]:
"""Returns one text for each running bounded command whose scope is in parent, as the fields of a check line.

A field that cannot be read is '-'. Probe scopes and the scopes named in skip give no text.
"""
if ticks is None:
ticks = os.sysconf("SC_CLK_TCK")
if machine is None:
machine = machine_cpus()

def mib(text: Optional[str]) -> str:
return "%dM" % (int(text) // (1024 * 1024)) if text is not None and text.strip().isdigit() else "-"
Expand All @@ -839,6 +893,7 @@ def mib(text: Optional[str]) -> str:
directory = os.path.join(parent, name)
limit = _read_text(os.path.join(directory, "memory.max"))
current = _read_text(os.path.join(directory, "memory.current"))
cpus = _scope_cpus(directory, machine)
pids = [int(line) for line in (_read_text(os.path.join(directory, "cgroup.procs")) or "").split() if line.isdigit()]
if not os.path.isdir(directory):
# The scope ended while it was read.
Expand All @@ -853,8 +908,8 @@ def mib(text: Optional[str]) -> str:
if working is not None:
working = _one_line(working)
command = _held_command(pid, proc_root) if pid is not None else None
held.append("unit=%s budget=%s used=%s age=%s dir=%s command=%s" % (
name[:-len(".scope")], mib(limit), mib(current), "-" if age is None else "%ds" % age,
held.append("unit=%s budget=%s used=%s cpus=%s age=%s dir=%s command=%s" % (
name[:-len(".scope")], mib(limit), mib(current), "-" if cpus is None else cpus, "-" if age is None else "%ds" % age,
working or "-", command or "-"))
return held

Expand Down Expand Up @@ -1326,7 +1381,8 @@ def bounded_once(options: Options, environ: Mapping[str, str]) -> Tuple[int, int
exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive]

unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6))
choice = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, probe_cap)
cpus = options.cpus if options.cpus is not None else default_cpus(machine_cpus())
choice = None if settings.no_cap else choose_cap_prefix(budget, cpus, unit, probe_cap)
prefix = choice[0] if choice is not None else None
capped = prefix is not None
if options.measure and options.memory is None and not capped:
Expand Down Expand Up @@ -1355,7 +1411,7 @@ def read_outstanding() -> Optional[int]:
child_environ: Dict[str, str] = dict(environ)
child_environ[ACTIVE_VARIABLE] = "1"
child_environ["BOUNDED_RUN_MEMORY_MIB"] = str(budget)
child_environ["BOUNDED_RUN_CPUS"] = str(options.cpus if options.cpus is not None else (os.cpu_count() or 1))
child_environ["BOUNDED_RUN_CPUS"] = str(cpus)

trackers: List[PeakTracker] = []

Expand Down Expand Up @@ -1469,12 +1525,15 @@ def read_outstanding() -> Optional[int]:
else:
available, outstanding = settings.free_mib, None

machine = machine_cpus()
used = None if scopes is None else cpus_in_use(scopes, ())

def mib(value: Optional[int]) -> str:
return "-" if value is None else "%dM" % value

log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s line=%s" % (
log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s cpus=%d cpus-used=%s line=%s" % (
count, settings.slot_mib, "-" if free_slots is None else free_slots, mib(available), mib(outstanding),
"free" if line is not None else "busy"))
machine, "-" if used is None else used, "free" if line is not None else "busy"))
for held in held_commands(scopes, ()) if scopes is not None else []:
log("check held " + held)
for budget in budgets:
Expand Down
Loading
Loading