diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 6511ea7..ca2fad5 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -11,7 +11,7 @@ Every heavy command an agent starts goes through the wrapper. There is no except A machine freezes because of the heavy commands that run on it, not because of the number of agents. Sessions in other terminals and other projects run their own test suites and builds at the same moment, and no session can see the others. When the commands together need more memory than the machine has, it swaps until it stops responding, and that costs every session, not only the one that started the last command. The wrapper makes the commands of every session and every project on the machine take turns on its memory, so too much work shows up as a queue instead of a freeze. -**Looking first does not protect the machine.** Two sessions that look at the load at the same moment both see a quiet machine, and both start. A sum of budgets against the machine's total memory does not protect it either: the sum counts your commands and no one else's. Only a reservation that every session takes before it starts can count the commands, and the wrapper is that reservation. +**Looking first does not protect the machine.** Two sessions that look at the load at the same moment both see a quiet machine, and both start. A sum of budgets against the machine's total memory does not protect it either: the sum counts your commands and no one else's. Only a reservation that every session takes before it starts can count the commands, and the wrapper is that reservation. The check of the wrapper looks too, but it decides which measured row to queue, never whether to queue (§The record). **Violating the letter of these rules is violating their spirit.** @@ -35,6 +35,7 @@ A server that a heavy command talks to is a part of that command: a development ``` python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... [--measure] [--label ] -- python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure-rows ,,... [--memory ] [--exclusive ]... [--label ] -- +python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --check [--memory ]... ``` | Option | Meaning | @@ -45,6 +46,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--measure` | Also print a suggested budget. Discovery uses it. With no `--memory`, the command runs alone in the queue. | | `--measure-rows ,,...` | 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 alone in the queue. 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. The exit code is the first exit code of a row that is not 0. | | `--label ` | A name for the row lines of a measurement, such as `unit-tests`. Use letters, digits, `.`, `_`, and `-`, and start with a letter or a digit. It changes nothing else. | +| `--check` | Run no command. Print the state of the queue now, and for each `--memory`, whether a command of that budget would start now. It takes only `--memory`, which you can repeat. It holds no slot, and its exit code is 0. §The record says how to choose a row with it. | 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: @@ -54,6 +56,16 @@ bounded-run: row label= cpus= budget=M peak=M exact= exit `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). +A check prints its lines in a fixed form too: + +``` +bounded-run: check slots= slot=M free-slots= free=M unused=M line= +bounded-run: check held unit= budget=M used=M age=s dir= command= +bounded-run: check budget=M slots= headroom=M starts= +``` + +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. + 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). The wrapper sets `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB` in the environment of the command, from `--cpus` and `--memory`. A recorded command line can read them and hand them to the toolchain's own parallelism and memory settings. You do not set them: you change them with the two options. @@ -81,12 +93,16 @@ A budget is valid only at the `--cpus` of its row. The same command at more proc 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. +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. + +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. + An entry is complete when it has a `self-bound` field, at least one row, and one default row whose `--cpus` and budget are the values in its command line. An entry without the `self-bound` field is incomplete, also when it has a budget: its budget can be the peak of a command that nothing limits. An entry from an older shape of this record, with one budget and no table, is complete in one case only: its command line passes `--cpus` to the wrapper, before the `--`, and reads `BOUNDED_RUN_CPUS`. Then rewrite it into this shape. The setting that reads the variable is its `self-bound`, and its budget, peak, and date become the default row at that `--cpus`. Then, before each heavy command, use the first case that applies: 1. **Your prompt carries bounded command lines.** You are a subagent. Use them under the rule that your prompt gives with them, and run no discovery. For a heavy command that your prompt does not carry, use the wrapper with no `--memory` option. -2. **The record exists and has a complete entry for the command.** Check that the plain command still exists in the project, and that the file of the wrapper in the command line still exists. When the file of the wrapper is not there, an update of the plugin moved it. The command line in §The wrapper shows the correct path: put it into each command line of the record. Then use the bounded command line with the default row. +2. **The record exists and has a complete entry for the command.** Check that the plain command still exists in the project, and that the file of the wrapper in the command line still exists. When the file of the wrapper is not there, an update of the plugin moved it. The command line in §The wrapper shows the correct path: put it into each command line of the record. Then use the bounded command line with the row that you chose. 3. **The record exists, and the command is not in it, its entry is incomplete, or its entry is no longer correct.** Run the discovery for that command and correct the entry. When the command line changes in more than the values of the wrapper's `--memory` and `--cpus`, its rows measured a different command: delete them, and measure the new command line. Remove an entry whose command the project no longer has. 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. @@ -142,14 +158,14 @@ A command that the project adds later gets its entry when an agent first needs i ## Rules for the wait -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. Only the command at the head of the line tries for slots, so the smaller commands behind it do not take the slots that it waits for. The line has no fixed order, and a head that sees no slot come free for 5 minutes lets the commands behind it try first. 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. +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. Only the command at the head of the line tries for slots, so the smaller commands behind it do not take the slots that it waits for. The line has no fixed order, and a head that sees no slot come free for 5 minutes lets the commands behind it try first. 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. - **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. - **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. - **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). - **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. - **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. -- **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. +- **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. - **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. ## When an instruction sends a command around the wrapper @@ -168,8 +184,8 @@ A subagent does not see your project memory. It knows the bounded commands only On a machine on which the wrapper can run, every dispatch prompt for a subagent that will run a heavy command MUST include: -1. The bounded command line for each heavy command, copied from the record, with the `--cpus` and the budget of the row that you chose for it. -2. This rule, in these words: "Run the bounded commands as written. You can make two changes: a narrower argument at the end of the line, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited." +1. The bounded command line for each heavy command, copied from the record, with the `--cpus` and the budget of its default row. When its entry has more than one row, also the `--cpus` and the budget of each row, and its check line with one `--memory` for each row. +2. This rule, in these words: "Run the bounded commands as written. You can make three changes: the `--cpus` and the `--memory` of a row that this prompt gives for the command, a narrower argument at the end of the line, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. When this prompt gives a command more than one row, run its check line before each run, and use the largest row with `starts=yes`, or the default row when no row has it. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited. After a long wait, run the same wrapper with `--check`, and name in your report each command of its `held` lines, with its directory and its age." 3. Each command that an instruction exempts from the wrapper, in its plain form, in a list of its own, with the instruction that exempts it. The rule of item 2 does not apply to that list. An instruction of the user that covers one run goes to the one subagent that does that run, and to no other. Do not dispatch fewer subagents to protect the machine. The queue protects it. Subagents that wait in the queue cost time, not memory. On a machine on which the wrapper cannot run, the next section says how to dispatch. @@ -191,6 +207,7 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "This session is the only one running, so the plain command is fine" | You cannot see other sessions or other projects. Each heavy command goes through the wrapper, unless an instruction names the plain command. | | "Both budgets together are well under the machine's memory" | The sum counts your commands only. The queue counts the commands of every session. | | "I'll check the load first and start when it is quiet" | Each session that looks at that moment sees the same quiet machine. Take the reservation: run through the wrapper. | +| "The check says it would start, so I'll run the plain command" | The check is a snapshot, not a reservation. Another session can take the same slots a moment later. Run the chosen row through the wrapper. | | "It is only the linter, it is small" | The record says what is heavy, not your sense of it. Not in the record, and not a part of a recorded command, means not yet measured. | | "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. | diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 00717cd..ad2b6c7 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -3,6 +3,7 @@ Usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] [--label NAME] -- COMMAND... bounded_run.py --measure-rows N,N,... [--memory SIZE] [--exclusive NAME]... [--label NAME] -- COMMAND... + bounded_run.py --check [--memory SIZE]... The exit code is the exit code of the command. Exit code 125 means that this script failed before the command gave a result. @@ -18,6 +19,18 @@ the budget of the one before it when that run did not exit 0. The exit code is the first exit code that is not 0. +--check runs no command and holds no lock when it returns. Its exit code is 0. +It prints the state of the queue at that moment, one held line for each +running bounded command where the hard cap is available, and one line for +each --memory, in the order given: + + bounded-run: check slots=N slot=M free-slots=N|- free=M|- unused=M|- line=free|busy + bounded-run: check held unit=NAME budget=M|- used=M|- age=Ns|- dir=PATH|- command=TEXT|- + bounded-run: check budget=M slots=N headroom=M starts=yes|no + +A '-' stands for a value that the check cannot read or count here. starts=yes +means that a run of that budget would start now. It is not a reservation. + A normal call sets none of the environment variables below. A person can set the tuning values in the profile of the shell, so that every session on the machine uses the same values. The tests of this script set the @@ -68,6 +81,7 @@ PREFIX = "bounded-run" EXIT_WRAPPER = 125 ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE" +VALUE_OPTIONS = ("--memory", "--cpus", "--exclusive", "--measure-rows", "--label") SLOT_MIB = 2048 MINIMUM_RESERVE_MIB = 2048 MINIMUM_HEADROOM_MIB = 1024 @@ -79,10 +93,12 @@ MARGIN_EXACT = 0.25 MARGIN_APPROXIMATE = 0.5 BUDGET_STEP_MIB = 256 +HELD_COMMAND_CHARACTERS = 200 PR_SET_PDEATHSIG = 1 USAGE = ( "usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] [--label NAME] -- COMMAND...\n" - " bounded_run.py --measure-rows N,N,... [--memory SIZE] [--exclusive NAME]... [--label NAME] -- COMMAND..." + " bounded_run.py --measure-rows N,N,... [--memory SIZE] [--exclusive NAME]... [--label NAME] -- COMMAND...\n" + " bounded_run.py --check [--memory SIZE]..." ) # The exit codes of a run that a stop signal to the wrapper ended: 128 plus SIGHUP, SIGINT, SIGQUIT, or SIGTERM. STOP_CODES = frozenset(128 + int(signum) for signum in (signal.SIGHUP, signal.SIGINT, signal.SIGQUIT, signal.SIGTERM)) @@ -441,8 +457,11 @@ def _names_free(directory: str, exclusive_files: Sequence[str]) -> bool: return True -def _free_slots(directory: str, count: int) -> int: - turn = _lock(os.path.join(directory, "reserve.lock"), wait=True) +def _free_slots(directory: str, count: int, wait: bool = True) -> Optional[int]: + """Returns the number of free slots, or None when wait is false and a waiter holds the turn lock.""" + turn = _lock(os.path.join(directory, "reserve.lock"), wait=wait) + if turn is None: + return None try: free = 0 for index in range(count): @@ -553,6 +572,11 @@ def available_memory_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/c return min(found) if found else None +def memory_fits(budget_mib: int, available: Optional[int], outstanding: Optional[int], headroom_mib: int) -> bool: + """Returns whether a command of the budget may start. True when the free memory is not known.""" + return available is None or available - (outstanding or 0) - headroom_mib >= budget_mib + + def wait_for_memory( budget_mib: int, interval_seconds: float, poll_seconds: float, headroom_mib: int = 0, read_available: Callable[[], Optional[int]] = available_memory_mib, @@ -583,7 +607,7 @@ def wait_for_memory( outstanding = None if before is None or after is None else max(before, after) counted = "unused running budgets not counted here" if outstanding is None else "%d MiB of running budgets unused" % outstanding state = "%d MiB free, %s, %d MiB headroom, budget %d MiB" % (available, counted, headroom_mib, budget_mib) - if available - (outstanding or 0) - headroom_mib >= budget_mib: + if memory_fits(budget_mib, available, outstanding, headroom_mib): log(state + "; starting") return waited = clock() - started @@ -661,19 +685,25 @@ def own_scope_name(proc_root: str = "/proc") -> Optional[str]: return None if path is None else os.path.basename(path) +def _bounded_scopes(parent: str, skip: Sequence[str]) -> List[str]: + """Returns the names of the scopes of bounded commands in parent, less the probe scopes and the names in skip.""" + try: + names = os.listdir(parent) + except OSError: + return [] + return sorted( + name for name in names + if name.startswith(PREFIX + "-") and name.endswith(".scope") and not name.endswith("-probe.scope") and name not in skip + ) + + def unused_budget_mib(parent: str, skip: Sequence[str]) -> int: """Returns the part of their budgets that the bounded commands whose scopes are in parent do not use yet. Probe scopes, the scopes named in skip, and scopes with no memory limit add nothing. """ - try: - names = os.listdir(parent) - except OSError: - return 0 unused = 0 - for name in names: - if not name.startswith(PREFIX + "-") or not name.endswith(".scope") or name.endswith("-probe.scope") or name in skip: - continue + for name in _bounded_scopes(parent, skip): try: with open(os.path.join(parent, name, "memory.max")) as handle: limit = handle.read().strip() @@ -715,6 +745,79 @@ def wait_for_scope( return True +def _read_text(path: str) -> Optional[str]: + try: + with open(path, "rb") as handle: + return handle.read().decode("utf-8", "replace") + except OSError: + return None + + +def _process_age_seconds(pid: int, proc_root: str, ticks: int) -> Optional[int]: + stat_text = _read_text(os.path.join(proc_root, str(pid), "stat")) + uptime = _read_text(os.path.join(proc_root, "uptime")) + try: + # The name of the process can hold spaces and ')', so the fields are counted from its last ')'. + start = int(stat_text.rsplit(")", 1)[1].split()[19]) + return max(0, int(float(uptime.split()[0]) - start / ticks)) + except (AttributeError, IndexError, ValueError): + return None + + +def _one_line(text: str) -> str: + # The check prints one line for each command: a line break in an argument or a path would split the line, + # and a control character would act on the terminal. + return "".join(character if character.isprintable() else "?" for character in " ".join(text.split())) + + +def _held_command(pid: int, proc_root: str) -> Optional[str]: + text = _read_text(os.path.join(proc_root, str(pid), "cmdline")) + if not text: + return None + arguments = text.rstrip("\0").split("\0") + if "--inside-cap" in arguments: + at = arguments.index("--inside-cap") + if arguments[at + 3:at + 4] == ["--"]: + arguments = arguments[at + 4:] + return _one_line(" ".join(arguments))[:HELD_COMMAND_CHARACTERS] + + +def held_commands(parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None) -> List[str]: + """Returns one text for each running bounded command whose scope is in parent, as the fields of a check line. + + A field that cannot be read is '-'. Probe scopes and the scopes named in skip give no text. + """ + if ticks is None: + ticks = os.sysconf("SC_CLK_TCK") + + def mib(text: Optional[str]) -> str: + return "%dM" % (int(text) // (1024 * 1024)) if text is not None and text.strip().isdigit() else "-" + + held = [] + for name in _bounded_scopes(parent, skip): + directory = os.path.join(parent, name) + limit = _read_text(os.path.join(directory, "memory.max")) + current = _read_text(os.path.join(directory, "memory.current")) + pids = [int(line) for line in (_read_text(os.path.join(directory, "cgroup.procs")) or "").split() if line.isdigit()] + if not os.path.isdir(directory): + # The scope ended while it was read. + continue + # The wrapper starts the first process of the scope, and that process starts the command. + pid = min(pids) if pids else None + age = _process_age_seconds(pid, proc_root, ticks) if pid is not None else None + try: + working = os.readlink(os.path.join(proc_root, str(pid), "cwd")) if pid is not None else None + except OSError: + working = None + if working is not None: + working = _one_line(working) + command = _held_command(pid, proc_root) if pid is not None else None + held.append("unit=%s budget=%s used=%s age=%s dir=%s command=%s" % ( + name[:-len(".scope")], mib(limit), mib(current), "-" if age is None else "%ds" % age, + working or "-", command or "-")) + return held + + def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]: try: with open(os.path.join(proc_root, str(pid), "cgroup")) as handle: @@ -959,14 +1062,45 @@ def __init__(self) -> None: self.rows: List[int] = [] self.label: Optional[str] = None self.command: List[str] = [] + self.check = False + self.budgets: List[int] = [] + + +def _check_option_given(flags: Sequence[str]) -> bool: + position = 0 + while position < len(flags): + if flags[position] == "--check": + return True + position += 2 if flags[position] in VALUE_OPTIONS else 1 + return False + + +def _parse_check(flags: Sequence[str], has_command: bool) -> Options: + options = Options() + options.check = True + if has_command: + raise WrapperError("--check runs no command; remove the '--' and the command\n" + USAGE) + remaining = list(flags) + while remaining: + flag = remaining.pop(0) + if flag == "--check": + continue + if flag != "--memory": + raise WrapperError("--check takes only --memory, not '%s'\n%s" % (flag, USAGE)) + if not remaining: + raise WrapperError("the option '--memory' needs a value\n" + USAGE) + options.budgets.append(parse_size_mib(remaining.pop(0))) + return options def parse_arguments(argv: Sequence[str]) -> Options: options = Options() arguments = list(argv) + split = arguments.index("--") if "--" in arguments else len(arguments) + if _check_option_given(arguments[:split]): + return _parse_check(arguments[:split], split < len(arguments)) if "--" not in arguments: raise WrapperError("the '--' before the command is missing\n" + USAGE) - split = arguments.index("--") options.command = arguments[split + 1:] if not options.command: raise WrapperError("the command is missing\n" + USAGE) @@ -976,7 +1110,7 @@ def parse_arguments(argv: Sequence[str]) -> Options: if flag == "--measure": options.measure = True continue - if flag not in ("--memory", "--cpus", "--exclusive", "--measure-rows", "--label"): + if flag not in VALUE_OPTIONS: raise WrapperError("cannot read the option '%s'\n%s" % (flag, USAGE)) if not flags: raise WrapperError("the option '%s' needs a value\n%s" % (flag, USAGE)) @@ -1188,6 +1322,61 @@ def on_start(pid: int) -> None: return code, suggested +def check( + budgets: Sequence[int], environ: Mapping[str, str], + read_available: Callable[[], Optional[int]] = available_memory_mib, + read_outstanding: Optional[Callable[[], Optional[int]]] = None, +) -> int: + """Prints the state of the queue and, for each budget in MiB, whether a run of that budget would start now. + + Takes no reservation and holds no lock when it returns. read_outstanding gives the unused budgets of the + running commands, or None where they cannot be counted; by default the check finds them as a run does. + """ + settings = Settings(environ) + count = slot_count(settings.total_mib, settings.slot_mib, settings.reserve_mib) + most = queue_mib(settings.total_mib, settings.slot_mib, settings.reserve_mib) + uid = os.getuid() + directory = lock_directory(environ, uid) + ensure_lock_directory(directory, uid) + unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) + # The probe can take seconds, so the state of the queue is read after it. + choice = None if settings.no_cap else choose_cap_prefix(settings.slot_mib, None, unit, probe_cap) + # A waiter tries for slots only while it holds the turn lock, so a count under that lock never makes a free slot look held to it. + free_slots = _free_slots(directory, count, wait=False) + line = _try_lock(os.path.join(directory, "line.lock")) + if line is not None: + os.close(line) + scopes = scope_parent_directory(choice[1]) if choice is not None else None + if read_outstanding is None: + # A wrapper that starts on its own counts every bounded scope, also the one that this check runs in. + def read_outstanding() -> Optional[int]: + return None if scopes is None else unused_budget_mib(scopes, ()) + + if settings.free_mib is None: + before = read_outstanding() + available = read_available() + after = read_outstanding() + outstanding = None if before is None or after is None else max(before, after) + else: + available, outstanding = settings.free_mib, None + + def mib(value: Optional[int]) -> str: + return "-" if value is None else "%dM" % value + + log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s line=%s" % ( + count, settings.slot_mib, "-" if free_slots is None else free_slots, mib(available), mib(outstanding), + "free" if line is not None else "busy")) + for held in held_commands(scopes, ()) if scopes is not None else []: + log("check held " + held) + for budget in budgets: + needed = slots_needed(budget, settings.slot_mib, count) + headroom = headroom_mib(settings.total_mib, min(budget, most), most) + starts = (line is not None and free_slots is not None and free_slots >= needed + and memory_fits(min(budget, most), available, outstanding, headroom)) + log("check budget=%dM slots=%d headroom=%dM starts=%s" % (budget, needed, headroom, "yes" if starts else "no")) + return 0 + + def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int: arguments = list(sys.argv[1:] if argv is None else argv) variables = os.environ if environ is None else environ @@ -1195,6 +1384,8 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st if len(arguments) > 4 and arguments[0] == "--inside-cap" and arguments[3] == "--": return inside_cap(arguments[1], arguments[2], arguments[4:]) options = parse_arguments(arguments) + if options.check: + return check(options.budgets, variables) if variables.get(ACTIVE_VARIABLE): log("nested call; running the command directly") try: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index f6ec6bc..7e9b38d 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1055,6 +1055,102 @@ def sleep(seconds): self.assertEqual(sleeps, [5.0]) +class HeldCommandTest(unittest.TestCase): + """Gives held_commands a slice of the cgroup filesystem and a process filesystem in temporary directories.""" + + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.slice = os.path.join(self.base.name, "app.slice") + self.proc = os.path.join(self.base.name, "proc") + os.makedirs(self.slice) + os.makedirs(self.proc) + Path(self.proc, "uptime").write_text("170.52 300.00\n") + + def scope(self, name, limit=str(4096 * 1024 ** 2), current=str(1024 * 1024 ** 2), pids=("100",)): + directory = os.path.join(self.slice, name) + os.makedirs(directory) + Path(directory, "memory.max").write_text(limit + "\n") + Path(directory, "memory.current").write_text(current + "\n") + Path(directory, "cgroup.procs").write_text("".join(pid + "\n" for pid in pids)) + + def process(self, pid, arguments, start_ticks=5000, cwd="/work/project"): + directory = os.path.join(self.proc, str(pid)) + os.makedirs(directory) + Path(directory, "stat").write_text("%d (python 3) S %s %d 0 0\n" % (pid, " ".join(["0"] * 18), start_ticks)) + Path(directory, "cmdline").write_bytes(b"".join(argument.encode() + b"\0" for argument in arguments)) + os.symlink(cwd, os.path.join(directory, "cwd")) + + def held(self, skip=()): + return bounded_run.held_commands(self.slice, skip, proc_root=self.proc, ticks=100) + + def inside(self, *command): + return ["python3", "/x/bounded_run.py", "--inside-cap", "/l/peak-u", "bounded-run-100-aaaaaa", "--"] + list(command) + + def test_names_the_budget_the_use_the_age_the_directory_and_the_command(self): + self.scope("bounded-run-100-aaaaaa.scope", pids=("105", "100")) + self.process(100, self.inside("sh", "-c", "make test")) + self.process(105, ["make", "test"], start_ticks=9000, cwd="/elsewhere") + self.assertEqual(self.held(), [ + "unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=120s dir=/work/project command=sh -c make test", + ]) + + def test_a_scope_with_no_budget_gives_a_dash(self): + self.scope("bounded-run-100-aaaaaa.scope", limit="max") + self.process(100, self.inside("tool")) + self.assertIn(" budget=- ", self.held()[0]) + + def test_skips_probe_scopes_named_scopes_and_other_units(self): + self.scope("bounded-run-100-aaaaaa-probe.scope") + self.scope("bounded-run-101-bbbbbb.scope") + self.scope("editor-1.scope") + self.scope("bounded-run-102-cccccc.scope") + self.process(100, self.inside("tool")) + held = self.held(skip=["bounded-run-101-bbbbbb.scope"]) + self.assertEqual([line.split()[0] for line in held], ["unit=bounded-run-102-cccccc"]) + + def test_a_process_that_cannot_be_read_gives_dashes(self): + self.scope("bounded-run-100-aaaaaa.scope", pids=("999",)) + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=- dir=- command=-"]) + + def test_a_scope_with_no_process_gives_dashes(self): + self.scope("bounded-run-100-aaaaaa.scope", pids=()) + self.assertTrue(self.held()[0].endswith(" age=- dir=- command=-"), self.held()) + + def test_a_scope_that_ends_while_it_is_read_is_skipped(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, self.inside("tool")) + listing = os.listdir(self.slice) + ["bounded-run-200-dddddd.scope"] + with mock.patch.object(bounded_run.os, "listdir", return_value=listing): + held = self.held() + self.assertEqual([line.split()[0] for line in held], ["unit=bounded-run-100-aaaaaa"]) + + def test_a_long_command_is_cut_and_stays_on_one_line(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, self.inside("sh", "-c", "first\nsecond " + "x" * 300)) + command = self.held()[0].split(" command=", 1)[1] + self.assertEqual(len(command), bounded_run.HELD_COMMAND_CHARACTERS) + self.assertTrue(command.startswith("sh -c first second x"), command) + + def test_a_directory_with_a_line_break_stays_on_one_line(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, self.inside("tool"), cwd="/work/two\nlines") + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=120s dir=/work/two lines command=tool"]) + + def test_control_characters_of_the_command_and_the_directory_become_question_marks(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, self.inside("printf", "\x1b[2Jdone"), cwd="/work/\x1b[31mred") + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M age=120s dir=/work/?[31mred command=printf ?[2Jdone"]) + + def test_a_command_without_the_prefix_of_the_wrapper_is_given_whole(self): + self.scope("bounded-run-100-aaaaaa.scope") + self.process(100, ["sleep", "60"]) + self.assertTrue(self.held()[0].endswith(" command=sleep 60"), self.held()) + + def test_no_slice_gives_no_line(self): + self.assertEqual(bounded_run.held_commands(os.path.join(self.base.name, "gone"), (), proc_root=self.proc), []) + + class CapTest(unittest.TestCase): def test_prefix_holds_the_limits(self): self.assertEqual(bounded_run.cap_prefix(6144, 4, "unit-1"), [ @@ -1864,6 +1960,250 @@ def once(options, environ): self.assertEqual(calls, [8, 4]) +class CheckTest(unittest.TestCase): + """Calls check() in this process with four slots of 2 GiB, a headroom of 1024 MiB, and no hard cap. + + The test holds lock files of the queue itself, as a running command and a waiter hold them. + """ + + def setUp(self): + self.lines = [] + patcher = mock.patch.object(bounded_run, "log", side_effect=self.lines.append) + patcher.start() + self.addCleanup(patcher.stop) + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.directory = os.path.join(self.base.name, "locks") + os.mkdir(self.directory, 0o700) + self.environ = dict(os.environ) + self.environ.pop("BOUNDED_RUN_ACTIVE", None) + self.environ.update({ + "BOUNDED_RUN_LOCK_DIR": self.directory, + "BOUNDED_RUN_TOTAL_MIB": "8192", + "BOUNDED_RUN_RESERVE_MIB": "0", + "BOUNDED_RUN_SLOT_MIB": "2048", + "BOUNDED_RUN_NO_CAP": "1", + }) + + def hold(self, name): + descriptor = bounded_run._try_lock(os.path.join(self.directory, name)) + self.assertIsNotNone(descriptor) + self.addCleanup(os.close, descriptor) + return descriptor + + def check(self, budgets=(), available=16384, outstanding=None): + options = bounded_run.parse_arguments(["--check"] + [part for budget in budgets for part in ("--memory", budget)]) + code = bounded_run.check(options.budgets, self.environ, read_available=lambda: available, read_outstanding=lambda: outstanding) + self.assertEqual(code, 0) + return self.lines + + def test_reports_the_slots_the_memory_and_the_line(self): + self.assertEqual(self.check(), [ + "check slots=4 slot=2048M free-slots=4 free=16384M unused=- line=free", + ]) + + def test_a_budget_of_the_whole_queue_starts_when_the_memory_of_the_queue_is_free(self): + self.assertEqual(self.check(["8G"], available=8192)[-1], "check budget=8192M slots=4 headroom=0M starts=yes") + + def test_the_free_memory_for_the_tests_replaces_the_measured_one(self): + self.environ["BOUNDED_RUN_FREE_MIB"] = "4096" + lines = self.check(["2G"], available=0, outstanding=65536) + self.assertIn(" free=4096M unused=- ", lines[0]) + self.assertEqual(lines[-1], "check budget=2048M slots=1 headroom=1024M starts=yes") + + def test_counts_the_slots_that_running_commands_hold(self): + self.hold("slot-000.lock") + self.hold("slot-002.lock") + self.assertIn(" free-slots=2 ", self.check()[0]) + + def test_a_command_can_take_every_free_slot_after_the_check(self): + self.hold("slot-001.lock") + self.check(["2G"]) + reservation = bounded_run.try_reserve(self.directory, 4, 3, []) + self.assertIsNotNone(reservation, "the check still holds a slot") + reservation.release() + line = bounded_run._try_lock(os.path.join(self.directory, "line.lock")) + self.assertIsNotNone(line, "the check still holds the line") + os.close(line) + + def test_a_waiter_in_the_line_makes_the_line_busy_and_no_budget_starts(self): + self.hold("line.lock") + lines = self.check(["2G"]) + self.assertTrue(lines[0].endswith(" line=busy"), lines) + self.assertEqual(lines[1], "check budget=2048M slots=1 headroom=1024M starts=no") + + def test_a_count_of_slots_that_another_command_takes_at_that_moment_is_not_given(self): + self.hold("reserve.lock") + lines = self.check(["2G"]) + self.assertIn(" free-slots=- ", lines[0]) + self.assertEqual(lines[1], "check budget=2048M slots=1 headroom=1024M starts=no") + + def test_each_budget_gets_its_slots_and_its_answer_in_the_order_given(self): + self.hold("slot-000.lock") + self.hold("slot-001.lock") + lines = self.check(["2G", "4096M", "5G"]) + self.assertEqual(lines[1:], [ + "check budget=2048M slots=1 headroom=1024M starts=yes", + "check budget=4096M slots=2 headroom=1024M starts=yes", + "check budget=5120M slots=3 headroom=1024M starts=no", + ]) + + def test_a_budget_starts_only_when_the_free_memory_less_the_unused_budgets_and_the_headroom_holds_it(self): + lines = self.check(["2G", "4G"], available=6000, outstanding=900) + self.assertEqual(lines[0], "check slots=4 slot=2048M free-slots=4 free=6000M unused=900M line=free") + self.assertEqual(lines[1:], ["check budget=2048M slots=1 headroom=1024M starts=yes", "check budget=4096M slots=2 headroom=1024M starts=no"]) + + def test_a_budget_starts_when_the_free_memory_cannot_be_read_as_the_wait_does(self): + lines = self.check(["2G"], available=None) + self.assertIn(" free=- ", lines[0]) + self.assertEqual(lines[1], "check budget=2048M slots=1 headroom=1024M starts=yes") + + def test_a_budget_larger_than_the_queue_needs_every_slot_and_the_memory_of_the_queue(self): + lines = self.check(["64G"], available=9300) + self.assertEqual(lines[1], "check budget=65536M slots=4 headroom=0M starts=yes") + + def test_counts_the_larger_of_the_unused_budgets_read_before_and_after_the_free_memory(self): + unused = [100, 900] + options = bounded_run.parse_arguments(["--check"]) + bounded_run.check(options.budgets, self.environ, read_available=lambda: 6000, read_outstanding=lambda: unused.pop(0)) + self.assertIn(" unused=900M ", self.lines[0]) + + def test_counts_the_unused_budgets_beside_the_scope_of_the_probe(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + calls = [] + + def unused(parent, skip): + calls.append(parent) + return 700 + + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ + mock.patch.object(bounded_run, "unused_budget_mib", unused), \ + mock.patch.object(bounded_run, "held_commands", return_value=[]): + self.assertEqual(bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000), 0) + self.assertEqual(set(calls), {"/sys/fs/cgroup/user.slice/app.slice"}) + self.assertIn(" unused=700M ", self.lines[0]) + + def test_names_each_held_command_after_the_state_line(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + calls = [] + + def held(parent, skip): + calls.append(parent) + return ["unit=bounded-run-7-abcdef budget=4096M used=100M age=5s dir=/w command=tool"] + + options = bounded_run.parse_arguments(["--check", "--memory", "2G"]) + with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ + mock.patch.object(bounded_run, "unused_budget_mib", return_value=0), \ + mock.patch.object(bounded_run, "held_commands", held): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + self.assertEqual(calls, ["/sys/fs/cgroup/user.slice/app.slice"]) + self.assertEqual(self.lines[1], "check held unit=bounded-run-7-abcdef budget=4096M used=100M age=5s dir=/w command=tool") + self.assertTrue(self.lines[2].startswith("check budget=2048M "), self.lines) + + def test_a_check_inside_a_bounded_command_counts_its_unused_budget_too(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + skips = [] + + def unused(parent, skip): + skips.append(list(skip)) + return 0 + + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ + mock.patch.object(bounded_run, "own_scope_name", return_value="bounded-run-2-111111.scope"), \ + mock.patch.object(bounded_run, "unused_budget_mib", unused), \ + mock.patch.object(bounded_run, "held_commands", return_value=[]): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + self.assertEqual(skips, [[], []]) + + def test_a_check_inside_a_bounded_command_names_that_command_too(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + skips = [] + + def held(parent, skip): + skips.append(list(skip)) + return [] + + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap", return_value=output), \ + mock.patch.object(bounded_run, "own_scope_name", return_value="bounded-run-2-111111.scope"), \ + mock.patch.object(bounded_run, "unused_budget_mib", return_value=0), \ + mock.patch.object(bounded_run, "held_commands", held): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + self.assertEqual(skips, [[]]) + + def test_the_slots_and_the_line_are_read_after_the_cap_probe(self): + self.environ.pop("BOUNDED_RUN_NO_CAP") + events = [] + real_free_slots = bounded_run._free_slots + + def probe(prefix): + events.append("probe") + return None + + def free_slots(*arguments, **keywords): + events.append("slots") + return real_free_slots(*arguments, **keywords) + + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap", probe), mock.patch.object(bounded_run, "_free_slots", free_slots): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + self.assertEqual(events[-1], "slots") + self.assertIn("probe", events) + + def test_no_held_line_without_a_cap(self): + self.hold("slot-000.lock") + self.assertFalse(any(line.startswith("check held") for line in self.check(["2G"]))) + + def test_counts_no_unused_budget_without_a_cap(self): + options = bounded_run.parse_arguments(["--check"]) + with mock.patch.object(bounded_run, "probe_cap") as probe: + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + probe.assert_not_called() + self.assertIn(" unused=- ", self.lines[0]) + + +class CheckArgumentTest(unittest.TestCase): + def test_reads_each_budget_in_order(self): + options = bounded_run.parse_arguments(["--check", "--memory", "6G", "--memory", "512M"]) + self.assertEqual((options.check, options.budgets), (True, [6144, 512])) + + def test_the_check_option_can_come_after_a_budget(self): + self.assertEqual(bounded_run.parse_arguments(["--memory", "2G", "--check"]).budgets, [2048]) + + def test_needs_no_budget(self): + self.assertEqual(bounded_run.parse_arguments(["--check"]).budgets, []) + + def test_a_command_after_the_check_option_is_a_command_of_a_run(self): + options = bounded_run.parse_arguments(["--memory", "2G", "--", "tool", "--check"]) + self.assertEqual((options.check, options.command), (False, ["tool", "--check"])) + + def test_the_value_of_an_option_is_not_the_check_option(self): + options = bounded_run.parse_arguments(["--exclusive", "--check", "--", "tool"]) + self.assertEqual((options.check, options.exclusive, options.command), (False, ["--check"], ["tool"])) + + def test_rejects_a_command_and_the_other_options(self): + for arguments in ( + ["--check", "--", "tool"], + ["--check", "--memory", "2G", "--", "tool"], + ["--check", "--cpus", "2"], + ["--check", "--exclusive", "port"], + ["--check", "--measure"], + ["--check", "--measure-rows", "4,2"], + ["--check", "--label", "lint"], + ["--check", "--memory"], + ["--check", "--memory", "six"], + ): + with self.subTest(arguments=arguments): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.parse_arguments(arguments) + + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" @@ -2471,6 +2811,36 @@ def test_a_first_measurement_starts_while_small_commands_keep_arriving(self): ) +class CheckProcessTest(WrapperProcessCase): + def check(self, arguments): + process = subprocess.Popen( + [sys.executable, WRAPPER, "--check"] + arguments, env=self.environ, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + self.processes.append(process) + output, errors = process.communicate(timeout=60) + return process.returncode, output, errors + + def test_prints_the_check_lines_on_the_error_stream_and_exits_0(self): + holder = self.worker("holder", "2G", hold="300") + self.wait_for_event("start", "holder") + code, output, errors = self.check(["--memory", "2G", "--memory", "4G"]) + self.assertEqual((code, output), (0, ""), errors) + self.assertRegex(errors, r"^bounded-run: check slots=2 slot=2048M free-slots=1 free=(\d+M|-) unused=- line=free\n") + self.assertRegex(errors, r"\nbounded-run: check budget=2048M slots=1 headroom=1024M starts=(yes|no)\nbounded-run: check budget=4096M slots=2 headroom=0M starts=no\n$") + holder.kill() + + def test_a_command_starts_at_once_after_the_check(self): + self.assertEqual(self.check([])[0], 0) + self.assertEqual(self.worker("after", "4G", hold="0").wait(timeout=60), 0) + + def test_a_fault_of_the_call_gives_125(self): + code, output, errors = self.check(["--cpus", "2"]) + self.assertEqual(code, 125) + self.assertTrue(errors.startswith("bounded-run: "), errors) + self.assertNotIn("check slots=", errors) + + @unittest.skipUnless( bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None, "no hard cap on this machine",