Skip to content

Commit 34a988f

Browse files
sourcehawkclaude
andcommitted
feat(skills/bounding-heavy-commands): give a run without --cpus a quota and show processors in the check
A bounded command without --cpus ran with no CPU quota and with BOUNDED_RUN_CPUS at every processor of the machine, so the commands of the queue together could ask for more processors than the machine has, and nothing showed how many were taken. A run without --cpus now gets half the machine's processors, rounded down and at least 1: in BOUNDED_RUN_CPUS, and as its CPUQuota where the hard cap is available. This matches the --cpus of a command's first measurement. --measure-rows gives each row its own --cpus, so it is unchanged. --check now prints cpus=<machine processors> and cpus-used=<sum of the quotas of the running bounded scopes, from cpu.max> on its state line, and cpus=<n> on each held line, so that an agent can choose a row that fits the free processors. The skill says to prefer such a row when two rows would start. The admission of a command by processors stays open. Towards #72 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1955b7c commit 34a988f

3 files changed

Lines changed: 222 additions & 26 deletions

File tree

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru
4141
| Option | Meaning |
4242
| --- | --- |
4343
| `--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. |
44-
| `--cpus <n>` | Processor limit, as a whole number. Taken from the record. |
44+
| `--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. |
4545
| `--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. |
4646
| `--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. |
4747
| `--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. |
@@ -59,12 +59,12 @@ bounded-run: row label=<name> cpus=<n> budget=<n>M peak=<n>M held=<n>M|- exact=<
5959
A check prints its lines in a fixed form too:
6060

6161
```
62-
bounded-run: check slots=<n> slot=<n>M free-slots=<n> free=<n>M unused=<n>M line=<free|busy>
63-
bounded-run: check held unit=<name> budget=<n>M used=<n>M age=<n>s dir=<directory> command=<command>
62+
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>
63+
bounded-run: check held unit=<name> budget=<n>M used=<n>M cpus=<n> age=<n>s dir=<directory> command=<command>
6464
bounded-run: check budget=<n>M slots=<n> headroom=<n>M starts=<yes|no>
6565
```
6666

67-
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.
67+
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.
6868

6969
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).
7070

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

9494
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.
9595

96-
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.
96+
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.
9797

9898
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.
9999

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

Lines changed: 70 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@
1313
not stop the shell. A caller that reads the exit status reads 128 plus the
1414
signal.
1515
16+
A run without --cpus gets half of the processors of the machine, rounded
17+
down and at least 1. The command reads its processors in BOUNDED_RUN_CPUS,
18+
and the hard cap, where it is available, holds the command to them.
19+
1620
A measurement prints one row line on the error stream, in a fixed form:
1721
1822
bounded-run: row label=NAME cpus=N budget=<n>M peak=<n>M held=<n>M|- exact=yes|no exit=CODE
@@ -32,12 +36,15 @@
3236
running bounded command where the hard cap is available, and one line for
3337
each --memory, in the order given:
3438
35-
bounded-run: check slots=N slot=<n>M free-slots=N|- free=<n>M|- unused=<n>M|- line=free|busy
36-
bounded-run: check held unit=NAME budget=<n>M|- used=<n>M|- age=Ns|- dir=PATH|- command=TEXT|-
39+
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
40+
bounded-run: check held unit=NAME budget=<n>M|- used=<n>M|- cpus=N|- age=Ns|- dir=PATH|- command=TEXT|-
3741
bounded-run: check budget=<n>M slots=N headroom=<n>M starts=yes|no
3842
39-
A '-' stands for a value that the check cannot read or count here. starts=yes
40-
means that a run of that budget would start now. It is not a reservation.
43+
A '-' stands for a value that the check cannot read or count here. cpus is
44+
the processors of the machine. cpus-used is the sum of the processors that
45+
the running bounded commands may use, and the cpus of a held line is the
46+
part of one command. starts=yes means that a run of that budget would start
47+
now. It is not a reservation.
4148
4249
A normal call sets none of the environment variables below. A person can
4350
set the tuning values in the profile of the shell, so that every session
@@ -659,6 +666,15 @@ def wait_for_memory(
659666
sleep(poll_seconds)
660667

661668

669+
def machine_cpus() -> int:
670+
return os.cpu_count() or 1
671+
672+
673+
def default_cpus(machine: int) -> int:
674+
"""Returns the processors of a run that gives no --cpus: half of the machine's, rounded down, and at least 1."""
675+
return max(1, machine // 2)
676+
677+
662678
def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool = True) -> List[str]:
663679
prefix = [
664680
"systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", unit,
@@ -759,6 +775,40 @@ def unused_budget_mib(parent: str, skip: Sequence[str]) -> int:
759775
return unused // (1024 * 1024)
760776

761777

778+
def _scope_cpus(directory: str, machine: int) -> Optional[int]:
779+
"""Returns the processors that the quota of the scope in directory allows, rounded up, or None when it cannot be read.
780+
781+
A scope with no quota can use each processor of the machine.
782+
"""
783+
try:
784+
quota, period = (_read_text(os.path.join(directory, "cpu.max")) or "").split()
785+
if quota == "max":
786+
return machine
787+
return -(-int(quota) // int(period)) if int(period) > 0 else None
788+
except ValueError:
789+
return None
790+
791+
792+
def cpus_in_use(parent: str, skip: Sequence[str], machine: Optional[int] = None) -> Optional[int]:
793+
"""Returns the sum of the processors that the quotas of the bounded commands whose scopes are in parent allow.
794+
795+
Probe scopes and the scopes named in skip add nothing. Returns None when the quota of a running scope cannot be read.
796+
"""
797+
if machine is None:
798+
machine = machine_cpus()
799+
used = 0
800+
for name in _bounded_scopes(parent, skip):
801+
directory = os.path.join(parent, name)
802+
cpus = _scope_cpus(directory, machine)
803+
if not os.path.isdir(directory):
804+
# The scope ended while it was read.
805+
continue
806+
if cpus is None:
807+
return None
808+
used += cpus
809+
return used
810+
811+
762812
def _scope_counts(path: str) -> bool:
763813
try:
764814
with open(os.path.join(path, "memory.max")) as handle:
@@ -823,13 +873,17 @@ def _held_command(pid: int, proc_root: str) -> Optional[str]:
823873
return _one_line(" ".join(arguments))[:HELD_COMMAND_CHARACTERS]
824874

825875

826-
def held_commands(parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None) -> List[str]:
876+
def held_commands(
877+
parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None, machine: Optional[int] = None,
878+
) -> List[str]:
827879
"""Returns one text for each running bounded command whose scope is in parent, as the fields of a check line.
828880
829881
A field that cannot be read is '-'. Probe scopes and the scopes named in skip give no text.
830882
"""
831883
if ticks is None:
832884
ticks = os.sysconf("SC_CLK_TCK")
885+
if machine is None:
886+
machine = machine_cpus()
833887

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

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

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

13601416
trackers: List[PeakTracker] = []
13611417

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

1528+
machine = machine_cpus()
1529+
used = None if scopes is None else cpus_in_use(scopes, ())
1530+
14721531
def mib(value: Optional[int]) -> str:
14731532
return "-" if value is None else "%dM" % value
14741533

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

0 commit comments

Comments
 (0)