Skip to content

Commit 48fd634

Browse files
sourcehawkclaude
andauthored
fix(skills/bounding-heavy-commands): stop the suggested budget from counting file cache (#67)
* 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> * fix(skills/bounding-heavy-commands): count page tables and vmalloc in the held memory of an older kernel A kernel with a 'kernel' line in memory.stat counts page tables and vmalloc memory in it. On an older kernel the wrapper added the parts of kernel memory itself but left out pagetables, sec_pagetables, and vmalloc, so the same command reported less held memory there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(skills/bounding-heavy-commands): double the cap after a capped measurement, and stop calling the budget the peak The suggested budget can now be far below the cap that stopped a run, so "two times the budget that the wrapper printed" could retry below the failed cap. The rule now names the budget of the cap in the summary line. A Red Flags row still said that the budget is the measured peak plus a margin. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(skills/bounding-heavy-commands): show held=- in the fixed form of the row line The wrapper prints held=- when it has no sample of the held memory, and the prose says so, but the fixed form in the skill showed only a number. It now shows both, as the usage text does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(skills/bounding-heavy-commands): leave the reclaimable slab out of the held memory on a newer kernel The 'kernel' line of memory.stat includes slab_reclaimable, the cache of file names and inodes, which the kernel can take back under the cap. The held memory counted it, so a command that walks many files got a larger held peak than it needs. The wrapper now subtracts slab_reclaimable from the kernel line. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(skills/bounding-heavy-commands): change a row when the suggested budget moves, not only the peak Under the hard cap the suggested budget follows the held memory, so it can change while the full peak stays the same. The record rule changed a row only when the peak moved, so an agent kept a budget that the wrapper no longer suggested. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fce95a1 commit 48fd634

3 files changed

Lines changed: 194 additions & 29 deletions

File tree

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

Lines changed: 5 additions & 5 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

@@ -107,7 +107,7 @@ Then, before each heavy command, use the first case that applies:
107107
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.
108108
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.
109109

110-
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.
110+
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.
111111

112112
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.
113113

@@ -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 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.
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.
@@ -212,7 +212,7 @@ When Python is missing or too old, and when the fault is a fault of the machine,
212212
| "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. |
213213
| "I'll run the plain command once to check quickly" | One command outside the queue is all a freeze needs. |
214214
| "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. |
215-
| "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. |
215+
| "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. |
216216
| "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_`. |
217217
| "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. |
218218
| "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. |

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

Lines changed: 85 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,33 @@ 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", "pagetables", "sec_pagetables", "slab_unreclaimable", "sock", "percpu", "vmalloc")
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+
if "kernel" in fields:
867+
# The 'kernel' line also counts the reclaimable slab, the cache of file names and inodes.
868+
fields["kernel"] = max(0, fields["kernel"] - fields.get("slab_reclaimable", 0))
869+
names = HELD_FIELDS + (("kernel",) if "kernel" in fields else KERNEL_PARTS)
870+
found = [fields[name] for name in names if name in fields]
871+
return math.ceil(sum(found) / (1024 * 1024)) if found else None
872+
873+
844874
def parse_group_rss_mib(text: str, group: int) -> Optional[int]:
845875
total = 0
846876
found = False
@@ -868,17 +898,51 @@ def rusage_peak_mib(maxrss: int, platform: str = sys.platform) -> int:
868898
return math.ceil(maxrss / 1024)
869899

870900

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

875929

876930
class PeakTracker(threading.Thread):
877-
def __init__(self, read_sample: Callable[[], Optional[int]], interval: float) -> None:
931+
"""Keeps the largest sample of read_sample in peak, and of read_held in held, until finish.
932+
933+
held stays None without read_held or when read_held gives no value.
934+
"""
935+
936+
def __init__(
937+
self, read_sample: Callable[[], Optional[int]], interval: float,
938+
read_held: Optional[Callable[[], Optional[int]]] = None,
939+
) -> None:
878940
super().__init__(daemon=True)
879941
self.read_sample = read_sample
942+
self.read_held = read_held
880943
self.interval = interval
881944
self.peak: Optional[int] = None
945+
self.held: Optional[int] = None
882946
self.done = threading.Event()
883947

884948
def run(self) -> None:
@@ -888,12 +952,9 @@ def run(self) -> None:
888952
return
889953

890954
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
955+
self.peak = _larger(self.peak, self.read_sample)
956+
if self.read_held is not None:
957+
self.held = _larger(self.held, self.read_held)
897958

898959
def finish(self) -> Optional[int]:
899960
self.done.set()
@@ -1263,12 +1324,17 @@ def start_tracker(pid: int) -> None:
12631324
def read_sample() -> Optional[int]:
12641325
found = cgroup_directory(pid, unit)
12651326
return cgroup_peak_mib(found) if found is not None else None
1327+
1328+
def read_held() -> Optional[int]:
1329+
found = cgroup_directory(pid, unit)
1330+
return cgroup_held_mib(found) if found is not None else None
12661331
interval = min(settings.sample_seconds, 0.5)
12671332
else:
12681333
def read_sample() -> Optional[int]:
12691334
return group_rss_mib(pid)
1335+
read_held = None
12701336
interval = settings.sample_seconds
1271-
tracker = PeakTracker(read_sample, interval)
1337+
tracker = PeakTracker(read_sample, interval, read_held)
12721338
tracker.start()
12731339
trackers.append(tracker)
12741340

@@ -1303,6 +1369,7 @@ def on_start(pid: int) -> None:
13031369
)
13041370
code, maxrss = run_command(command, child_environ, on_start)
13051371
tracked = trackers[0].finish() if trackers else None
1372+
held = trackers[0].held if trackers else None
13061373
finally:
13071374
unlock_memory()
13081375
if capped:
@@ -1311,14 +1378,16 @@ def on_start(pid: int) -> None:
13111378

13121379
exact = reported is not None
13131380
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))
1381+
log("budget %d MiB, peak %d MiB (%s), held %s, exit %d" % (
1382+
budget, peak, "cgroup" if exact else "sampled, approximate", "-" if held is None else "%d MiB (sampled)" % held, code))
13151383
if capped and code == 137:
13161384
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)
1385+
suggested = suggested_budget_mib(peak, not exact, held)
13181386
if options.measure:
13191387
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))
1388+
log("row label=%s cpus=%s budget=%dM peak=%dM held=%s exact=%s exit=%d" % (
1389+
options.label or "-", options.cpus if options.cpus is not None else "-", suggested, peak,
1390+
"-" if held is None else "%dM" % held, "yes" if exact else "no", code))
13221391
return code, suggested
13231392

13241393

0 commit comments

Comments
 (0)