diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 2542554..5448ded 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -41,7 +41,7 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | Option | Meaning | | --- | --- | | `--memory ` | Memory the command may use, such as `6G` or `4096M`. Taken from the record. Without it the wrapper uses its default budget, a quarter of the machine's memory. A measurement without it takes the whole queue where there is no hard cap. | -| `--cpus ` | Processor limit, as a whole number. Taken from the record. | +| `--cpus ` | Processor limit, as a whole number. Taken from the record. Without it the wrapper uses half the machine's processors, rounded down, and at least 1. | | `--exclusive ` | A resource that only one command may hold at a time, such as a fixed port. You choose the name. The wrapper keeps the names of each repository apart, and all worktrees of one repository share them. Repeat the option for each resource. | | `--measure` | Also print a suggested budget. Discovery uses it. With no `--memory`, the command runs with the default budget where the hard cap is available, and alone in the queue where it is not. | | `--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 with the default budget where the hard cap is available, and alone in the queue where it is not. 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. A stop signal to the wrapper then ends the wrapper by that signal. So a Ctrl-C, which reaches the shell too, stops a line of joined calls; a signal sent to the wrapper alone does not stop the shell's line. Otherwise the exit code is the first exit code of a row that is not 0. | @@ -59,12 +59,12 @@ bounded-run: row label= cpus= budget=M peak=M held=M|- exact=< 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 slots= slot=M free-slots= free=M unused=M cpus= cpus-used= line= +bounded-run: check held unit= budget=M used=M cpus= 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 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, the processors of the machine, and the processors that the running bounded commands can use together (`cpus-used`). `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, the processors it can use, how long it has run, its working directory, and its command. The held lines and `cpus-used` need the hard cap, so without it there are no held lines and `cpus-used` is `-`. 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). @@ -93,7 +93,7 @@ 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. +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`). A row whose `--cpus`, added to `cpus-used`, is more than `cpus` makes every running command slower, so when two rows would both start, prefer the largest one that fits in `cpus`. 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. @@ -185,7 +185,7 @@ 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 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." +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` whose `--cpus`, added to `cpus-used`, fits in `cpus`. When no such row fits, use the largest row with `starts=yes`, and when no row has it, use the default row. 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. diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 7e7e275..7d27d3b 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -13,6 +13,10 @@ not stop the shell. A caller that reads the exit status reads 128 plus the signal. +A run without --cpus gets half of the processors of the machine, rounded +down and at least 1. The command reads its processors in BOUNDED_RUN_CPUS, +and the hard cap, where it is available, holds the command to them. + A measurement prints one row line on the error stream, in a fixed form: bounded-run: row label=NAME cpus=N budget=M peak=M held=M|- exact=yes|no exit=CODE @@ -32,12 +36,15 @@ 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 slots=N slot=M free-slots=N|- free=M|- unused=M|- cpus=N cpus-used=N|- line=free|busy + bounded-run: check held unit=NAME budget=M|- used=M|- cpus=N|- 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 '-' stands for a value that the check cannot read or count here. cpus is +the processors of the machine. cpus-used is the sum of the processors that +the running bounded commands may use, and the cpus of a held line is the +part of one command. 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 @@ -659,6 +666,15 @@ def wait_for_memory( sleep(poll_seconds) +def machine_cpus() -> int: + return os.cpu_count() or 1 + + +def default_cpus(machine: int) -> int: + """Returns the processors of a run that gives no --cpus: half of the machine's, rounded down, and at least 1.""" + return max(1, machine // 2) + + def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool = True) -> List[str]: prefix = [ "systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", unit, @@ -759,6 +775,40 @@ def unused_budget_mib(parent: str, skip: Sequence[str]) -> int: return unused // (1024 * 1024) +def _scope_cpus(directory: str, machine: int) -> Optional[int]: + """Returns the processors that the quota of the scope in directory allows, rounded up, or None when it cannot be read. + + A scope with no quota can use each processor of the machine. + """ + try: + quota, period = (_read_text(os.path.join(directory, "cpu.max")) or "").split() + if quota == "max": + return machine + return -(-int(quota) // int(period)) if int(period) > 0 else None + except ValueError: + return None + + +def cpus_in_use(parent: str, skip: Sequence[str], machine: Optional[int] = None) -> Optional[int]: + """Returns the sum of the processors that the quotas of the bounded commands whose scopes are in parent allow. + + Probe scopes and the scopes named in skip add nothing. Returns None when the quota of a running scope cannot be read. + """ + if machine is None: + machine = machine_cpus() + used = 0 + for name in _bounded_scopes(parent, skip): + directory = os.path.join(parent, name) + cpus = _scope_cpus(directory, machine) + if not os.path.isdir(directory): + # The scope ended while it was read. + continue + if cpus is None: + return None + used += cpus + return used + + def _scope_counts(path: str) -> bool: try: with open(os.path.join(path, "memory.max")) as handle: @@ -823,13 +873,17 @@ def _held_command(pid: int, proc_root: str) -> Optional[str]: 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]: +def held_commands( + parent: str, skip: Sequence[str], proc_root: str = "/proc", ticks: Optional[int] = None, machine: 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") + if machine is None: + machine = machine_cpus() def mib(text: Optional[str]) -> str: return "%dM" % (int(text) // (1024 * 1024)) if text is not None and text.strip().isdigit() else "-" @@ -839,6 +893,7 @@ def mib(text: Optional[str]) -> str: directory = os.path.join(parent, name) limit = _read_text(os.path.join(directory, "memory.max")) current = _read_text(os.path.join(directory, "memory.current")) + cpus = _scope_cpus(directory, machine) 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. @@ -853,8 +908,8 @@ def mib(text: Optional[str]) -> str: 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, + held.append("unit=%s budget=%s used=%s cpus=%s age=%s dir=%s command=%s" % ( + name[:-len(".scope")], mib(limit), mib(current), "-" if cpus is None else cpus, "-" if age is None else "%ds" % age, working or "-", command or "-")) return held @@ -1326,7 +1381,8 @@ def bounded_once(options: Options, environ: Mapping[str, str]) -> Tuple[int, int exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive] unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) - choice = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, probe_cap) + cpus = options.cpus if options.cpus is not None else default_cpus(machine_cpus()) + choice = None if settings.no_cap else choose_cap_prefix(budget, cpus, unit, probe_cap) prefix = choice[0] if choice is not None else None capped = prefix is not None if options.measure and options.memory is None and not capped: @@ -1355,7 +1411,7 @@ def read_outstanding() -> Optional[int]: child_environ: Dict[str, str] = dict(environ) child_environ[ACTIVE_VARIABLE] = "1" child_environ["BOUNDED_RUN_MEMORY_MIB"] = str(budget) - child_environ["BOUNDED_RUN_CPUS"] = str(options.cpus if options.cpus is not None else (os.cpu_count() or 1)) + child_environ["BOUNDED_RUN_CPUS"] = str(cpus) trackers: List[PeakTracker] = [] @@ -1469,12 +1525,15 @@ def read_outstanding() -> Optional[int]: else: available, outstanding = settings.free_mib, None + machine = machine_cpus() + used = None if scopes is None else cpus_in_use(scopes, ()) + 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" % ( + log("check slots=%d slot=%dM free-slots=%s free=%s unused=%s cpus=%d cpus-used=%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")) + machine, "-" if used is None else used, "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: 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 6b0d6e5..5ca8be3 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1067,9 +1067,11 @@ def setUp(self): 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",)): + def scope(self, name, limit=str(4096 * 1024 ** 2), current=str(1024 * 1024 ** 2), pids=("100",), cpu_max="400000 100000"): directory = os.path.join(self.slice, name) os.makedirs(directory) + if cpu_max is not None: + Path(directory, "cpu.max").write_text(cpu_max + "\n") 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)) @@ -1082,7 +1084,7 @@ def process(self, pid, arguments, start_ticks=5000, cwd="/work/project"): 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) + return bounded_run.held_commands(self.slice, skip, proc_root=self.proc, ticks=100, machine=16) def inside(self, *command): return ["python3", "/x/bounded_run.py", "--inside-cap", "/l/peak-u", "bounded-run-100-aaaaaa", "--"] + list(command) @@ -1092,7 +1094,7 @@ def test_names_the_budget_the_use_the_age_the_directory_and_the_command(self): 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", + "unit=bounded-run-100-aaaaaa budget=4096M used=1024M cpus=4 age=120s dir=/work/project command=sh -c make test", ]) def test_a_scope_with_no_budget_gives_a_dash(self): @@ -1111,7 +1113,7 @@ def test_skips_probe_scopes_named_scopes_and_other_units(self): 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=-"]) + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M cpus=4 age=- dir=- command=-"]) def test_a_scope_with_no_process_gives_dashes(self): self.scope("bounded-run-100-aaaaaa.scope", pids=()) @@ -1135,12 +1137,12 @@ def test_a_long_command_is_cut_and_stays_on_one_line(self): 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"]) + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M cpus=4 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"]) + self.assertEqual(self.held(), ["unit=bounded-run-100-aaaaaa budget=4096M used=1024M cpus=4 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") @@ -1150,6 +1152,71 @@ def test_a_command_without_the_prefix_of_the_wrapper_is_given_whole(self): 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), []) + def test_a_part_of_a_processor_counts_as_a_whole_one(self): + self.scope("bounded-run-100-aaaaaa.scope", cpu_max="150000 100000") + self.process(100, self.inside("tool")) + self.assertIn(" cpus=2 ", self.held()[0]) + + def test_a_scope_with_no_quota_holds_every_processor(self): + self.scope("bounded-run-100-aaaaaa.scope", cpu_max="max 100000") + self.process(100, self.inside("tool")) + self.assertIn(" cpus=16 ", self.held()[0]) + + def test_a_quota_that_cannot_be_read_gives_a_dash(self): + self.scope("bounded-run-100-aaaaaa.scope", cpu_max=None) + self.process(100, self.inside("tool")) + self.assertIn(" cpus=- ", self.held()[0]) + + +class CpusInUseTest(unittest.TestCase): + """Gives cpus_in_use a slice of the cgroup filesystem in a temporary directory, on a machine of 16 processors.""" + + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.slice = os.path.join(self.base.name, "app.slice") + os.makedirs(self.slice) + + def scope(self, name, cpu_max): + directory = os.path.join(self.slice, name) + os.makedirs(directory) + if cpu_max is not None: + Path(directory, "cpu.max").write_text(cpu_max + "\n") + + def used(self, skip=()): + return bounded_run.cpus_in_use(self.slice, skip, machine=16) + + def test_adds_the_quotas_of_the_bounded_scopes_each_rounded_up(self): + self.scope("bounded-run-1-aaaaaa.scope", "800000 100000") + self.scope("bounded-run-2-bbbbbb.scope", "150000 100000") + self.assertEqual(self.used(), 10) + + def test_a_scope_with_no_quota_counts_every_processor(self): + self.scope("bounded-run-1-aaaaaa.scope", "max 100000") + self.scope("bounded-run-2-bbbbbb.scope", "200000 100000") + self.assertEqual(self.used(), 18) + + def test_skips_probe_scopes_named_scopes_and_other_units(self): + self.scope("bounded-run-1-aaaaaa-probe.scope", "800000 100000") + self.scope("bounded-run-2-bbbbbb.scope", "800000 100000") + self.scope("editor-1.scope", "800000 100000") + self.scope("bounded-run-3-cccccc.scope", "300000 100000") + self.assertEqual(self.used(skip=["bounded-run-2-bbbbbb.scope"]), 3) + + def test_no_running_scope_uses_no_processor(self): + self.assertEqual(self.used(), 0) + + def test_a_scope_that_ends_while_it_is_read_is_skipped(self): + self.scope("bounded-run-1-aaaaaa.scope", "200000 100000") + listing = os.listdir(self.slice) + ["bounded-run-9-dddddd.scope"] + with mock.patch.object(bounded_run.os, "listdir", return_value=listing): + self.assertEqual(self.used(), 2) + + def test_a_running_scope_whose_quota_cannot_be_read_makes_the_sum_unknown(self): + self.scope("bounded-run-1-aaaaaa.scope", "200000 100000") + self.scope("bounded-run-2-bbbbbb.scope", None) + self.assertIsNone(self.used()) + class CapTest(unittest.TestCase): def test_prefix_holds_the_limits(self): @@ -1750,6 +1817,29 @@ def fake_run_command(command, environ, on_start=None): self.assertEqual(waits, [4096]) self.assertIn("MemoryMax=4096M", commands[0]) + def capped_command(self, cpus): + commands = [] + + def fake_run_command(command, environ, on_start=None): + commands.append(list(command)) + return 0, 0 + + options = bounded_run.Options() + options.memory = "1G" + options.cpus = cpus + options.command = [sys.executable, "-c", "pass"] + with mock.patch.object(bounded_run, "probe_cap", return_value=""), \ + mock.patch.object(bounded_run, "machine_cpus", return_value=16), \ + mock.patch.object(bounded_run, "run_command", fake_run_command): + self.assertEqual(bounded_run.bounded(options, self.environ), 0) + return commands[0] + + def test_the_cap_of_a_run_without_cpus_holds_half_the_processors(self): + self.assertIn("CPUQuota=800%", self.capped_command(None)) + + def test_the_cap_of_a_run_with_cpus_holds_them(self): + self.assertIn("CPUQuota=300%", self.capped_command(3)) + def wait_arguments(self, probe_output, environ=None): waits = [] options = bounded_run.Options() @@ -1938,6 +2028,18 @@ def test_a_measurement_prints_one_row_line(self): self.assertEqual(self.run_bounded(["--measure", "--cpus", "4", "--label", "unit-tests"], [(0, 1000)]), 0) self.assertEqual(self.row_lines(), ["row label=unit-tests cpus=4 budget=1536M peak=1000M held=- exact=no exit=0"]) + def test_a_run_without_cpus_gets_half_the_processors_rounded_down_and_at_least_one(self): + for machine, expected in ((16, 8), (7, 3), (1, 1)): + self.runs = [] + with mock.patch.object(bounded_run, "machine_cpus", return_value=machine): + self.run_bounded(["--memory", "1G"], [(0, 100)]) + self.assertEqual(self.runs, [(expected, 1024)], machine) + + def test_a_run_with_cpus_gets_them_on_any_machine(self): + with mock.patch.object(bounded_run, "machine_cpus", return_value=16): + self.run_bounded(["--memory", "1G", "--cpus", "12"], [(0, 100)]) + self.assertEqual(self.runs, [(12, 1024)]) + def test_a_row_line_marks_the_options_that_were_not_given(self): self.run_bounded(["--measure"], [(3, 100)]) self.assertEqual(self.row_lines(), ["row label=- cpus=- budget=256M peak=100M held=- exact=no exit=3"]) @@ -2113,7 +2215,7 @@ def test_without_a_cap_the_largest_measured_row_takes_the_whole_queue(self): class CheckTest(unittest.TestCase): - """Calls check() in this process with four slots of 2 GiB, a headroom of 1024 MiB, and no hard cap. + """Calls check() in this process with four slots of 2 GiB, a headroom of 1024 MiB, 16 processors, and no hard cap. The test holds lock files of the queue itself, as a running command and a waiter hold them. """ @@ -2123,6 +2225,9 @@ def setUp(self): patcher = mock.patch.object(bounded_run, "log", side_effect=self.lines.append) patcher.start() self.addCleanup(patcher.stop) + patcher = mock.patch.object(bounded_run, "machine_cpus", return_value=16) + patcher.start() + self.addCleanup(patcher.stop) self.base = tempfile.TemporaryDirectory() self.addCleanup(self.base.cleanup) self.directory = os.path.join(self.base.name, "locks") @@ -2151,7 +2256,7 @@ def check(self, budgets=(), available=16384, outstanding=None): 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", + "check slots=4 slot=2048M free-slots=4 free=16384M unused=- cpus=16 cpus-used=- line=free", ]) def test_a_budget_of_the_whole_queue_starts_when_the_memory_of_the_queue_is_free(self): @@ -2202,7 +2307,7 @@ def test_each_budget_gets_its_slots_and_its_answer_in_the_order_given(self): 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[0], "check slots=4 slot=2048M free-slots=4 free=6000M unused=900M cpus=16 cpus-used=- 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): @@ -2237,6 +2342,32 @@ def unused(parent, skip): self.assertEqual(set(calls), {"/sys/fs/cgroup/user.slice/app.slice"}) self.assertIn(" unused=700M ", self.lines[0]) + def check_with_cap(self, cpus_in_use): + self.environ.pop("BOUNDED_RUN_NO_CAP") + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + 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, "cpus_in_use", cpus_in_use), \ + mock.patch.object(bounded_run, "held_commands", return_value=[]): + bounded_run.check(options.budgets, self.environ, read_available=lambda: 9000) + return self.lines + + def test_counts_the_processors_of_the_running_commands_beside_the_scope_of_the_probe(self): + calls = [] + + def cpus_in_use(parent, skip): + calls.append((parent, list(skip))) + return 12 + + lines = self.check_with_cap(cpus_in_use) + self.assertEqual(calls, [("/sys/fs/cgroup/user.slice/app.slice", [])]) + self.assertIn(" cpus=16 cpus-used=12 line=free", lines[0]) + self.assertEqual(lines[1], "check budget=2048M slots=1 headroom=1024M starts=yes") + + def test_processors_that_cannot_be_counted_give_a_dash(self): + self.assertIn(" cpus=16 cpus-used=- ", self.check_with_cap(lambda parent, skip: None)[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" @@ -2541,6 +2672,12 @@ def test_the_command_gets_the_budget_and_the_marker(self): output, errors = process.communicate(timeout=60) self.assertEqual(output, "1 2048 3\n") + def test_a_command_without_cpus_gets_half_the_processors_of_the_machine(self): + script = "import os; print(os.environ['BOUNDED_RUN_CPUS'])" + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual(output, "%d\n" % max(1, (os.cpu_count() or 1) // 2), errors) + def test_the_command_reads_the_input_of_the_wrapper(self): variables = dict(self.environ) process = subprocess.Popen( @@ -2978,7 +3115,7 @@ def test_prints_the_check_lines_on_the_error_stream_and_exits_0(self): 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"^bounded-run: check slots=2 slot=2048M free-slots=1 free=(\d+M|-) unused=- cpus=\d+ cpus-used=- 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()