Skip to content

Commit 94e4a22

Browse files
sourcehawkclaude
andcommitted
feat(skills/bounding-heavy-commands): name the commands that hold the queue in the check
When the queue is full, every session waits and no one can see what holds it. The user has to ask, and the agent has no way to answer: the skill tells it not to look for the process that holds a lock file. The kernel already knows. Each running bounded command is a scope in the slice that the probe finds. The check now prints one held line for each such scope, with its budget, the memory it uses, its age, its working directory, and its command without the prefix that the wrapper adds. A field that cannot be read is '-', and a scope that ends while it is read is skipped. Without the hard cap there are no scopes, so there are no held lines. The skill tells an agent to run the check after a long wait and to name the held commands in its message to the user. It says that the held lines are the way to name what holds the queue, and that a held command belongs to another session or to the user, so the agent never stops it. Refs #57 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6c90321 commit 94e4a22

3 files changed

Lines changed: 204 additions & 18 deletions

File tree

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,11 @@ A check prints its lines in a fixed form too:
6060

6161
```
6262
bounded-run: check slots=<n> slot=<n>M free-slots=<n> free=<n>M unused=<n>M headroom=<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>
6364
bounded-run: check budget=<n>M slots=<n> starts=<yes|no>
6465
```
6566

66-
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, and the headroom. `line=busy` means that a command waits in the line. Each next line is one `--memory`, in the order given: the slots that it needs, 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, and the headroom. `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, 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.
6768

6869
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).
6970

@@ -157,14 +158,14 @@ A command that the project adds later gets its entry when an agent first needs i
157158

158159
## Rules for the wait
159160

160-
A long wait means that the machine is full. It is never a fault to repair: the queue has no state that can go wrong between runs, and an agent that repairs it breaks it. Waiting commands take turns in a line. A command that needs many slots is not overtaken by smaller commands that arrive after it. So a small command can wait behind a large one, also when a slot is free. Unless an instruction says otherwise (see the next section), the only correct moves are to keep the run in the queue and to tell the user that the machine is full and the command is queued. A subagent tells its dispatcher in its report.
161+
A long wait means that the machine is full. It is never a fault to repair: the queue has no state that can go wrong between runs, and an agent that repairs it breaks it. Waiting commands take turns in a line. A command that needs many slots is not overtaken by smaller commands that arrive after it. So a small command can wait behind a large one, also when a slot is free. Unless an instruction says otherwise (see the next section), the only correct moves are to keep the run in the queue and to tell the user that the machine is full and the command is queued. After a long wait, run the wrapper with `--check`, and in that message name each command of its `held` lines, with its directory and its age, so that the user can see what holds the machine. A subagent tells its dispatcher in its report.
161162

162163
- **Run a bounded command in the background, with no short timeout around it.** It can wait in the queue for minutes before it starts. Where the harness requires a timeout, use the longest one that it permits. When that timeout ends a run, start the run again through the wrapper, and say in your report that the timeout ended the run and that the code did not fail. A timeout that you calculate from the run time of the command does not count the wait. A timeout that fires during the wait kills a command that never ran, and the result reads like a failure of the code.
163164
- **Plan the time as if the commands run one after the other.** Two bounded commands that start together are safe, because the queue puts them in sequence when the machine cannot hold both. So a parallel start does not always save time, and a promise to the user that depends on it is a guess.
164165
- **Do not lower a budget to start sooner.** A smaller budget does not make the command smaller. It moves the failure inside the command: on Linux as a kill at the hard cap, elsewhere as the swap that the queue exists to prevent. A row at a smaller `--cpus` is not a lower budget: it is a smaller command, measured, and it is the way to start sooner (§The record).
165166
- **Do not run the plain command because the queue is slow.** A slow queue means the machine is full. The plain command is how it freezes. This includes a narrower form of the command: one test file outside the queue is a command that the queue cannot count.
166167
- **Do not set an environment variable whose name starts with `BOUNDED_RUN_`.** The usage text of the wrapper lists variables that change how the queue counts memory, where it keeps its locks, and whether the hard cap applies. They are for a person who tunes the whole machine in a shell profile, and for the tests of the wrapper. A call that sets one does not share the queue with the other sessions, or it runs with no cap. A note in your project memory that recommends one is wrong: delete the note, and tell the user that you did.
167-
- **Do not touch the lock files of the wrapper.** The wrapper keeps them in a directory of its own. Do not look for that directory. Do not delete, move, or edit a file in it, and do not look for the process that holds one of these lock files. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot.
168+
- **Do not touch the lock files of the wrapper.** The wrapper keeps them in a directory of its own. Do not look for that directory. Do not delete, move, or edit a file in it, and do not look for the process that holds one of these lock files. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot. The `held` lines of `--check` are the way to name what holds the queue: do not look further, and never stop a held command, because it belongs to another session or to the user.
168169
- **Do not sleep and retry around a collision, not even one time.** A port in use or a tool's lock means two commands wanted one resource. Add the resource to the record as an `--exclusive` name and run through the wrapper. A subagent adds the option to its own command line and names the resource in its report, so that its dispatcher corrects the record. Do not stop the process that holds the resource: it belongs to a different session. When a run with the `--exclusive` name fails on the same collision, the holder did not go through the wrapper or belongs to a different repository: tell the user, or your dispatcher, what holds the resource, and wait for the answer.
169170

170171
## When an instruction sends a command around the wrapper

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

Lines changed: 90 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@
2020
is the first exit code that is not 0.
2121
2222
--check runs no command and holds no lock when it returns. Its exit code is 0.
23-
It prints the state of the queue at that moment, and one line for each
24-
--memory, in the order given:
23+
It prints the state of the queue at that moment, one held line for each
24+
running bounded command where the hard cap is available, and one line for
25+
each --memory, in the order given:
2526
2627
bounded-run: check slots=N slot=MIBM free-slots=N|- free=MIBM|- unused=MIBM|- headroom=MIBM line=free|busy
28+
bounded-run: check held unit=NAME budget=MIBM|- used=MIBM|- age=Ns|- dir=PATH|- command=TEXT|-
2729
bounded-run: check budget=MIBM slots=N starts=yes|no
2830
2931
A '-' stands for a value that the check cannot read or count here. starts=yes
@@ -89,6 +91,7 @@
8991
MARGIN_EXACT = 0.25
9092
MARGIN_APPROXIMATE = 0.5
9193
BUDGET_STEP_MIB = 256
94+
HELD_COMMAND_CHARACTERS = 200
9295
PR_SET_PDEATHSIG = 1
9396
USAGE = (
9497
"usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] [--label NAME] -- COMMAND...\n"
@@ -670,19 +673,25 @@ def own_scope_name(proc_root: str = "/proc") -> Optional[str]:
670673
return None if path is None else os.path.basename(path)
671674

672675

676+
def _bounded_scopes(parent: str, skip: Sequence[str]) -> List[str]:
677+
"""Returns the names of the scopes of bounded commands in parent, less the probe scopes and the names in skip."""
678+
try:
679+
names = os.listdir(parent)
680+
except OSError:
681+
return []
682+
return sorted(
683+
name for name in names
684+
if name.startswith(PREFIX + "-") and name.endswith(".scope") and not name.endswith("-probe.scope") and name not in skip
685+
)
686+
687+
673688
def unused_budget_mib(parent: str, skip: Sequence[str]) -> int:
674689
"""Returns the part of their budgets that the bounded commands whose scopes are in parent do not use yet.
675690
676691
Probe scopes, the scopes named in skip, and scopes with no memory limit add nothing.
677692
"""
678-
try:
679-
names = os.listdir(parent)
680-
except OSError:
681-
return 0
682693
unused = 0
683-
for name in names:
684-
if not name.startswith(PREFIX + "-") or not name.endswith(".scope") or name.endswith("-probe.scope") or name in skip:
685-
continue
694+
for name in _bounded_scopes(parent, skip):
686695
try:
687696
with open(os.path.join(parent, name, "memory.max")) as handle:
688697
limit = handle.read().strip()
@@ -697,6 +706,72 @@ def unused_budget_mib(parent: str, skip: Sequence[str]) -> int:
697706
return unused // (1024 * 1024)
698707

699708

709+
def _read_text(path: str) -> Optional[str]:
710+
try:
711+
with open(path, "rb") as handle:
712+
return handle.read().decode("utf-8", "replace")
713+
except OSError:
714+
return None
715+
716+
717+
def _process_age_seconds(pid: int, proc_root: str, ticks: int) -> Optional[int]:
718+
stat_text = _read_text(os.path.join(proc_root, str(pid), "stat"))
719+
uptime = _read_text(os.path.join(proc_root, "uptime"))
720+
try:
721+
# The name of the process can hold spaces and ')', so the fields are counted from its last ')'.
722+
start = int(stat_text.rsplit(")", 1)[1].split()[19])
723+
return max(0, int(float(uptime.split()[0]) - start / ticks))
724+
except (AttributeError, IndexError, ValueError):
725+
return None
726+
727+
728+
def _held_command(pid: int, proc_root: str) -> Optional[str]:
729+
text = _read_text(os.path.join(proc_root, str(pid), "cmdline"))
730+
if not text:
731+
return None
732+
arguments = text.rstrip("\0").split("\0")
733+
if "--inside-cap" in arguments:
734+
at = arguments.index("--inside-cap")
735+
if arguments[at + 3:at + 4] == ["--"]:
736+
arguments = arguments[at + 4:]
737+
# The check prints one line for each command, so a line break inside an argument becomes a space.
738+
return " ".join(" ".join(arguments).split())[:HELD_COMMAND_CHARACTERS]
739+
740+
741+
def held_commands(parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None) -> List[str]:
742+
"""Returns one text for each running bounded command whose scope is in parent, as the fields of a check line.
743+
744+
A field that cannot be read is '-'. Probe scopes and the scopes named in skip give no text.
745+
"""
746+
if ticks is None:
747+
ticks = os.sysconf("SC_CLK_TCK")
748+
749+
def mib(text: Optional[str]) -> str:
750+
return "%dM" % (int(text) // (1024 * 1024)) if text is not None and text.strip().isdigit() else "-"
751+
752+
held = []
753+
for name in _bounded_scopes(parent, skip):
754+
directory = os.path.join(parent, name)
755+
limit = _read_text(os.path.join(directory, "memory.max"))
756+
current = _read_text(os.path.join(directory, "memory.current"))
757+
pids = [int(line) for line in (_read_text(os.path.join(directory, "cgroup.procs")) or "").split() if line.isdigit()]
758+
if not os.path.isdir(directory):
759+
# The scope ended while it was read.
760+
continue
761+
# The wrapper starts the first process of the scope, and that process starts the command.
762+
pid = min(pids) if pids else None
763+
age = _process_age_seconds(pid, proc_root, ticks) if pid is not None else None
764+
try:
765+
working = os.readlink(os.path.join(proc_root, str(pid), "cwd")) if pid is not None else None
766+
except OSError:
767+
working = None
768+
command = _held_command(pid, proc_root) if pid is not None else None
769+
held.append("unit=%s budget=%s used=%s age=%s dir=%s command=%s" % (
770+
name[:-len(".scope")], mib(limit), mib(current), "-" if age is None else "%ds" % age,
771+
working or "-", command or "-"))
772+
return held
773+
774+
700775
def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]:
701776
try:
702777
with open(os.path.join(proc_root, str(pid), "cgroup")) as handle:
@@ -1162,12 +1237,11 @@ def check(
11621237
line = _try_lock(os.path.join(directory, "line.lock"))
11631238
if line is not None:
11641239
os.close(line)
1240+
unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6))
1241+
choice = None if settings.no_cap else choose_cap_prefix(settings.slot_mib, None, unit, probe_cap)
1242+
scopes = scope_parent_directory(choice[1]) if choice is not None else None
1243+
skip = [name for name in (own_scope_name(),) if name is not None]
11651244
if read_outstanding is None:
1166-
unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6))
1167-
choice = None if settings.no_cap else choose_cap_prefix(settings.slot_mib, None, unit, probe_cap)
1168-
scopes = scope_parent_directory(choice[1]) if choice is not None else None
1169-
skip = [name for name in (own_scope_name(),) if name is not None]
1170-
11711245
def read_outstanding() -> Optional[int]:
11721246
return None if scopes is None else unused_budget_mib(scopes, skip)
11731247

@@ -1184,6 +1258,8 @@ def mib(value: Optional[int]) -> str:
11841258
log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s headroom=%dM line=%s" % (
11851259
count, settings.slot_mib, "-" if free_slots is None else free_slots, mib(available), mib(outstanding),
11861260
headroom, "free" if line is not None else "busy"))
1261+
for held in held_commands(scopes, skip) if scopes is not None else []:
1262+
log("check held " + held)
11871263
for budget in budgets:
11881264
needed = slots_needed(budget, settings.slot_mib, count)
11891265
starts = (line is not None and free_slots is not None and free_slots >= needed

0 commit comments

Comments
 (0)