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
10 changes: 5 additions & 5 deletions skills/bounding-heavy-commands/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru
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:`. A measurement also prints one row line, in a fixed form:

```
bounded-run: row label=<name> cpus=<n> budget=<n>M peak=<n>M exact=<yes|no> exit=<code>
bounded-run: row label=<name> cpus=<n> budget=<n>M peak=<n>M held=<n>M|- exact=<yes|no> exit=<code>
```

`budget` is the suggested budget. `exact=no` means that the peak was sampled, so the margin is larger. A `-` in place of the label or the `--cpus` means that the call did not give the option. The wrapper cannot know if the command did its full work: the exit code and the output of the command tell you (§Discovery, step 5).
`budget` is the suggested budget. `peak` is the peak of all memory of the command, with the file cache that the kernel can take back from it. `held` is the peak of the memory that the kernel cannot take back at once. It needs the hard cap: without it, the row line shows `held=-`. With `held`, the suggested budget is `held` plus a margin, but at least a quarter of `peak` plus a margin, so that the files the command reads stay in the cache. It is never more than `peak` plus a margin. Without `held`, it is `peak` plus a margin. `exact=no` means that the peak was sampled, so the margin is larger. `held` is always sampled. A `-` in place of the label or the `--cpus` means that the call did not give the option. The wrapper cannot know if the command did its full work: the exit code and the output of the command tell you (§Discovery, step 5).
Comment thread
sourcehawk marked this conversation as resolved.
Resolved

A check prints its lines in a fixed form too:

Expand Down Expand Up @@ -107,7 +107,7 @@ Then, before each heavy command, use the first case that applies:
4. **Your harness has no project memory, or it is off.** You cannot save a record, so do not try. Run the discovery in this session, keep the result in your context, and use the wrapper's default budget for anything you could not measure.
5. **Project memory is on, and the record does not exist.** Run the discovery for every heavy command of the project, not only for the command that you are about to run, and measure them all with one command line that the user runs (§Measure the whole project). While you wait for the answer of the user and for the line, run a heavy command that you need through the wrapper, as its bounded command line at `--cpus` of half the machine's processors, with no `--memory` option.

A budget is a measurement, not a preference. Change a row only when the wrapper's output at the `--cpus` of that row shows that the peak moved, and write the new peak and date in it.
A budget is a measurement, not a preference. Change a row only when the wrapper's output at the `--cpus` of that row shows that the suggested budget moved, and write the new budget, peak, and date in it. Under the hard cap the budget follows `held`, so it can move while `peak` stays the same.

To make a run start sooner, use a row at a smaller `--cpus`. That command runs fewer things at once, so its peak and its budget are smaller. It gets a slot sooner only when its budget needs fewer slots of the queue than the budget of the default row. It is a different measured command, not a lower budget for the same command. This works only for a command whose `self-bound` reads `BOUNDED_RUN_CPUS`. For any other command, a smaller `--cpus` does not make the command run fewer things at once: keep the run in the queue, and measure no smaller row. When the entry has no row at a smaller `--cpus`, the current run cannot start sooner: keep it in the queue. Then measure the command with `--measure`, with `--cpus` at half the smallest `--cpus` of the table, rounded down, and with `--memory` at the budget of the smallest row, in place of the two values of the command line, and add the row, so that the next run can use it. A command that runs fewer things at once seldom needs more than that budget, and with `--memory` the measurement does not take the whole queue. When the hard cap stops it, measure it again with two times that budget, as step 5 of §Discovery says. At `--cpus 1` no smaller command exists. Keep the default row as it is, unless the user wants the smaller `--cpus` for each run.

Expand All @@ -131,7 +131,7 @@ A part of a recorded command (one test file, one target) uses the bounded comman
python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure --cpus <n> -- <bounded command>
```

5. Record the suggested budget that the wrapper prints, with the peak and the date, as the row at the `--cpus` of the measurement. Record it only from a run in which the command did its full work. The suggested budget is the peak plus a margin, and the margin is larger where the measurement is approximate. A run that stopped early gives a peak that is too small: a suite that stops at its first failure, a command that failed at its start, a run that a signal or the hard cap stopped. Do not record the budget of such a run, and save no record for the command yet. Run the command with `--measure` again each time that you run it, until one run does its full work. A measurement with no `--memory` does not know the peak of the command. Where the hard cap is available, it runs with the default budget, and the cap stops it when it needs more. Where there is no hard cap, it takes the whole queue: it waits until no other bounded command runs, and no other starts while it runs. While it is at the head of the line, the commands behind it wait too (§Rules for the wait). When it waits for the whole queue, tell the user that a first measurement waits for the other bounded commands to end. If the hard cap stopped a measurement, measure again with `--memory` at two times the budget that the wrapper printed. For a measurement with no `--memory`, that is the default budget. The wrapper lowers a budget that is larger than the queue to the whole queue. If the cap stopped a measurement at the whole queue, the command needs more memory than the queue has: tell the user, with the budget that the wrapper printed.
5. Record the suggested budget that the wrapper prints, with the peak and the date, as the row at the `--cpus` of the measurement. Record it only from a run in which the command did its full work. The suggested budget is the peak plus a margin, and the margin is larger where the measurement is approximate. Under the hard cap, the peak that counts is the memory that the kernel cannot take back at once, with a floor for the file cache (§The wrapper). A run that stopped early gives a peak that is too small: a suite that stops at its first failure, a command that failed at its start, a run that a signal or the hard cap stopped. Do not record the budget of such a run, and save no record for the command yet. Run the command with `--measure` again each time that you run it, until one run does its full work. A measurement with no `--memory` does not know the peak of the command. Where the hard cap is available, it runs with the default budget, and the cap stops it when it needs more. Where there is no hard cap, it takes the whole queue: it waits until no other bounded command runs, and no other starts while it runs. While it is at the head of the line, the commands behind it wait too (§Rules for the wait). When it waits for the whole queue, tell the user that a first measurement waits for the other bounded commands to end. If the hard cap stopped a measurement, measure again with `--memory` at two times the budget of the cap: the budget in the line `budget <n> MiB, peak ...` that the wrapper printed, not the suggested budget. For a measurement with no `--memory`, that is the default budget. The wrapper lowers a budget that is larger than the queue to the whole queue. If the cap stopped a measurement at the whole queue, the command needs more memory than the queue has: tell the user, with the budget that the wrapper printed.
Comment thread
sourcehawk marked this conversation as resolved.
Resolved
6. Save the record.

The measured run is a real run of the command. Its result counts, also when the run stopped early, so do not run the command a second time to get the result.
Expand Down Expand Up @@ -212,7 +212,7 @@ When Python is missing or too old, and when the fault is a fault of the machine,
| "I'll run just those few tests now, that fits in the free memory" | A part of a heavy command goes through the wrapper too. "It fits" is your estimate; the queue is the count. |
| "I'll run the plain command once to check quickly" | One command outside the queue is all a freeze needs. |
| "Running both in parallel is what makes the deadline possible" | Through the wrapper a parallel start is safe, but the queue decides if the two run together. Do not promise a time that depends on it. |
| "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is the measured peak plus a margin. Lowering it moves the failure inside the command. |
| "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is a measurement of the command plus a margin. Lowering it moves the failure inside the command. |
| "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no variable whose name starts with `BOUNDED_RUN_`. |
| "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock files alone. |
| "The user told me to run it directly, but the skill says no exception" | An explicit instruction from the user comes first. Say one time what the wrapper protects, then obey. |
Expand Down
101 changes: 85 additions & 16 deletions skills/bounding-heavy-commands/scripts/bounded_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@

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 exact=yes|no exit=CODE
bounded-run: row label=NAME cpus=N budget=<n>M peak=<n>M held=<n>M|- exact=yes|no exit=CODE

budget is the suggested budget. A '-' stands for an option that the call did
budget is the suggested budget. held is the sampled peak of the memory that
the kernel cannot take back at once under the hard cap, or '-' without it.
A '-' in place of the label or of cpus stands for an option that the call did
not give. --measure-rows measures the command at each processor limit of the
list, the largest first. The largest runs with --memory. Without it, the
largest runs with the default budget where the hard cap is available, and
Expand Down Expand Up @@ -93,6 +95,7 @@
SCOPE_WAIT_SECONDS = 5.0
MARGIN_EXACT = 0.25
MARGIN_APPROXIMATE = 0.5
CACHE_FLOOR_DIVISOR = 4
Comment thread
sourcehawk marked this conversation as resolved.
Resolved
BUDGET_STEP_MIB = 256
HELD_COMMAND_CHARACTERS = 200
PR_SET_PDEATHSIG = 1
Expand Down Expand Up @@ -841,6 +844,33 @@ def cgroup_peak_mib(directory: str, names: Sequence[str] = ("memory.peak", "memo
return None


# The kernel cannot take back these pages at once to keep a cgroup under its limit: dirty and writeback file pages
# must reach the disk first. An older kernel has no 'kernel' line, and there its parts stand in for it.
HELD_FIELDS = ("anon", "shmem", "file_dirty", "file_writeback")
KERNEL_PARTS = ("kernel_stack", "pagetables", "sec_pagetables", "slab_unreclaimable", "sock", "percpu", "vmalloc")


def cgroup_held_mib(directory: str) -> Optional[int]:
"""Returns the memory of the cgroup that the kernel cannot take back at once, from its memory.stat.

Returns None when the file cannot be read or has none of the lines of that memory.
"""
text = _read_text(os.path.join(directory, "memory.stat"))
if text is None:
return None
fields = {}
for line in text.splitlines():
parts = line.split()
if len(parts) == 2 and parts[1].isdigit():
fields[parts[0]] = int(parts[1])
if "kernel" in fields:
# The 'kernel' line also counts the reclaimable slab, the cache of file names and inodes.
fields["kernel"] = max(0, fields["kernel"] - fields.get("slab_reclaimable", 0))
names = HELD_FIELDS + (("kernel",) if "kernel" in fields else KERNEL_PARTS)
found = [fields[name] for name in names if name in fields]
return math.ceil(sum(found) / (1024 * 1024)) if found else None
Comment thread
sourcehawk marked this conversation as resolved.
Resolved


def parse_group_rss_mib(text: str, group: int) -> Optional[int]:
total = 0
found = False
Expand Down Expand Up @@ -868,17 +898,51 @@ def rusage_peak_mib(maxrss: int, platform: str = sys.platform) -> int:
return math.ceil(maxrss / 1024)


def suggested_budget_mib(peak_mib: int, approximate: bool) -> int:
def _with_margin(mib: int, approximate: bool) -> int:
margin = MARGIN_APPROXIMATE if approximate else MARGIN_EXACT
return max(1, math.ceil(peak_mib * (1 + margin) / BUDGET_STEP_MIB)) * BUDGET_STEP_MIB
return max(1, math.ceil(mib * (1 + margin) / BUDGET_STEP_MIB)) * BUDGET_STEP_MIB


def suggested_budget_mib(peak_mib: int, approximate: bool, held_mib: Optional[int] = None) -> int:
"""Returns the suggested budget in MiB for a command with the peak. An approximate peak gets the larger margin.

held_mib is the sampled peak of the memory that the kernel cannot take back at once. With it, the budget
covers that memory and a quarter of the peak, and it is never more than the budget from the peak alone.
"""
from_peak = _with_margin(peak_mib, approximate)
if held_mib is None:
return from_peak
# A command that reads the same files again and again slows down when the cap leaves no room for their cache.
cache_floor = _with_margin(math.ceil(peak_mib / CACHE_FLOOR_DIVISOR), approximate)
return min(from_peak, max(_with_margin(held_mib, True), cache_floor))


def _larger(current: Optional[int], read: Callable[[], Optional[int]]) -> Optional[int]:
try:
value = read()
except Exception:
value = None
if value is not None and (current is None or value > current):
return value
return current


class PeakTracker(threading.Thread):
def __init__(self, read_sample: Callable[[], Optional[int]], interval: float) -> None:
"""Keeps the largest sample of read_sample in peak, and of read_held in held, until finish.

held stays None without read_held or when read_held gives no value.
"""

def __init__(
self, read_sample: Callable[[], Optional[int]], interval: float,
read_held: Optional[Callable[[], Optional[int]]] = None,
) -> None:
super().__init__(daemon=True)
self.read_sample = read_sample
self.read_held = read_held
self.interval = interval
self.peak: Optional[int] = None
self.held: Optional[int] = None
self.done = threading.Event()

def run(self) -> None:
Expand All @@ -888,12 +952,9 @@ def run(self) -> None:
return

def sample(self) -> None:
try:
value = self.read_sample()
except Exception:
value = None
if value is not None and (self.peak is None or value > self.peak):
self.peak = value
self.peak = _larger(self.peak, self.read_sample)
if self.read_held is not None:
self.held = _larger(self.held, self.read_held)

def finish(self) -> Optional[int]:
self.done.set()
Expand Down Expand Up @@ -1263,12 +1324,17 @@ def start_tracker(pid: int) -> None:
def read_sample() -> Optional[int]:
found = cgroup_directory(pid, unit)
return cgroup_peak_mib(found) if found is not None else None

def read_held() -> Optional[int]:
found = cgroup_directory(pid, unit)
return cgroup_held_mib(found) if found is not None else None
interval = min(settings.sample_seconds, 0.5)
else:
def read_sample() -> Optional[int]:
return group_rss_mib(pid)
read_held = None
interval = settings.sample_seconds
tracker = PeakTracker(read_sample, interval)
tracker = PeakTracker(read_sample, interval, read_held)
tracker.start()
trackers.append(tracker)

Expand Down Expand Up @@ -1303,6 +1369,7 @@ def on_start(pid: int) -> None:
)
code, maxrss = run_command(command, child_environ, on_start)
tracked = trackers[0].finish() if trackers else None
held = trackers[0].held if trackers else None
finally:
unlock_memory()
if capped:
Expand All @@ -1311,14 +1378,16 @@ def on_start(pid: int) -> None:

exact = reported is not None
peak = max(reported or tracked or 0, rusage_peak_mib(maxrss))
log("budget %d MiB, peak %d MiB (%s), exit %d" % (budget, peak, "cgroup" if exact else "sampled, approximate", code))
log("budget %d MiB, peak %d MiB (%s), held %s, exit %d" % (
budget, peak, "cgroup" if exact else "sampled, approximate", "-" if held is None else "%d MiB (sampled)" % held, code))
if capped and code == 137:
log("the command was killed; if the peak is near the budget, the hard cap stopped it")
suggested = suggested_budget_mib(peak, not exact)
suggested = suggested_budget_mib(peak, not exact, held)
if options.measure:
log("suggested budget %d MiB" % suggested)
log("row label=%s cpus=%s budget=%dM peak=%dM exact=%s exit=%d" % (
options.label or "-", options.cpus if options.cpus is not None else "-", suggested, peak, "yes" if exact else "no", code))
log("row label=%s cpus=%s budget=%dM peak=%dM held=%s exact=%s exit=%d" % (
options.label or "-", options.cpus if options.cpus is not None else "-", suggested, peak,
"-" if held is None else "%dM" % held, "yes" if exact else "no", code))
return code, suggested


Expand Down
Loading
Loading