diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index da8dd0b..e9ccd15 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -28,6 +28,8 @@ Skip for commands that only read (listing files, searching, version-control quer A command that does not end, such as a server or a watch mode, holds its memory in the queue until it stops. Start it through the wrapper, and stop it when your work with it is done. +A server that a heavy command talks to is a part of that command: a development server, a database, or a container that a test suite sends its requests to. The work of the suite grows the server, and the budget of the suite does not count a server outside it. When the test runner can start the server itself, let it: give the run a port that no running server uses, so that the server starts inside the bounded command and its budget covers it. When the server must run on its own, start it through the wrapper. Do not run a heavy command against a server that runs outside the queue, also when it already listens on the port: an agent or a person started it without the wrapper, and the queue cannot count it. Do not stop that server either, because it belongs to someone else. Use a port of your own. + ## The wrapper ``` @@ -41,11 +43,11 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--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 alone in the queue. | -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. Each line that the wrapper prints starts with `bounded-run:`. Its exit code 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 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:`. Its exit code 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. -On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. When a recorded command ends with exit code 137 and the wrapper reports a peak near the budget, the cap stopped it: the command grew. Measure it again with `--measure` and `--memory` at two times the budget, and correct the record. +On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. Without the cap, and on a system with cgroup version 1, the wait does not count the unused budgets of the running commands. When a recorded command ends with exit code 137 and the wrapper reports a peak near the budget, the cap stopped it: the command grew. Measure it again with `--measure` and `--memory` at two times the budget, and correct the record. ## The record @@ -158,6 +160,7 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "The port was in use, I'll back off once and retry" | Two commands wanted one resource. Record it as `--exclusive` and run through the wrapper. | | "My command timed out, the tests must hang" | It was waiting in the queue. Run it in the background with no short timeout. | | "The subagent will find the test command on its own" | It will find the plain one. Put the bounded command lines in its prompt. | +| "The server is already running on the port, the tests can reuse it" | The queue does not count a server that runs outside it, and the tests make it grow. Give the run a port of its own, so that the runner starts the server inside the bounded command. | | "Four subagents is too many for this machine, I'll dispatch two" | The queue limits the commands. Fewer subagents only makes the work slower. | | "Project memory is off, so there is no record to keep" | Discover in this session and keep the result in context. The rule does not depend on the memory. | | "The wrapper cannot run here, so none of this applies" | The fallback applies: one heavy command at a time, toolchain parallelism at half or less, and say so. | diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 85e7167..544546e 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -20,11 +20,12 @@ BOUNDED_RUN_SLOT_MIB size of one memory slot (default 2048) BOUNDED_RUN_RESERVE_MIB memory that the queue never gives out - BOUNDED_RUN_MEMORY_WAIT_SECONDS time limit of the wait for free memory (default 300) + BOUNDED_RUN_MEMORY_WAIT_SECONDS time between two lines of the wait for free memory (default 300) Values for the tests of this script, and for its maintainers: BOUNDED_RUN_TOTAL_MIB memory of the machine, in place of the measured value + BOUNDED_RUN_FREE_MIB free memory for the wait, in place of the measured free memory less the unused budgets BOUNDED_RUN_POLL_SECONDS time between two tries for the slots (default 2) BOUNDED_RUN_SAMPLE_SECONDS time between two memory samples (default 1) BOUNDED_RUN_LOCK_DIR directory of the lock files, as an absolute path @@ -57,9 +58,11 @@ ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE" SLOT_MIB = 2048 MINIMUM_RESERVE_MIB = 2048 +MINIMUM_HEADROOM_MIB = 1024 POLL_SECONDS = 2.0 MEMORY_WAIT_SECONDS = 300.0 SAMPLE_SECONDS = 1.0 +SCOPE_WAIT_SECONDS = 5.0 MARGIN_EXACT = 0.25 MARGIN_APPROXIMATE = 0.5 BUDGET_STEP_MIB = 256 @@ -187,6 +190,15 @@ def default_reserve_mib(total_mib: int) -> int: return max(MINIMUM_RESERVE_MIB, total_mib // 4) +def headroom_mib(total_mib: int, budget_mib: int, queue_mib: int) -> int: + """Returns the memory that the wait for free memory keeps free beside the budget for the programs outside the queue. + + The budget and the headroom together never need more than queue_mib, so a budget of the whole queue gets no headroom. + """ + # The reserve of the queue already keeps memory for the programs outside it. + return max(0, min(max(MINIMUM_HEADROOM_MIB, total_mib // 10), queue_mib - budget_mib)) + + def slot_count(total_mib: int, slot_mib: int, reserve_mib: int) -> int: return max(1, (total_mib - reserve_mib) // slot_mib) @@ -219,6 +231,8 @@ def __init__(self, environ: Mapping[str, str], read_total: Callable[[], int] = t self.memory_wait_seconds = _number(environ, "BOUNDED_RUN_MEMORY_WAIT_SECONDS", MEMORY_WAIT_SECONDS) self.sample_seconds = _number(environ, "BOUNDED_RUN_SAMPLE_SECONDS", SAMPLE_SECONDS) self.no_cap = bool(environ.get("BOUNDED_RUN_NO_CAP")) + free = environ.get("BOUNDED_RUN_FREE_MIB") + self.free_mib = int(_number(environ, "BOUNDED_RUN_FREE_MIB", 0)) if free else None if self.slot_mib <= 0: raise WrapperError("BOUNDED_RUN_SLOT_MIB must be more than zero") # A loop that sleeps for zero seconds never ends its wait and takes a full processor. @@ -454,25 +468,44 @@ def available_memory_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/c def wait_for_memory( - budget_mib: int, limit_seconds: float, poll_seconds: float, + budget_mib: int, interval_seconds: float, poll_seconds: float, headroom_mib: int = 0, read_available: Callable[[], Optional[int]] = available_memory_mib, + read_outstanding: Callable[[], Optional[int]] = lambda: None, sleep: Callable[[float], None] = time.sleep, -) -> bool: - waited = 0.0 + lock: Callable[[], None] = lambda: None, + unlock: Callable[[], None] = lambda: None, + clock: Callable[[], float] = time.monotonic, +) -> None: + """Returns when the free memory, less the unused budgets of running commands and the headroom, holds the budget. + + There is no time limit, so the call can block for as long as the machine is full. Returns at once when + the free memory cannot be read. read_outstanding gives None where the unused budgets cannot be counted. + The call returns with lock held: the caller calls unlock once the new command counts in read_outstanding. + """ + started = clock() + next_line: Optional[float] = None while True: + lock() + # A running command that grows or shrinks during the reads moves both values. The larger of the two unused + # counts around the free memory is the one that matches it or errs on the safe side. + before = read_outstanding() available = read_available() if available is None: log("cannot read the free memory; starting") - return True - if available >= budget_mib: - log("%d MiB free, budget %d MiB; starting" % (available, budget_mib)) - return True - if waited >= limit_seconds: - log("WARNING: only %d MiB free after %ds, budget %d MiB; starting" % (available, waited, budget_mib)) - return False - log("%d MiB free, budget %d MiB; waiting (%d of %ds)" % (available, budget_mib, waited, limit_seconds)) + return + after = read_outstanding() + 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: + log(state + "; starting") + return + waited = clock() - started + if next_line is None or waited >= next_line: + log(state + ("; waiting" if next_line is None else "; still waiting after %ds" % waited)) + next_line = waited + interval_seconds + unlock() sleep(poll_seconds) - waited += poll_seconds def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool = True) -> List[str]: @@ -488,32 +521,114 @@ def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool return prefix + ["--"] -def cap_usable( +def probe_cap( prefix: Sequence[str], platform: str = sys.platform, which: Callable[[str], Optional[str]] = shutil.which, run: Callable[..., "subprocess.CompletedProcess"] = subprocess.run, -) -> bool: +) -> Optional[str]: + """Runs a short command under the prefix. Returns None when the prefix does not work here, else the + text of /proc/self/cgroup inside the probe scope, which can be empty.""" if not platform.startswith("linux") or which("systemd-run") is None: - return False + return None try: - done = run(list(prefix) + ["true"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15) + done = run(list(prefix) + ["cat", "/proc/self/cgroup"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=15) except (OSError, subprocess.TimeoutExpired): - return False - return done.returncode == 0 + return None + if done.returncode != 0: + return None + return done.stdout or "" def choose_cap_prefix( budget_mib: int, cpus: Optional[int], unit: str, - usable: Callable[[Sequence[str]], bool], -) -> Optional[List[str]]: - """Returns the prefix of the hard cap for the unit, or None when no cap is usable here.""" + probe: Callable[[Sequence[str]], Optional[str]], +) -> Optional[Tuple[List[str], str]]: + """Returns the prefix of the hard cap for the unit and the output of its probe, or None when no cap is usable here.""" # A scope unit accepts OOMPolicy= from systemd 253; an older systemd rejects the whole prefix. for oom_policy in (True, False): - if usable(cap_prefix(budget_mib, cpus, unit + "-probe", oom_policy)): - return cap_prefix(budget_mib, cpus, unit, oom_policy) + found = probe(cap_prefix(budget_mib, cpus, unit + "-probe", oom_policy)) + if found is not None: + return cap_prefix(budget_mib, cpus, unit, oom_policy), found return None +def _unified_path(cgroup_text: str) -> Optional[str]: + for line in cgroup_text.splitlines(): + if line.startswith("0::"): + return line.strip()[3:] + return None + + +def scope_parent_directory(probe_output: str, cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]: + """Returns the directory that holds the scope of the probe, or None without a cgroup version 2 line.""" + path = _unified_path(probe_output) + return None if path is None else os.path.dirname(cgroup_root + path) + + +def own_scope_name(proc_root: str = "/proc") -> Optional[str]: + """Returns the name of the cgroup of this process, or None when it cannot be read.""" + try: + with open(os.path.join(proc_root, "self", "cgroup")) as handle: + path = _unified_path(handle.read()) + except OSError: + return None + return None if path is None else os.path.basename(path) + + +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 + try: + with open(os.path.join(parent, name, "memory.max")) as handle: + limit = handle.read().strip() + with open(os.path.join(parent, name, "memory.current")) as handle: + current = int(handle.read().strip()) + if limit == "max": + continue + unused += max(0, int(limit) - current) + except (OSError, ValueError): + # A scope ends between the listing and the read. + continue + return unused // (1024 * 1024) + + +def _scope_counts(path: str) -> bool: + try: + with open(os.path.join(path, "memory.max")) as handle: + limit = handle.read().strip() + with open(os.path.join(path, "memory.current")) as handle: + int(handle.read().strip()) + except (OSError, ValueError): + return False + return limit.isdigit() + + +def wait_for_scope( + parent: str, unit: str, limit_seconds: float, + sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic, +) -> bool: + """Returns True when the scope of the unit is in parent with its memory limit, as unused_budget_mib counts it, + or False when it is not there after limit_seconds.""" + path = os.path.join(parent, unit + ".scope") + deadline = clock() + limit_seconds + # systemd makes the directory of the scope before it writes the limit. + while not _scope_counts(path): + if clock() >= deadline: + return False + sleep(0.02) + return True + + 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: @@ -825,8 +940,22 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive] unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) - prefix = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, cap_usable) + choice = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, probe_cap) + prefix = choice[0] if choice is not None else None capped = prefix is not None + # Every scope of the user that systemd-run makes with no slice option goes to the slice of the probe. + scopes = scope_parent_directory(choice[1]) if choice is not None else None + # A wrapper that runs inside a bounded scope does its work in the budget of that scope. + skip = [name for name in (unit + ".scope", own_scope_name()) if name is not None] + + def read_available() -> Optional[int]: + return available_memory_mib() if settings.free_mib is None else settings.free_mib + + def read_outstanding() -> Optional[int]: + if settings.free_mib is not None or scopes is None: + return None + return unused_budget_mib(scopes, skip) + peak_file = os.path.join(directory, "peak-%s" % unit) if prefix is not None: inside = [sys.executable, os.path.abspath(__file__), "--inside-cap", peak_file, unit, "--"] @@ -855,13 +984,39 @@ def read_sample() -> Optional[int]: tracker.start() trackers.append(tracker) + # Without one lock over the check and the start, two wrappers with different slots both pass the check before either scope counts. + memory_lock_path = os.path.join(directory, "memory.lock") + memory_lock: List[int] = [] + + def lock_memory() -> None: + descriptor = _lock(memory_lock_path, wait=True) + if descriptor is not None: + memory_lock.append(descriptor) + + def unlock_memory() -> None: + while memory_lock: + os.close(memory_lock.pop()) + + def on_start(pid: int) -> None: + start_tracker(pid) + if scopes is not None and memory_lock: + if not wait_for_scope(scopes, unit, SCOPE_WAIT_SECONDS): + log("the scope of the command did not appear after %ds; the next command may not count its budget" % SCOPE_WAIT_SECONDS) + unlock_memory() + reported: Optional[int] = None reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds) try: - wait_for_memory(wait_budget, settings.memory_wait_seconds, settings.poll_seconds) - code, maxrss = run_command(command, child_environ, start_tracker) + wait_for_memory( + wait_budget, settings.memory_wait_seconds, settings.poll_seconds, + headroom_mib=headroom_mib(settings.total_mib, wait_budget, most), + read_available=read_available, read_outstanding=read_outstanding, + lock=lock_memory, unlock=unlock_memory, + ) + code, maxrss = run_command(command, child_environ, on_start) tracked = trackers[0].finish() if trackers else None finally: + unlock_memory() if capped: reported = read_peak_file(peak_file) reservation.release() 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 1095d51..5b15c0f 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -9,6 +9,7 @@ import subprocess import sys import tempfile +import threading import time import unittest from pathlib import Path @@ -60,6 +61,10 @@ def test_says_who_the_test_values_are_for(self): self.assertIn("Values for the tests of this script, and for its maintainers:", text) self.assertNotIn("diagnosis", text) + def test_lists_the_free_memory_for_the_tests(self): + values = bounded_run.__doc__.split("Values for the tests of this script, and for its maintainers:")[1] + self.assertIn("BOUNDED_RUN_FREE_MIB", values) + class SizeTest(unittest.TestCase): def test_reads_gibibytes(self): @@ -228,6 +233,10 @@ def test_defaults(self): self.assertEqual(settings.poll_seconds, 2.0) self.assertEqual(settings.memory_wait_seconds, 300.0) self.assertFalse(settings.no_cap) + self.assertIsNone(settings.free_mib) + + def test_a_set_free_memory(self): + self.assertEqual(bounded_run.Settings({"BOUNDED_RUN_FREE_MIB": "3000"}, read_total=lambda: 1).free_mib, 3000) def test_overrides(self): settings = bounded_run.Settings({ @@ -748,32 +757,227 @@ def setUp(self): self.log = patcher.start() self.addCleanup(patcher.stop) - def wait(self, values, limit): + def wait(self, values, limit, outstanding=None, headroom=0, oversleep=1): readings = list(values) sleeps = [] - result = bounded_run.wait_for_memory( - 4096, limit, 5.0, read_available=lambda: readings.pop(0), sleep=sleeps.append, + now = [0.0] + + def sleep(seconds): + sleeps.append(seconds) + now[0] += seconds * oversleep + + bounded_run.wait_for_memory( + 4096, limit, 5.0, headroom_mib=headroom, read_available=lambda: readings.pop(0), + read_outstanding=lambda: outstanding, sleep=sleep, clock=lambda: now[0], ) - return result, sleeps + return sleeps + + def lines(self): + return [call[0][0] for call in self.log.call_args_list] def test_starts_at_once_when_the_memory_is_free(self): - self.assertEqual(self.wait([8000], 300), (True, [])) + self.assertEqual(self.wait([8000], 300), []) def test_waits_until_the_memory_is_free(self): - self.assertEqual(self.wait([1000, 2000, 5000], 300), (True, [5.0, 5.0])) + self.assertEqual(self.wait([1000, 2000, 5000], 300), [5.0, 5.0]) + + def test_does_not_start_after_the_time_limit_while_the_memory_is_not_free(self): + self.assertEqual(self.wait([1000] * 7 + [5000], 10), [5.0] * 7) + lines = self.lines() + self.assertTrue(lines[-1].endswith("; starting"), lines) + self.assertFalse(any(line.endswith("; starting") for line in lines[:-1]), lines) - def test_starts_after_the_time_limit(self): - self.assertEqual(self.wait([1000, 1000, 1000], 10), (False, [5.0, 5.0])) + def test_a_limit_of_zero_does_not_start_while_the_memory_is_not_free(self): + self.assertEqual(self.wait([1000, 1000, 5000], 0), [5.0, 5.0]) - def test_a_limit_of_zero_does_not_wait(self): - self.assertEqual(self.wait([1000], 0), (False, [])) + def test_the_time_limit_is_the_time_between_two_lines_of_the_wait(self): + self.wait([1000] * 7 + [5000], 10) + waiting = [line for line in self.lines() if "waiting" in line] + self.assertEqual(len(waiting), 4, waiting) + self.assertIn("still waiting", waiting[1]) - def test_a_start_after_the_time_limit_is_a_warning(self): - self.wait([1000], 0) - self.assertTrue(self.log.call_args[0][0].startswith("WARNING: ")) + def test_the_time_between_two_lines_is_real_time(self): + self.wait([1000] * 3 + [5000], 100, oversleep=10) + waiting = [line for line in self.lines() if "waiting" in line] + self.assertEqual(len(waiting), 2, waiting) + self.assertTrue(waiting[1].endswith("; still waiting after 100s"), waiting) def test_starts_when_the_memory_is_not_readable(self): - self.assertEqual(self.wait([None], 300), (True, [])) + self.assertEqual(self.wait([None], 300), []) + self.assertEqual(self.lines(), ["cannot read the free memory; starting"]) + + def test_each_reading_holds_the_lock_and_the_call_returns_with_it_held(self): + events = [] + readings = [1000, 5000] + + def read(): + events.append("read") + return readings.pop(0) + + bounded_run.wait_for_memory( + 4096, 300, 5.0, read_available=read, sleep=lambda seconds: events.append("sleep"), + lock=lambda: events.append("lock"), unlock=lambda: events.append("unlock"), + ) + self.assertEqual(events, ["lock", "read", "unlock", "sleep", "lock", "read"]) + + def test_reads_the_unused_budgets_before_and_after_the_free_memory(self): + events = [] + + def read_available(): + events.append("free") + return 8000 + + def read_outstanding(): + events.append("unused") + return 0 + + bounded_run.wait_for_memory( + 4096, 300, 5.0, read_available=read_available, read_outstanding=read_outstanding, sleep=lambda seconds: None, + ) + self.assertEqual(events, ["unused", "free", "unused"]) + + def test_counts_the_larger_of_the_unused_budgets_read_before_and_after_the_free_memory(self): + for first, second in ((1000, 3000), (3000, 1000)): + with self.subTest(first=first, second=second): + unused = [first, second, 0, 0] + readings = [4000, 8000] + sleeps = [] + bounded_run.wait_for_memory( + 2048, 300, 5.0, read_available=lambda: readings.pop(0), read_outstanding=lambda: unused.pop(0), + sleep=sleeps.append, + ) + self.assertEqual(sleeps, [5.0]) + + def test_the_headroom_is_not_given_out(self): + self.assertEqual(self.wait([5000, 5200], 300, headroom=1024), [5.0]) + + def test_a_line_of_the_wait_names_each_part_of_the_count(self): + self.wait([4000, 8000], 300, outstanding=1500, headroom=1024) + self.assertEqual( + self.lines()[0], + "4000 MiB free, 1500 MiB of running budgets unused, 1024 MiB headroom, budget 4096 MiB; waiting", + ) + + def test_a_line_of_the_wait_says_when_the_unused_budgets_are_not_counted(self): + self.wait([8000], 300, outstanding=None, headroom=1024) + self.assertEqual( + self.lines()[0], + "8000 MiB free, unused running budgets not counted here, 1024 MiB headroom, budget 4096 MiB; starting", + ) + + +class HeadroomTest(unittest.TestCase): + def test_a_tenth_of_the_memory(self): + self.assertEqual(bounded_run.headroom_mib(27703, 2048, 20480), 2770) + + def test_never_less_than_the_minimum(self): + self.assertEqual(bounded_run.headroom_mib(4096, 1024, 4096), 1024) + + def test_no_headroom_for_a_budget_of_the_whole_queue(self): + self.assertEqual(bounded_run.headroom_mib(27703, 20480, 20480), 0) + + def test_the_budget_and_the_headroom_never_need_more_than_the_queue(self): + self.assertEqual(bounded_run.headroom_mib(27703, 19000, 20480), 1480) + + +class UnusedBudgetTest(unittest.TestCase): + """Gives unused_budget_mib a slice of the cgroup filesystem in a temporary directory.""" + + 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, limit, current): + directory = os.path.join(self.slice, name) + os.makedirs(directory) + if limit is not None: + Path(directory, "memory.max").write_text(limit + "\n") + if current is not None: + Path(directory, "memory.current").write_text(current + "\n") + + def unused(self, skip=()): + return bounded_run.unused_budget_mib(self.slice, skip) + + def test_adds_the_unused_part_of_each_budget(self): + self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), str(1024 * 1024 ** 2)) + self.scope("bounded-run-11-bbbbbb.scope", str(2048 * 1024 ** 2), str(512 * 1024 ** 2)) + self.assertEqual(self.unused(), 5120 + 1536) + + def test_a_scope_above_its_budget_adds_nothing(self): + self.scope("bounded-run-10-aaaaaa.scope", str(1024 * 1024 ** 2), str(2048 * 1024 ** 2)) + self.assertEqual(self.unused(), 0) + + def test_skips_the_probe_scopes(self): + self.scope("bounded-run-10-aaaaaa-probe.scope", str(6144 * 1024 ** 2), "0") + self.assertEqual(self.unused(), 0) + + def test_skips_the_scopes_that_the_caller_names(self): + self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), "0") + self.scope("bounded-run-11-bbbbbb.scope", str(2048 * 1024 ** 2), "0") + self.assertEqual(self.unused(skip=["bounded-run-10-aaaaaa.scope"]), 2048) + + def test_skips_a_scope_with_no_budget(self): + self.scope("bounded-run-10-aaaaaa.scope", "max", "0") + self.assertEqual(self.unused(), 0) + + def test_skips_units_of_other_programs(self): + self.scope("editor-1.scope", str(6144 * 1024 ** 2), "0") + self.scope("bounded-run-10-aaaaaa.service", str(6144 * 1024 ** 2), "0") + self.assertEqual(self.unused(), 0) + + def test_skips_a_scope_that_ends_while_it_is_read(self): + self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), None) + self.scope("bounded-run-11-bbbbbb.scope", None, None) + self.assertEqual(self.unused(), 0) + + def test_no_slice_gives_nothing(self): + self.assertEqual(bounded_run.unused_budget_mib(os.path.join(self.base.name, "gone"), ()), 0) + + def test_the_slice_is_the_parent_of_the_probe_scope(self): + self.assertEqual( + bounded_run.scope_parent_directory("0::/user.slice/user@1000.service/app.slice/unit-1-probe.scope\n", "/cg"), + "/cg/user.slice/user@1000.service/app.slice", + ) + + def test_the_scope_of_this_process(self): + with tempfile.TemporaryDirectory() as proc: + os.mkdir(os.path.join(proc, "self")) + Path(proc, "self", "cgroup").write_text("0::/user.slice/app.slice/bounded-run-2-111111.scope\n") + self.assertEqual(bounded_run.own_scope_name(proc_root=proc), "bounded-run-2-111111.scope") + + def test_no_scope_of_this_process_without_its_cgroup(self): + with tempfile.TemporaryDirectory() as proc: + self.assertIsNone(bounded_run.own_scope_name(proc_root=proc)) + + def test_no_slice_without_a_cgroup_version_2_line(self): + self.assertIsNone(bounded_run.scope_parent_directory("", "/cg")) + self.assertIsNone(bounded_run.scope_parent_directory("4:memory:/user.slice/unit-1-probe.scope\n", "/cg")) + + def test_the_wait_for_a_scope_ends_after_its_time_limit_of_real_time(self): + now = [0.0] + + def slow_sleep(seconds): + now[0] += 10 * seconds + + self.assertFalse(bounded_run.wait_for_scope(self.slice, "bounded-run-1-000000", 1.0, sleep=slow_sleep, clock=lambda: now[0])) + self.assertLessEqual(now[0], 1.2) + + def test_a_running_command_that_uses_little_of_a_large_budget_holds_back_the_next(self): + self.scope("bounded-run-10-aaaaaa.scope", str(6144 * 1024 ** 2), str(1024 * 1024 ** 2)) + sleeps = [] + + def sleep(seconds): + sleeps.append(seconds) + shutil.rmtree(os.path.join(self.slice, "bounded-run-10-aaaaaa.scope")) + + with mock.patch.object(bounded_run, "log"): + bounded_run.wait_for_memory( + 4096, 300, 5.0, headroom_mib=1024, read_available=lambda: 8000, + read_outstanding=lambda: self.unused(), sleep=sleep, + ) + self.assertEqual(sleeps, [5.0]) class CapTest(unittest.TestCase): @@ -795,28 +999,28 @@ def test_prefix_without_the_oom_policy(self): def choose(self, answers): probes = [] - def usable(prefix): + def probe(prefix): probes.append(list(prefix)) return answers[len(probes) - 1] - return bounded_run.choose_cap_prefix(1024, 2, "unit-1", usable), probes + return bounded_run.choose_cap_prefix(1024, 2, "unit-1", probe), probes def test_uses_the_oom_policy_when_the_first_probe_passes(self): - prefix, probes = self.choose([True]) - self.assertEqual(prefix, bounded_run.cap_prefix(1024, 2, "unit-1")) + choice, probes = self.choose(["0::/app.slice/unit-1-probe.scope\n"]) + self.assertEqual(choice, (bounded_run.cap_prefix(1024, 2, "unit-1"), "0::/app.slice/unit-1-probe.scope\n")) self.assertEqual(len(probes), 1) self.assertIn("OOMPolicy=continue", probes[0]) self.assertNotIn("unit-1", probes[0]) def test_uses_the_prefix_without_the_oom_policy_when_only_the_second_probe_passes(self): - prefix, probes = self.choose([False, True]) - self.assertEqual(prefix, bounded_run.cap_prefix(1024, 2, "unit-1", oom_policy=False)) + choice, probes = self.choose([None, ""]) + self.assertEqual(choice, (bounded_run.cap_prefix(1024, 2, "unit-1", oom_policy=False), "")) self.assertEqual(len(probes), 2) self.assertNotIn("OOMPolicy=continue", probes[1]) def test_no_cap_when_both_probes_fail(self): - prefix, probes = self.choose([False, False]) - self.assertIsNone(prefix) + choice, probes = self.choose([None, None]) + self.assertIsNone(choice) self.assertEqual(len(probes), 2) def test_no_command_runs_on_a_different_system(self): @@ -826,47 +1030,50 @@ def run(command, **keywords): calls.append(command) return subprocess.CompletedProcess(command, 0) - def usable(prefix): - return bounded_run.cap_usable(prefix, platform="darwin", which=lambda name: "/usr/bin/systemd-run", run=run) + def probe(prefix): + return bounded_run.probe_cap(prefix, platform="darwin", which=lambda name: "/usr/bin/systemd-run", run=run) - self.assertIsNone(bounded_run.choose_cap_prefix(1024, 2, "unit-1", usable)) + self.assertIsNone(bounded_run.choose_cap_prefix(1024, 2, "unit-1", probe)) self.assertEqual(calls, []) - def probe(self, platform, tool, code=0, error=None): + def probe(self, platform, tool, code=0, error=None, output=None): calls = [] def run(command, **keywords): calls.append(command) if error is not None: raise error - return subprocess.CompletedProcess(command, code) + return subprocess.CompletedProcess(command, code, stdout=output) - usable = bounded_run.cap_usable( + found = bounded_run.probe_cap( bounded_run.cap_prefix(1024, 2, "unit-1"), platform=platform, which=lambda name: tool, run=run, ) - return usable, calls + return found, calls - def test_usable_when_the_probe_succeeds(self): - usable, calls = self.probe("linux", "/usr/bin/systemd-run") - self.assertTrue(usable) - self.assertEqual(calls[0][-1], "true") + def test_the_probe_gives_the_cgroup_of_its_scope(self): + found, calls = self.probe("linux", "/usr/bin/systemd-run", output="0::/app.slice/unit-1.scope\n") + self.assertEqual(found, "0::/app.slice/unit-1.scope\n") + self.assertEqual(calls[0][-2:], ["cat", "/proc/self/cgroup"]) self.assertIn("CPUQuota=200%", calls[0]) + def test_a_probe_with_no_output_is_usable(self): + self.assertEqual(self.probe("linux", "/usr/bin/systemd-run")[0], "") + def test_not_usable_when_the_probe_fails(self): - self.assertFalse(self.probe("linux", "/usr/bin/systemd-run", code=1)[0]) + self.assertIsNone(self.probe("linux", "/usr/bin/systemd-run", code=1)[0]) def test_not_usable_when_the_probe_does_not_return(self): error = subprocess.TimeoutExpired("systemd-run", 15) - self.assertFalse(self.probe("linux", "/usr/bin/systemd-run", error=error)[0]) + self.assertIsNone(self.probe("linux", "/usr/bin/systemd-run", error=error)[0]) def test_not_usable_without_the_tool(self): - usable, calls = self.probe("linux", None) - self.assertFalse(usable) + found, calls = self.probe("linux", None) + self.assertIsNone(found) self.assertEqual(calls, []) def test_not_usable_on_a_different_system(self): - usable, calls = self.probe("darwin", "/usr/bin/systemd-run") - self.assertFalse(usable) + found, calls = self.probe("darwin", "/usr/bin/systemd-run") + self.assertIsNone(found) self.assertEqual(calls, []) @@ -1220,7 +1427,7 @@ def test_a_child_of_this_process_runs_with_no_pipe(self): class BoundedCleanupTest(unittest.TestCase): - """Calls bounded() in this process, with run_command and cap_usable replaced by stubs. + """Calls bounded() in this process, with run_command and probe_cap replaced by stubs. No real command, no real cgroup, and no real subprocess run outside the stubs. """ @@ -1243,6 +1450,7 @@ def setUp(self): "BOUNDED_RUN_POLL_SECONDS": "0.05", "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", "BOUNDED_RUN_SAMPLE_SECONDS": "0.1", + "BOUNDED_RUN_FREE_MIB": "1048576", }) def test_the_peak_file_is_removed_when_the_run_fails_after_the_start(self): @@ -1256,7 +1464,7 @@ def fake_run_command(command, environ, on_start=None): options.memory = "2G" options.command = [sys.executable, "-c", "pass"] - with mock.patch.object(bounded_run, "cap_usable", return_value=True), \ + with mock.patch.object(bounded_run, "probe_cap", return_value=""), \ mock.patch.object(bounded_run, "run_command", fake_run_command): with self.assertRaises(RuntimeError): bounded_run.bounded(options, self.environ) @@ -1280,14 +1488,152 @@ def fake_run_command(command, environ, on_start=None): options.memory = "64G" options.command = [sys.executable, "-c", "pass"] - with mock.patch.object(bounded_run, "cap_usable", return_value=True), \ - mock.patch.object(bounded_run, "wait_for_memory", side_effect=lambda budget, *rest: waits.append(budget)), \ + with mock.patch.object(bounded_run, "probe_cap", return_value=""), \ + mock.patch.object(bounded_run, "wait_for_memory", side_effect=lambda budget, *rest, **keywords: waits.append(budget)), \ mock.patch.object(bounded_run, "run_command", fake_run_command): self.assertEqual(bounded_run.bounded(options, self.environ), 0) self.assertEqual(waits, [4096]) self.assertIn("MemoryMax=4096M", commands[0]) + def wait_arguments(self, probe_output, environ=None): + waits = [] + options = bounded_run.Options() + options.memory = "1G" + options.command = [sys.executable, "-c", "pass"] + if environ is None: + environ = dict(self.environ) + del environ["BOUNDED_RUN_FREE_MIB"] + with mock.patch.object(bounded_run, "probe_cap", return_value=probe_output), \ + mock.patch.object(bounded_run, "own_scope_name", return_value="bounded-run-2-111111.scope"), \ + mock.patch.object(bounded_run, "wait_for_memory", side_effect=lambda *arguments, **keywords: waits.append(keywords)), \ + mock.patch.object(bounded_run, "run_command", return_value=(0, 0)): + self.assertEqual(bounded_run.bounded(options, environ), 0) + return waits[0] + + def test_the_wait_keeps_a_headroom_of_the_memory_of_the_machine(self): + self.assertEqual(self.wait_arguments(None)["headroom_mib"], bounded_run.headroom_mib(4096, 1024, 4096)) + + def run_with_free_memory(self, memory, total, free): + options = bounded_run.Options() + options.memory = memory + options.command = [sys.executable, "-c", "pass"] + environ = dict(self.environ, BOUNDED_RUN_TOTAL_MIB=str(total), BOUNDED_RUN_RESERVE_MIB="", BOUNDED_RUN_FREE_MIB=str(free)) + + real_wait = bounded_run.wait_for_memory + + def sleep(seconds): + raise AssertionError("the command waits") + + def wait(*arguments, **keywords): + return real_wait(*arguments, sleep=sleep, **keywords) + + with mock.patch.object(bounded_run, "probe_cap", return_value=None), \ + mock.patch.object(bounded_run, "wait_for_memory", wait), \ + mock.patch.object(bounded_run, "run_command", return_value=(0, 0)): + return bounded_run.bounded(options, environ) + + def test_a_budget_of_the_whole_queue_starts_when_the_memory_of_the_queue_is_free(self): + queue = bounded_run.queue_mib(27703, 2048, bounded_run.default_reserve_mib(27703)) + self.assertEqual(self.run_with_free_memory("%dM" % queue, 27703, queue), 0) + + def test_a_small_budget_waits_for_its_headroom(self): + with self.assertRaisesRegex(AssertionError, "the command waits"): + self.run_with_free_memory("2G", 27703, 2048 + bounded_run.headroom_mib(27703, 2048, 20480) - 1) + + def test_a_small_budget_starts_with_its_headroom_free(self): + self.assertEqual(self.run_with_free_memory("2G", 27703, 2048 + bounded_run.headroom_mib(27703, 2048, 20480)), 0) + + def test_a_set_free_memory_replaces_the_free_memory_and_the_unused_budgets(self): + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + keywords = self.wait_arguments(output, dict(self.environ, BOUNDED_RUN_FREE_MIB="3000")) + with mock.patch.object(bounded_run, "unused_budget_mib", side_effect=AssertionError("unused")), \ + mock.patch.object(bounded_run, "available_memory_mib", side_effect=AssertionError("available")): + self.assertEqual(keywords["read_available"](), 3000) + self.assertIsNone(keywords["read_outstanding"]()) + + def test_the_wait_counts_the_unused_budgets_beside_the_scope_of_the_probe(self): + calls = [] + + def unused(parent, skip): + calls.append((parent, list(skip))) + return 777 + + output = "0::/user.slice/app.slice/bounded-run-1-000000-probe.scope\n" + keywords = self.wait_arguments(output) + with mock.patch.object(bounded_run, "unused_budget_mib", unused): + self.assertEqual(keywords["read_outstanding"](), 777) + parent, skip = calls[0] + self.assertEqual(parent, "/sys/fs/cgroup/user.slice/app.slice") + self.assertIn("bounded-run-2-111111.scope", skip) + self.assertTrue(any(re.match(r"^bounded-run-%d-[0-9a-f]{6}\.scope$" % os.getpid(), name) for name in skip), skip) + + def run_with_scopes(self, appears): + """Runs bounded() with a capped command whose scope appears in a temporary slice in two steps, or never when appears is false. + + The scope appears first with no memory limit, then with its limit. Returns whether the memory lock was free before the + scope, before its limit, and when the command started. + """ + scopes = os.path.join(self.base.name, "slice") + os.makedirs(scopes) + lock_path = os.path.join(self.directory, "memory.lock") + free = {} + + def lock_is_free(): + descriptor = bounded_run._try_lock(lock_path) + if descriptor is None: + return False + os.close(descriptor) + return True + + def fake_run_command(command, environ, on_start=None): + scope = os.path.join(scopes, command[command.index("--inside-cap") + 2] + ".scope") + + def appear(): + time.sleep(0.2) + free["before the scope"] = lock_is_free() + if appears: + os.mkdir(scope) + Path(scope, "memory.max").write_text("max\n") + time.sleep(0.2) + free["before the limit"] = lock_is_free() + if appears: + Path(scope, "memory.current").write_text("0\n") + Path(scope, "memory.max").write_text("%d\n" % (1024 * 1024 ** 2)) + + thread = threading.Thread(target=appear) + thread.start() + on_start(os.getpid()) + thread.join() + free["at the start"] = lock_is_free() + return 0, 0 + + options = bounded_run.Options() + options.memory = "1G" + options.command = [sys.executable, "-c", "pass"] + with mock.patch.object(bounded_run, "probe_cap", return_value="0::/slice/bounded-run-1-000000-probe.scope\n"), \ + mock.patch.object(bounded_run, "scope_parent_directory", return_value=scopes), \ + mock.patch.object(bounded_run, "SCOPE_WAIT_SECONDS", 1.0), \ + mock.patch.object(bounded_run, "run_command", fake_run_command): + self.assertEqual(bounded_run.bounded(options, self.environ), 0) + return free + + def test_the_next_memory_check_waits_until_the_scope_of_the_command_counts(self): + free = self.run_with_scopes(appears=True) + self.assertEqual(free, {"before the scope": False, "before the limit": False, "at the start": True}) + + def test_a_scope_that_never_appears_frees_the_memory_check_after_a_time_limit(self): + started = time.monotonic() + free = self.run_with_scopes(appears=False) + self.assertEqual(free, {"before the scope": False, "before the limit": False, "at the start": True}) + self.assertLess(time.monotonic() - started, 5) + + def test_the_wait_counts_no_unused_budget_without_a_cap(self): + self.assertIsNone(self.wait_arguments(None)["read_outstanding"]()) + + def test_the_wait_counts_no_unused_budget_without_a_cgroup_version_2(self): + self.assertIsNone(self.wait_arguments("")["read_outstanding"]()) + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" @@ -1307,6 +1653,7 @@ def setUp(self): "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", "BOUNDED_RUN_SAMPLE_SECONDS": "0.1", "BOUNDED_RUN_NO_CAP": "1", + "BOUNDED_RUN_FREE_MIB": "1048576", "EVENTS": self.events, }) self.processes = [] @@ -1633,7 +1980,7 @@ def test_the_command_does_not_inherit_the_locks(self): ) process = self.wrapper(["--memory", "4G", "--exclusive", "port"], [sys.executable, "-c", script]) output, errors = process.communicate(timeout=60) - self.assertEqual(output, "locks 4 inherited 0\n", errors) + self.assertEqual(output, "locks 5 inherited 0\n", errors) def test_commands_with_the_same_exclusive_name_take_turns(self): workers = [self.worker("w%d" % index, "2G", hold="0.3", options=["--exclusive", "port-8080"]) for index in range(3)] # brief; the test waits for each to end @@ -1774,9 +2121,8 @@ def test_a_measurement_with_a_budget_takes_the_slots_of_the_budget(self): def test_a_first_measurement_waits_for_the_memory_of_the_default_budget_only(self): reads = [] - def wait(budget, limit, poll): + def wait(budget, limit, poll, **rest): reads.append(budget) - return True options = bounded_run.Options() options.measure = True @@ -1819,7 +2165,7 @@ def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self): @unittest.skipUnless( - bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.cap_usable) is not None, + 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", ) class HardCapTest(WrapperProcessCase):