diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index b3f934a..6511ea7 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -33,7 +33,8 @@ A server that a heavy command talks to is a part of that command: a development ## The wrapper ``` -python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... [--measure] -- +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 ] -- ``` | Option | Meaning | @@ -42,8 +43,18 @@ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_ru | `--cpus ` | Processor limit, as a whole number. Taken from the record. | | `--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. | +| `--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. | -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 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: + +``` +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). + +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. @@ -78,7 +89,7 @@ Then, before each heavy command, use the first case that applies: 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. 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 the commands that you are about to run, and save the record. The measured runs of the discovery are your first heavy runs. A heavy command of the project that you do not run now gets its entry when an agent first needs it. +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. A budget is a measurement, not a preference. Change a row only when the wrapper's output at the `--cpus` of that row shows that the peak moved, and write the new peak and date in it. @@ -88,7 +99,7 @@ A part of a recorded command (one test file, one target) uses the bounded comman ## Discovery -1. Find how the project runs its tests, its linter, its build, and its type check. Read the project's instruction files, its build configuration, and its CI configuration. +1. Find how the project runs its tests, its linter, its build, and its type check, and each other heavy command (§When to invoke): code generators, installs, formatters over the whole tree. Read the project's instruction files, its build configuration, and its CI configuration. 2. Bound the command before you measure it. Do not measure a command until this step is done. Find what makes the toolchain run fewer things at once: a flag or a variable for the number of jobs, workers, processes, or threads. Find a memory setting too, but only one that covers the whole command. A memory setting for one process does not cover the processes that it starts. Most tools that start many processes have no memory setting for the whole command, so the number of things that run at once is the main way to lower the peak. Write the command line so that it takes the setting from `BOUNDED_RUN_CPUS` or `BOUNDED_RUN_MEMORY_MIB`, and record that setting as the `self-bound` of the entry. When the tool has no such setting, record `self-bound: none: `, so that a missing bound is a decision and not an omission. The wrapper sets the two variables for the command only. Your own shell does not have them. Put the command into an inner shell, in single quotes, so that your own shell does not replace the variable with an empty value before the wrapper starts: ``` @@ -109,6 +120,26 @@ A part of a recorded command (one test file, one target) uses the bounded comman The measured run is a real run of the command. Its result counts, also when the run stopped early, so do not run the command a second time to get the result. +### Measure the whole project + +When the record does not exist (§The record, case 5), do steps 1 to 3 for every heavy command of the project. Then measure them all in one run, in place of steps 4 and 5. Do not measure only the command that you need now. A command that gets its entry later gets its first measurement in the middle of someone's work, and that measurement holds the whole queue while other sessions wait. + +1. Choose the rows. Measure each command at three `--cpus`: all the machine's processors, half of them, and a quarter of them. Round each one down, use at least 1, and drop a value that is the same as another. A command with `self-bound: none` gets the row at half only: nothing in it reads its `--cpus`, so each row would measure the same command. A command whose next run reuses the output of the run before, such as a build or a generator with a cache, also gets the row at half only: its later rows would do less work and measure a peak that is too small. +2. Write one command line. For each command, write one call of the wrapper with `--measure-rows` and the rows that step 1 chose for it, a `--label` that names the command and no other command of the line, the `--exclusive` options of the command, and its bounded command line. Join the calls with `;`, so that a measurement that fails does not stop the others. Write the path of the wrapper in full, so that the line runs in any shell. Run it from the root of the project: + + ``` + python3 "" --measure-rows 16,8,4 --label unit-tests -- ; python3 "" --measure-rows 16,8,4 --label lint -- + ``` + +3. Ask the user to run the line when the machine is quiet. Do not run it yourself unless the user asks you to. Your message names the commands and the rows that the line measures. It says that the line can take a long time, and that the first row of each command holds the whole queue, so that the heavy commands of the other sessions wait while it runs. It says how to run the line: type `! ` in this session, or run it in a terminal at the root of the project, or tell you to run it. +4. Act on the answer: + - **The user ran the line.** Read its output into the record (step 5 of this list). When the user ran it in a terminal, you cannot see the output: ask the user for each line that starts with `bounded-run: row`, and for the end of the output of each command, which shows whether the run did its full work. + - **The user tells you to run it.** Run it in the background, with no short timeout around it. Continue with work that runs no heavy command. A heavy command that you need before the line ends runs through the wrapper with no `--memory` option. When the line ends, read its output into the record (step 5 of this list). + - **The user declines.** Run steps 4 to 6 of the list above for the command that you are about to run, and save the record. Each other command gets its entry when an agent first needs it (§The record, case 3). +5. Read the row lines of the output. Each row line of a run that did its full work gives the row at its `cpus`, in the entry of its `label`: its `budget`, its `peak`, and the date. A run did its full work when it exits 0, or when it ran all of its work and reported failures, such as a suite that ran each test and reported the failures. Step 5 of the list above names the runs that stopped early. A row line of such a run gives no row: write nothing for it. The row at half the processors is the default row. When it has no row, the default row is the row with the `--cpus` nearest to half. An entry that has no row is incomplete (§The record), and an agent measures it when it first needs it. Save the record. + +A command that the project adds later gets its entry when an agent first needs it (§The record, case 3). + ## 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. @@ -176,6 +207,8 @@ When Python is missing or too old, and when the fault is a fault of the machine, | "I measured the plain command, the peak is real" | It is the real peak of a command that nothing limits. Bound the command first, then measure the bounded command line at the `--cpus` that you record. | | "The new measurement at a different `--cpus` replaces the old entry" | A different `--cpus` is a different command. Add a row and keep the others. Only a measurement at the same `--cpus` replaces a row. | | "A smaller `--cpus` is a lower budget by another name" | A lower `--memory` on the same command is a guess. A row at a smaller `--cpus` is a smaller command with a measured budget. Use it to start sooner. | +| "I only need the unit tests now, the others get entries when an agent needs them" | Each later first measurement holds the whole queue in the middle of someone's work. When the record does not exist, measure every heavy command of the project with one command line. | +| "I'll run the measurements myself now, it saves the user a step" | The line holds the whole queue for a long time. The user chooses when the machine can give it that time. Ask, and run it only when the user tells you to. | | "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 b75b7f9..00717cd 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -1,11 +1,23 @@ #!/usr/bin/env python3 """Runs a command under a memory reservation that every project of the user shares. -Usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] -- COMMAND... +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... The exit code is the exit code of the command. Exit code 125 means that this script failed before the command gave a result. +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 exact=yes|no exit=CODE + +budget is the suggested budget. A '-' stands for an option that the call did +not give. --measure-rows measures the command at each processor limit of the +list, the largest first. The largest runs with --memory, or alone in the queue. +Each smaller one runs with the suggested budget of the one before it, or with +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. + 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,7 +80,12 @@ MARGIN_APPROXIMATE = 0.5 BUDGET_STEP_MIB = 256 PR_SET_PDEATHSIG = 1 -USAGE = "usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] -- COMMAND..." +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..." +) +# 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)) class WrapperError(Exception): @@ -939,6 +956,8 @@ def __init__(self) -> None: self.cpus: Optional[int] = None self.exclusive: List[str] = [] self.measure = False + self.rows: List[int] = [] + self.label: Optional[str] = None self.command: List[str] = [] @@ -957,7 +976,7 @@ def parse_arguments(argv: Sequence[str]) -> Options: if flag == "--measure": options.measure = True continue - if flag not in ("--memory", "--cpus", "--exclusive"): + if flag not in ("--memory", "--cpus", "--exclusive", "--measure-rows", "--label"): 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)) @@ -967,14 +986,80 @@ def parse_arguments(argv: Sequence[str]) -> Options: elif flag == "--exclusive": if value not in options.exclusive: options.exclusive.append(value) + elif flag == "--label": + # The row line separates its fields with spaces and marks a missing label with '-'. + if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", value) is None: + raise WrapperError("cannot use the label '%s'; use letters, digits, '.', '_' and '-', and start with a letter or a digit" % value) + options.label = value + elif flag == "--measure-rows": + parts = value.split(",") + # int() of a very long number is slow on some versions of Python and raises ValueError on others. + rows = [int(part) for part in parts if re.fullmatch(r"[0-9]{1,6}", part)] + if len(rows) != len(parts) or min(rows) < 1: + raise WrapperError("cannot read --measure-rows '%s'; use whole numbers from 1 to 999999, such as 16,8,4" % value) + options.rows = sorted(set(rows), reverse=True) + options.measure = True else: if not value.isdigit() or int(value) < 1: raise WrapperError("cannot read --cpus '%s'; use a whole number of 1 or more" % value) options.cpus = int(value) + if options.rows and options.cpus is not None: + raise WrapperError("use --measure-rows or --cpus, not both\n" + USAGE) + if options.label is not None and not options.measure: + raise WrapperError("--label needs --measure or --measure-rows\n" + USAGE) return options +class _Stopped(Exception): + def __init__(self, signum: int) -> None: + super().__init__(signum) + self.signum = signum + + +def _raise_stopped(signum: int, frame: object) -> None: + raise _Stopped(signum) + + def bounded(options: Options, environ: Mapping[str, str]) -> int: + if not options.rows: + return bounded_once(options, environ)[0] + # run_command sets its own handlers while a row runs and puts these back after it. + previous = {signum: signal.signal(signum, _raise_stopped) for signum in (signal.SIGTERM, signal.SIGHUP, signal.SIGQUIT)} + try: + return _bounded_rows(options, environ) + finally: + for signum, handler in previous.items(): + signal.signal(signum, handler) + + +def _bounded_rows(options: Options, environ: Mapping[str, str]) -> int: + memory = options.memory + result = 0 + measured = 0 + try: + for cpus in options.rows: + row = Options() + row.memory, row.cpus, row.exclusive, row.measure, row.label, row.command = ( + memory, cpus, options.exclusive, True, options.label, options.command) + code, suggested = bounded_once(row, environ) + measured += 1 + if code in STOP_CODES: + log("stopped by a signal; the rows after --cpus %d are not measured" % cpus) + return result or code + if code == 0: + memory = "%dM" % suggested + else: + # A run that stopped early has a peak that is too small to be the budget of a smaller command. + result = result or code + except (KeyboardInterrupt, _Stopped) as stop: + # A signal while a row runs comes back as its exit code. A signal at any other time in the list raises. + log("stopped by a signal; %d of %d rows are measured" % (measured, len(options.rows))) + return result or 128 + (stop.signum if isinstance(stop, _Stopped) else int(signal.SIGINT)) + return result + + +def bounded_once(options: Options, environ: Mapping[str, str]) -> Tuple[int, int]: + """Runs the command one time. Returns the exit code and the suggested budget in MiB.""" settings = Settings(environ) if options.memory is not None: budget = parse_size_mib(options.memory) @@ -1095,9 +1180,12 @@ def on_start(pid: int) -> None: log("budget %d MiB, peak %d MiB (%s), exit %d" % (budget, peak, "cgroup" if exact else "sampled, approximate", code)) if capped and code == 137: log("the command was killed; if the peak is near the budget, the hard cap stopped it") + suggested = suggested_budget_mib(peak, not exact) if options.measure: - log("suggested budget %d MiB" % suggested_budget_mib(peak, not exact)) - return code + log("suggested budget %d MiB" % suggested) + log("row label=%s cpus=%s budget=%dM peak=%dM exact=%s exit=%d" % ( + options.label or "-", options.cpus if options.cpus is not None else "-", suggested, peak, "yes" if exact else "no", code)) + return code, suggested def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int: @@ -1118,6 +1206,10 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st except KeyboardInterrupt: log("interrupted while waiting") return 130 + except _Stopped as stop: + # The handlers of --measure-rows can fire after its list ends, before they are put back. + log("stopped by a signal") + return 128 + stop.signum except WrapperError as error: log(str(error)) return EXIT_WRAPPER 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 8a58e83..f6ec6bc 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1257,6 +1257,29 @@ def test_a_repeated_exclusive_name_is_kept_one_time(self): ) self.assertEqual(options.exclusive, ["port", "cache"]) + def test_reads_the_rows_largest_first_and_each_one_time(self): + options = bounded_run.parse_arguments(["--measure-rows", "4,16,8,4", "--label", "unit-tests", "--", "tool"]) + self.assertEqual((options.rows, options.label, options.measure), ([16, 8, 4], "unit-tests", True)) + + def test_rejects_bad_rows_and_labels(self): + for arguments in ( + ["--measure-rows", "0,2", "--", "tool"], + ["--measure-rows", "two", "--", "tool"], + ["--measure-rows", "", "--", "tool"], + ["--measure-rows", "4,,2", "--", "tool"], + ["--measure-rows", "\u00b2", "--", "tool"], + ["--measure-rows", "9" * 5000, "--", "tool"], + ["--measure-rows", "1000000", "--", "tool"], + ["--measure-rows", "4,2", "--cpus", "2", "--", "tool"], + ["--measure", "--label", "unit tests", "--", "tool"], + ["--measure", "--label", "-", "--", "tool"], + ["--measure", "--label", "lint\n", "--", "tool"], + ["--label", "lint", "--", "tool"], + ): + with self.subTest(arguments=arguments): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.parse_arguments(arguments) + class InsideCapTest(unittest.TestCase): def setUp(self): @@ -1710,6 +1733,137 @@ def test_the_wait_counts_no_unused_budget_without_a_cgroup_version_2(self): self.assertIsNone(self.wait_arguments("")["read_outstanding"]()) +class MeasuredRowTest(unittest.TestCase): + """Calls bounded() in this process, with run_command replaced by a stub and no hard cap. + + The stub gives each run the exit code and the ru_maxrss of the next answer, and keeps the + budget and the processors that the wrapper gave to the command. + """ + + 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.environ = dict(os.environ) + self.environ.pop("BOUNDED_RUN_ACTIVE", None) + self.environ.update({ + "BOUNDED_RUN_LOCK_DIR": os.path.join(self.base.name, "locks"), + "BOUNDED_RUN_TOTAL_MIB": "8192", + "BOUNDED_RUN_RESERVE_MIB": "0", + "BOUNDED_RUN_SLOT_MIB": "2048", + "BOUNDED_RUN_POLL_SECONDS": "0.05", + "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", + "BOUNDED_RUN_SAMPLE_SECONDS": "0.1", + "BOUNDED_RUN_NO_CAP": "1", + "BOUNDED_RUN_FREE_MIB": "1048576", + }) + self.runs = [] + + def run_bounded(self, arguments, answers): + remaining = list(answers) + + def fake_run_command(command, environ, on_start=None): + self.runs.append((int(environ["BOUNDED_RUN_CPUS"]), int(environ["BOUNDED_RUN_MEMORY_MIB"]))) + code, peak_mib = remaining.pop(0) + return code, peak_mib * 1024 + + options = bounded_run.parse_arguments(arguments + ["--", sys.executable, "-c", "pass"]) + with mock.patch.object(bounded_run, "run_command", fake_run_command), \ + mock.patch.object(bounded_run, "rusage_peak_mib", side_effect=lambda maxrss: maxrss // 1024): + return bounded_run.bounded(options, self.environ) + + def row_lines(self): + return [line for line in self.lines if line.startswith("row ")] + + 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 exact=no exit=0"]) + + 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 exact=no exit=3"]) + + def test_a_run_that_does_not_measure_prints_no_row_line(self): + self.run_bounded(["--memory", "2G"], [(0, 100)]) + self.assertEqual(self.row_lines(), []) + + def test_rows_run_largest_first_and_each_smaller_row_gets_the_budget_of_the_row_before_it(self): + code = self.run_bounded(["--measure-rows", "2,8,4", "--label", "build"], [(0, 1000), (0, 500), (0, 200)]) + self.assertEqual(code, 0) + # The first row has no budget yet, so it holds the whole queue of 8192 MiB. + self.assertEqual(self.runs, [(8, 8192), (4, 1536), (2, 768)]) + self.assertEqual(self.row_lines(), [ + "row label=build cpus=8 budget=1536M peak=1000M exact=no exit=0", + "row label=build cpus=4 budget=768M peak=500M exact=no exit=0", + "row label=build cpus=2 budget=512M peak=200M exact=no exit=0", + ]) + + def test_the_largest_row_runs_with_the_given_memory(self): + self.run_bounded(["--measure-rows", "8,4", "--memory", "4G"], [(0, 1000), (0, 500)]) + self.assertEqual(self.runs, [(8, 4096), (4, 1536)]) + + def test_the_row_after_a_failed_row_gets_the_budget_of_the_failed_row(self): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(1, 300), (0, 1000), (2, 100)]) + self.assertEqual(code, 1) + self.assertEqual(self.runs, [(8, 8192), (4, 8192), (2, 1536)]) + self.assertEqual([line.split()[-1] for line in self.row_lines()], ["exit=1", "exit=0", "exit=2"]) + + def test_a_row_that_a_stop_signal_ended_ends_the_rows(self): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(0, 1000), (130, 100), (0, 100)]) + self.assertEqual(code, 130) + self.assertEqual(self.runs, [(8, 8192), (4, 1536)]) + self.assertEqual(len(self.row_lines()), 2) + + def test_a_stop_signal_after_a_failed_row_keeps_the_first_exit_code(self): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(1, 1000), (130, 100), (0, 100)]) + self.assertEqual(code, 1) + self.assertEqual(len(self.runs), 2) + + def test_a_stop_signal_while_a_later_row_waits_keeps_the_first_exit_code(self): + for failure, expected in ((1, 1), (0, 128 + signal.SIGTERM)): + with self.subTest(failure=failure): + real_once = bounded_run.bounded_once + calls = [] + + def once(options, environ): + calls.append(options.cpus) + if len(calls) == 2: + os.kill(os.getpid(), signal.SIGTERM) + time.sleep(5) + return real_once(options, environ) + + before = signal.getsignal(signal.SIGTERM) + self.runs = [] + with mock.patch.object(bounded_run, "bounded_once", once): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(failure, 1000)]) + self.assertEqual(code, expected) + self.assertEqual(calls, [8, 4]) + self.assertIs(signal.getsignal(signal.SIGTERM), before) + + def test_a_stop_signal_outside_a_row_ends_main_with_its_code(self): + options = ["--measure-rows", "8,4", "--", sys.executable, "-c", "pass"] + with mock.patch.object(bounded_run, "bounded", side_effect=bounded_run._Stopped(int(signal.SIGTERM))): + self.assertEqual(bounded_run.main(options, self.environ), 128 + signal.SIGTERM) + + def test_an_interrupt_while_a_later_row_waits_keeps_the_first_exit_code(self): + real_once = bounded_run.bounded_once + calls = [] + + def once(options, environ): + calls.append(options.cpus) + if len(calls) == 2: + raise KeyboardInterrupt + return real_once(options, environ) + + with mock.patch.object(bounded_run, "bounded_once", once): + code = self.run_bounded(["--measure-rows", "8,4,2"], [(1, 1000)]) + self.assertEqual(code, 1) + self.assertEqual(calls, [8, 4]) + + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" @@ -2222,6 +2376,15 @@ def test_measure_mode_reports_a_peak_and_a_budget(self): self.assertEqual(int(suggested.split()[-2]) % 256, 0) self.assertGreaterEqual(int(suggested.split()[-2]), value * 1.5) + def test_measured_rows_print_their_row_lines_in_order(self): + script = "import os; print(os.environ['BOUNDED_RUN_CPUS'])" + process = self.wrapper(["--measure-rows", "1,2", "--label", "lint"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + self.assertEqual(output.split(), ["2", "1"]) + rows = re.findall(r"^bounded-run: row label=lint cpus=(\d+) budget=\d+M peak=\d+M exact=no exit=0$", errors, re.MULTILINE) + self.assertEqual(rows, ["2", "1"], errors) + def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self): holder = self.worker("holder", "4G", hold="300") self.wait_for_event("start", "holder")