Skip to content

Commit f0e4791

Browse files
sourcehawkclaude
andcommitted
fix(skills/bounding-heavy-commands): stop the suggested budget from counting file cache
The suggested budget came from memory.peak of the command's cgroup, which counts the page cache that the kernel takes back under the cap. A command that writes many files, such as a development server with a build cache, got a budget near the whole queue. While a capped command runs, the one sampler now also reads memory.stat and keeps the peak of the memory that the kernel cannot take back at once: anon, shmem, kernel (or its parts on an older kernel), and dirty and writeback file pages. The suggested budget is that peak with the margin for a sample, at least a quarter of memory.peak with its margin as a floor for the cache that a command reads again, and never more than the budget from memory.peak. Without a cgroup the budget is as before. The row line gains held=<n>M after peak= (held=- without the cap), and the summary line names both peaks. Fixes #59 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 52152f7 commit f0e4791

3 files changed

Lines changed: 188 additions & 27 deletions

File tree

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru
5151
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:
5252

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

57-
`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).
57+
`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).
5858

5959
A check prints its lines in a fixed form too:
6060

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

134-
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.
134+
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 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.
135135
6. Save the record.
136136

137137
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.

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

Lines changed: 82 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,11 @@
1010
1111
A measurement prints one row line on the error stream, in a fixed form:
1212
13-
bounded-run: row label=NAME cpus=N budget=<n>M peak=<n>M exact=yes|no exit=CODE
13+
bounded-run: row label=NAME cpus=N budget=<n>M peak=<n>M held=<n>M|- exact=yes|no exit=CODE
1414
15-
budget is the suggested budget. A '-' stands for an option that the call did
15+
budget is the suggested budget. held is the sampled peak of the memory that
16+
the kernel cannot take back at once under the hard cap, or '-' without it.
17+
A '-' in place of the label or of cpus stands for an option that the call did
1618
not give. --measure-rows measures the command at each processor limit of the
1719
list, the largest first. The largest runs with --memory. Without it, the
1820
largest runs with the default budget where the hard cap is available, and
@@ -93,6 +95,7 @@
9395
SCOPE_WAIT_SECONDS = 5.0
9496
MARGIN_EXACT = 0.25
9597
MARGIN_APPROXIMATE = 0.5
98+
CACHE_FLOOR_DIVISOR = 4
9699
BUDGET_STEP_MIB = 256
97100
HELD_COMMAND_CHARACTERS = 200
98101
PR_SET_PDEATHSIG = 1
@@ -841,6 +844,30 @@ def cgroup_peak_mib(directory: str, names: Sequence[str] = ("memory.peak", "memo
841844
return None
842845

843846

847+
# The kernel cannot take back these pages at once to keep a cgroup under its limit: dirty and writeback file pages
848+
# must reach the disk first. An older kernel has no 'kernel' line, and there its parts stand in for it.
849+
HELD_FIELDS = ("anon", "shmem", "file_dirty", "file_writeback")
850+
KERNEL_PARTS = ("kernel_stack", "slab_unreclaimable", "sock", "percpu")
851+
852+
853+
def cgroup_held_mib(directory: str) -> Optional[int]:
854+
"""Returns the memory of the cgroup that the kernel cannot take back at once, from its memory.stat.
855+
856+
Returns None when the file cannot be read or has none of the lines of that memory.
857+
"""
858+
text = _read_text(os.path.join(directory, "memory.stat"))
859+
if text is None:
860+
return None
861+
fields = {}
862+
for line in text.splitlines():
863+
parts = line.split()
864+
if len(parts) == 2 and parts[1].isdigit():
865+
fields[parts[0]] = int(parts[1])
866+
names = HELD_FIELDS + (("kernel",) if "kernel" in fields else KERNEL_PARTS)
867+
found = [fields[name] for name in names if name in fields]
868+
return math.ceil(sum(found) / (1024 * 1024)) if found else None
869+
870+
844871
def parse_group_rss_mib(text: str, group: int) -> Optional[int]:
845872
total = 0
846873
found = False
@@ -868,17 +895,51 @@ def rusage_peak_mib(maxrss: int, platform: str = sys.platform) -> int:
868895
return math.ceil(maxrss / 1024)
869896

870897

871-
def suggested_budget_mib(peak_mib: int, approximate: bool) -> int:
898+
def _with_margin(mib: int, approximate: bool) -> int:
872899
margin = MARGIN_APPROXIMATE if approximate else MARGIN_EXACT
873-
return max(1, math.ceil(peak_mib * (1 + margin) / BUDGET_STEP_MIB)) * BUDGET_STEP_MIB
900+
return max(1, math.ceil(mib * (1 + margin) / BUDGET_STEP_MIB)) * BUDGET_STEP_MIB
901+
902+
903+
def suggested_budget_mib(peak_mib: int, approximate: bool, held_mib: Optional[int] = None) -> int:
904+
"""Returns the suggested budget in MiB for a command with the peak. An approximate peak gets the larger margin.
905+
906+
held_mib is the sampled peak of the memory that the kernel cannot take back at once. With it, the budget
907+
covers that memory and a quarter of the peak, and it is never more than the budget from the peak alone.
908+
"""
909+
from_peak = _with_margin(peak_mib, approximate)
910+
if held_mib is None:
911+
return from_peak
912+
# A command that reads the same files again and again slows down when the cap leaves no room for their cache.
913+
cache_floor = _with_margin(math.ceil(peak_mib / CACHE_FLOOR_DIVISOR), approximate)
914+
return min(from_peak, max(_with_margin(held_mib, True), cache_floor))
915+
916+
917+
def _larger(current: Optional[int], read: Callable[[], Optional[int]]) -> Optional[int]:
918+
try:
919+
value = read()
920+
except Exception:
921+
value = None
922+
if value is not None and (current is None or value > current):
923+
return value
924+
return current
874925

875926

876927
class PeakTracker(threading.Thread):
877-
def __init__(self, read_sample: Callable[[], Optional[int]], interval: float) -> None:
928+
"""Keeps the largest sample of read_sample in peak, and of read_held in held, until finish.
929+
930+
held stays None without read_held or when read_held gives no value.
931+
"""
932+
933+
def __init__(
934+
self, read_sample: Callable[[], Optional[int]], interval: float,
935+
read_held: Optional[Callable[[], Optional[int]]] = None,
936+
) -> None:
878937
super().__init__(daemon=True)
879938
self.read_sample = read_sample
939+
self.read_held = read_held
880940
self.interval = interval
881941
self.peak: Optional[int] = None
942+
self.held: Optional[int] = None
882943
self.done = threading.Event()
883944

884945
def run(self) -> None:
@@ -888,12 +949,9 @@ def run(self) -> None:
888949
return
889950

890951
def sample(self) -> None:
891-
try:
892-
value = self.read_sample()
893-
except Exception:
894-
value = None
895-
if value is not None and (self.peak is None or value > self.peak):
896-
self.peak = value
952+
self.peak = _larger(self.peak, self.read_sample)
953+
if self.read_held is not None:
954+
self.held = _larger(self.held, self.read_held)
897955

898956
def finish(self) -> Optional[int]:
899957
self.done.set()
@@ -1263,12 +1321,17 @@ def start_tracker(pid: int) -> None:
12631321
def read_sample() -> Optional[int]:
12641322
found = cgroup_directory(pid, unit)
12651323
return cgroup_peak_mib(found) if found is not None else None
1324+
1325+
def read_held() -> Optional[int]:
1326+
found = cgroup_directory(pid, unit)
1327+
return cgroup_held_mib(found) if found is not None else None
12661328
interval = min(settings.sample_seconds, 0.5)
12671329
else:
12681330
def read_sample() -> Optional[int]:
12691331
return group_rss_mib(pid)
1332+
read_held = None
12701333
interval = settings.sample_seconds
1271-
tracker = PeakTracker(read_sample, interval)
1334+
tracker = PeakTracker(read_sample, interval, read_held)
12721335
tracker.start()
12731336
trackers.append(tracker)
12741337

@@ -1303,6 +1366,7 @@ def on_start(pid: int) -> None:
13031366
)
13041367
code, maxrss = run_command(command, child_environ, on_start)
13051368
tracked = trackers[0].finish() if trackers else None
1369+
held = trackers[0].held if trackers else None
13061370
finally:
13071371
unlock_memory()
13081372
if capped:
@@ -1311,14 +1375,16 @@ def on_start(pid: int) -> None:
13111375

13121376
exact = reported is not None
13131377
peak = max(reported or tracked or 0, rusage_peak_mib(maxrss))
1314-
log("budget %d MiB, peak %d MiB (%s), exit %d" % (budget, peak, "cgroup" if exact else "sampled, approximate", code))
1378+
log("budget %d MiB, peak %d MiB (%s), held %s, exit %d" % (
1379+
budget, peak, "cgroup" if exact else "sampled, approximate", "-" if held is None else "%d MiB (sampled)" % held, code))
13151380
if capped and code == 137:
13161381
log("the command was killed; if the peak is near the budget, the hard cap stopped it")
1317-
suggested = suggested_budget_mib(peak, not exact)
1382+
suggested = suggested_budget_mib(peak, not exact, held)
13181383
if options.measure:
13191384
log("suggested budget %d MiB" % suggested)
1320-
log("row label=%s cpus=%s budget=%dM peak=%dM exact=%s exit=%d" % (
1321-
options.label or "-", options.cpus if options.cpus is not None else "-", suggested, peak, "yes" if exact else "no", code))
1385+
log("row label=%s cpus=%s budget=%dM peak=%dM held=%s exact=%s exit=%d" % (
1386+
options.label or "-", options.cpus if options.cpus is not None else "-", suggested, peak,
1387+
"-" if held is None else "%dM" % held, "yes" if exact else "no", code))
13221388
return code, suggested
13231389

13241390

0 commit comments

Comments
 (0)