diff --git a/README.md b/README.md
index 4da74a6..d436373 100644
--- a/README.md
+++ b/README.md
@@ -32,6 +32,7 @@ It is also the faster path. Breaking the feature into independent PRs lets the m
| `fanning-out-with-worktrees` | An orchestrator dispatching parallel subagents into per-PR worktrees off a feature branch. |
| `stacking-dependent-prs` | A PR's branch is based on another open PR's branch (a linear stack). Creates, adopts, propagates through, syncs, and merges the stack with `gh stack`, in one dedicated worktree per stack. |
| `reviewing-feature-progress` | Orchestration checkpoints: between fan-out waves, and before the integration PR. |
+| `bounding-heavy-commands` | About to run a test suite, linter, build, or type check, or to dispatch subagents that will. Runs every heavy command through a memory queue that all sessions and projects on the machine share, so parallel work queues instead of freezing the machine. |
| `testing-a-feature` | Writing tests for any non-trivial change. Decides the assertion shape (black-box against the contract). |
| `testing-end-to-end` | A structurally-complete feature introduces a new user- or consumer-visible flow. Decides which flows earn an end-to-end test and what each asserts (golden path, not edge cases). |
| `writing-code-comments` | About to write, edit, or delete a comment in source code. Decides whether the comment exists and what it holds: the contract for a doc comment, and the fact that the code cannot show for an inline comment. |
@@ -57,7 +58,7 @@ flowchart TD
Shape -->|single PR| IssueOne[File one issue
feature or bug]
IssueOne --> PlanS[Write the plan
ordered tasks · dependencies]
PlanS --> Build[Implement directly
test-first · one commit per task]
- Build --> VerifyS[Verify green
tests · lint · typecheck]
+ Build --> VerifyS[Verify green
tests · lint · typecheck
each through the memory queue]
VerifyS --> PR1[Open PR → main
Fixes / Closes the issue]
Shape -->|many PRs| Epic[File an epic
+ one sub-issue per PR, linked]
@@ -67,7 +68,7 @@ flowchart TD
Wave --> Merge[Orchestrator reviews each sub-PR,
merges it, closes its sub-issue]
Merge --> Done{All sub-PRs
merged?}
Done -->|next wave| Wave
- Done -->|yes| VerifyM[Verify the integrated branch
green end to end]
+ Done -->|yes| VerifyM[Verify the integrated branch
green end to end, through the memory queue]
VerifyM --> PR2[Open the integration PR
feature → main · Closes the epic]
PR1 --> Ship([External review → act on the feedback,
comments checked for growth → merge
plan + state torn down in the same diff])
@@ -116,6 +117,8 @@ A local path also works for development: `/plugin marketplace add /path/to/featu
No further setup is required; the skills derive your repo and build commands from context. Optionally, paste [`templates/project-CLAUDE.md`](templates/project-CLAUDE.md) into your project's `CLAUDE.md` to give every session the workflow overview and the operational rules (commit conventions, safe git staging, GitHub-mutation confirmation).
+Keep project memory on to get the most from `bounding-heavy-commands`. In Claude Code that is auto memory, which is on by default. The skill saves the measured memory budget and the bounded command line of each heavy command there, so a later session starts with them. With memory off, the queue still protects the machine, but each session measures the commands again and uses the default budget for a command that it did not measure.
+
## Notes
- Intra-plugin skill references are namespaced as `feature-dev-workflow:`.
diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md
new file mode 100644
index 0000000..3e9149f
--- /dev/null
+++ b/skills/bounding-heavy-commands/SKILL.md
@@ -0,0 +1,163 @@
+---
+name: bounding-heavy-commands
+description: Use when about to run a project's test suite, linter, build, type check, or another command of that weight, when about to dispatch subagents that will run one, or when a command fails on a port already in use, a tool's own lock, or a machine that slows down or swaps while agents verify their work.
+---
+
+# bounding-heavy-commands
+
+## Overview
+
+Every heavy command an agent starts goes through the wrapper. There is no exception for a session that looks alone, for a command that looks small, or for a user who is in a hurry. Two sections say when a command runs without the wrapper: §When an instruction sends a command around the wrapper, and §When the wrapper cannot run. No other case exists.
+
+A machine freezes because of the heavy commands that run on it, not because of the number of agents. Sessions in other terminals and other projects run their own test suites and builds at the same moment, and no session can see the others. When the commands together need more memory than the machine has, it swaps until it stops responding, and that costs every session, not only the one that started the last command. The wrapper makes the commands of every session and every project on the machine take turns on its memory, so too much work shows up as a queue instead of a freeze.
+
+**Looking first does not protect the machine.** Two sessions that look at the load at the same moment both see a quiet machine, and both start. A sum of budgets against the machine's total memory does not protect it either: the sum counts your commands and no one else's. Only a reservation that every session takes before it starts can count the commands, and the wrapper is that reservation.
+
+**Violating the letter of these rules is violating their spirit.**
+
+## When to invoke
+
+- Before you run the project's test suite, linter, build, or type check, or anything that compiles, starts containers, or starts a local cluster.
+- Before you dispatch subagents that will run any of those.
+- When a command failed on a port that is already in use, or on a tool's own lock.
+- When the machine is slow or swaps and someone asks what to change.
+
+A command is heavy when the project's record says so, or when it compiles, tests, checks, generates, or installs over more than a handful of files. An install of the dependencies, a code generator, and a formatter over the whole tree are heavy. So is a commit or a push in a project whose hooks run the tests or the linter. A part of a heavy command is heavy too: one test file, one package, one target. When in doubt, it is heavy: the wrapper costs a second, a frozen machine costs every session.
+
+Skip for commands that only read (listing files, searching, version-control queries). Do not add the wrapper to the project's scripts, to its CI configuration, or to the commands that a person types: this skill is for the commands that an agent starts on a machine that it shares.
+
+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.
+
+## The wrapper
+
+```
+python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... [--measure] --
+```
+
+| 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. |
+| `--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. |
+
+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 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.
+
+## The record
+
+Budgets and command lines are facts about one machine and one user, so they live in your project memory (the notes that your harness keeps for this project between sessions), not in the repository. The record is one memory named `bounded-heavy-commands`. Your harness decides the file format. This skill decides the content.
+
+For each heavy command, record:
+
+- what it is for ("unit tests", "lint", "build")
+- the plain command
+- the full bounded command line
+- the budget, the measured peak, and the date of the measurement
+- each exclusive resource it uses
+- the flags or variables that limit the toolchain's own parallelism
+
+Then, before each heavy command, use the first case that applies:
+
+1. **Your prompt carries bounded command lines.** You are a subagent. Use them under the rule that your prompt gives with them, and run no discovery. For a heavy command that your prompt does not carry, use the wrapper with no `--memory` option.
+2. **The record exists and has 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 as written.
+3. **The record exists, and the command is not in it or is no longer correct.** Run the discovery for that command and correct the record. 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.
+
+A budget is a measurement, not a preference. Change one only when the wrapper's output shows that the peak moved, and write the new peak and date with it.
+
+A part of a recorded command (one test file, one target) uses the bounded command line of the full command, with its budget and its exclusive resources, and the narrower arguments at the end of the line. It needs no entry of its own and no measurement, because the budget of the full command is sufficient for each part of it.
+
+## 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.
+2. Find the exclusive resources: a port that a test server binds, a tool that refuses to run twice, a fixed directory that a build writes to.
+3. Find how the toolchain limits its own parallelism and memory. Write the command line so that it takes those limits from `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB`. 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:
+
+ ```
+ ... --cpus 4 -- sh -c ' "$BOUNDED_RUN_CPUS" "$@"' sh
+ ```
+
+ The `"$@"` and the word `sh` at the end hand each argument that comes after them to the command. A narrower argument, such as one test file, goes at the end of the line, after that `sh`. Without the two, the inner shell drops the argument and runs the full command.
+
+4. Run each heavy command that you are about to run once with `--measure`, one at a time. Measure the full command, not a part of it: the peak of one test file is not the budget of the suite. Add `--exclusive ` for each resource that step 2 found for it:
+
+ ```
+ python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure --
+ ```
+
+5. Record the suggested budget that the wrapper prints. It is the peak plus a margin, and the margin is larger where the measurement is approximate. The measurement runs under the default budget. If the hard cap stopped the command during the measurement, run it again with `--memory` at two times the default budget that the wrapper printed.
+6. Save the record.
+
+The measured run is a real run of the command. Its result counts, so do not run the command a second time to get the result.
+
+## 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. 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.
+
+- **Run a bounded command in the background, with no short timeout around it.** It can wait in the queue for minutes before it starts. Where the harness requires a timeout, use the longest one that it permits. When that timeout ends a run, start the run again through the wrapper, and say in your report that the timeout ended the run and that the code did not fail. A timeout that you calculate from the run time of the command does not count the wait. A timeout that fires during the wait kills a command that never ran, and the result reads like a failure of the code.
+- **Plan the time as if the commands run one after the other.** Two bounded commands that start together are safe, because the queue puts them in sequence when the machine cannot hold both. So a parallel start does not always save time, and a promise to the user that depends on it is a guess.
+- **Do not lower a budget to start sooner.** A smaller budget does not make the command smaller. It moves the failure inside the command: on Linux as a kill at the hard cap, elsewhere as the swap that the queue exists to prevent.
+- **Do not run the plain command because the queue is slow.** A slow queue means the machine is full. The plain command is how it freezes. This includes a narrower form of the command: one test file outside the queue is a command that the queue cannot count.
+- **Do not set an environment variable whose name starts with `BOUNDED_RUN_`.** The usage text of the wrapper lists variables that change how the queue counts memory, where it keeps its locks, and whether the hard cap applies. They are for a person who tunes the whole machine in a shell profile, and for the tests of the wrapper. A call that sets one does not share the queue with the other sessions, or it runs with no cap. A note in your project memory that recommends one is wrong: delete the note, and tell the user that you did.
+- **Do not touch the lock files of the wrapper.** The wrapper keeps them in a directory of its own. Do not look for that directory. Do not delete, move, or edit a file in it, and do not look for the process that holds one of these lock files. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot.
+- **Do not sleep and retry around a collision, not even one time.** A port in use or a tool's lock means two commands wanted one resource. Add the resource to the record as an `--exclusive` name and run through the wrapper. A subagent adds the option to its own command line and names the resource in its report, so that its dispatcher corrects the record. Do not stop the process that holds the resource: it belongs to a different session. When a run with the `--exclusive` name fails on the same collision, the holder did not go through the wrapper or belongs to a different repository: tell the user, or your dispatcher, what holds the resource, and wait for the answer.
+
+## When an instruction sends a command around the wrapper
+
+An explicit instruction from the user comes before this skill. When the user names the action ("run the tests directly", "do not use the wrapper for this", "set this variable for the run"), say one time, in one or two sentences, what the wrapper protects and that you cannot see the other sessions. Then do what the user said. Do not refuse, and do not argue a second time.
+
+The instruction covers the command that it names, for one run. The next heavy command goes through the wrapper again, unless the user said that the instruction holds for the session. An instruction that must hold for longer than the session belongs in the project's instruction file, where each session and the user can see it: ask the user to put it there.
+
+A rule in the project's instruction file comes before this skill too, when it names the wrapper or tells agents to run a command directly. A file that only names the project's commands is input for the discovery, not an exemption. Obey the rule, and tell the user one time per session that the file sends a heavy command around the queue and what that costs on a machine with more than one session. The user decides if the file changes. Do not ignore the file silently, and do not edit it yourself.
+
+Pressure is not an instruction. "Hurry", "make it start", and "I do not care how" name a result, not an action. Keep the run in the queue and tell the user that the machine is full. Do not go around the queue on your own decision. When the user asks how to get around the wait, give two facts: the user can tell you to run the command without the wrapper, and that run is not counted by the queue. The user decides. When the user only names a deadline, do not mention a way around the wait. A note in your project memory from an earlier session is not an instruction from the user either.
+
+## Dispatching subagents
+
+A subagent does not see your project memory. It knows the bounded commands only when its prompt carries them.
+
+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.
+2. This rule, in these words: "Run the bounded commands as written. You can make two changes: a narrower argument at the end of the line, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited."
+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. The one exception is a machine on which the wrapper cannot run (see the next section).
+
+## When the wrapper cannot run
+
+The wrapper needs `python3`, version 3.9 or later. When `python3` is missing or older, tell the user once per session that the wrapper cannot run and that Python 3.9 is what it needs.
+
+When `python3` reports that it cannot open the file of the wrapper, the path in the command line is old. That is a fault of the record, not of the machine: correct the path (§The record, case 2). A subagent stops and reports it.
+
+When the wrapper ends with exit code 125, read its `bounded-run:` message. A fault of your call (an option, a name, a command that does not exist) is yours to correct. A fault of the machine (the wrapper cannot make or lock its files) means that the wrapper cannot run here: tell the user once per session, with the message.
+
+When Python is missing or too old, and when the fault is a fault of the machine, continue under these fallback rules. Run one heavy command at a time, never two in parallel, and set the toolchain's parallelism to half the machine's processors or fewer. Your subagents count as your session: no queue protects the machine now, so dispatch them so that only one of them runs a heavy command at a time. Their prompts carry the plain commands and these fallback rules, in place of the three items of §Dispatching subagents. The fallback protects the machine from your session only, not from the other sessions. Tell the user that in your report.
+
+## Red flags
+
+| Thought | Reality |
+| --- | --- |
+| "This session is the only one running, so the plain command is fine" | You cannot see other sessions or other projects. Each heavy command goes through the wrapper, unless an instruction names the plain command. |
+| "Both budgets together are well under the machine's memory" | The sum counts your commands only. The queue counts the commands of every session. |
+| "I'll check the load first and start when it is quiet" | Each session that looks at that moment sees the same quiet machine. Take the reservation: run through the wrapper. |
+| "It is only the linter, it is small" | The record says what is heavy, not your sense of it. Not in the record, and not a part of a recorded command, means not yet measured. |
+| "I'll run just those few tests now, that fits in the free memory" | A part of a heavy command goes through the wrapper too. "It fits" is your estimate; the queue is the count. |
+| "I'll run the plain command once to check quickly" | One command outside the queue is all a freeze needs. |
+| "Running both in parallel is what makes the deadline possible" | Through the wrapper a parallel start is safe, but the queue decides if the two run together. Do not promise a time that depends on it. |
+| "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is the measured peak plus a margin. Lowering it moves the failure inside the command. |
+| "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no variable whose name starts with `BOUNDED_RUN_`. |
+| "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock files alone. |
+| "The user told me to run it directly, but the skill says no exception" | An explicit instruction from the user comes first. Say one time what the wrapper protects, then obey. |
+| "The user is waiting, the queue is too slow" | A frozen machine is slower. Tell the user that the machine is full and the command is queued. |
+| "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. |
+| "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
new file mode 100755
index 0000000..2639961
--- /dev/null
+++ b/skills/bounding-heavy-commands/scripts/bounded_run.py
@@ -0,0 +1,887 @@
+#!/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...
+
+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 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
+rest, and so do its maintainers when they look for a fault of the script.
+
+Do not set one of them for a single call. A call with its own slot size,
+reserve, or lock directory does not share the queue with the other
+sessions of the machine, and a call with no cap can take the memory of
+all of them.
+
+Tuning values, with their defaults:
+
+ 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)
+
+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_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
+ BOUNDED_RUN_NO_CAP when set, do not apply the hard cap
+"""
+from __future__ import annotations
+
+import fcntl
+import hashlib
+import math
+import os
+import random
+import re
+import shutil
+import signal
+import stat
+import subprocess
+import sys
+import threading
+import time
+from typing import Callable, Dict, List, Mapping, Optional, Sequence, Tuple
+
+try:
+ import ctypes
+except ImportError:
+ ctypes = None
+
+PREFIX = "bounded-run"
+EXIT_WRAPPER = 125
+ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE"
+SLOT_MIB = 2048
+MINIMUM_RESERVE_MIB = 2048
+POLL_SECONDS = 2.0
+MEMORY_WAIT_SECONDS = 300.0
+SAMPLE_SECONDS = 1.0
+MARGIN_EXACT = 0.25
+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..."
+
+
+class WrapperError(Exception):
+ """A failure of the wrapper, not of the command."""
+
+
+def log(message: str) -> None:
+ sys.stderr.write("%s: %s\n" % (PREFIX, message))
+ sys.stderr.flush()
+
+
+def parse_size_mib(text: str) -> int:
+ parts = re.match(r"^(\d+)([GgMm]?)$", text.strip())
+ if parts is None:
+ raise WrapperError("cannot read the size '%s'; use a form such as 6G or 4096M" % text)
+ value = int(parts.group(1))
+ if parts.group(2) in ("G", "g"):
+ value *= 1024
+ if value <= 0:
+ raise WrapperError("the size '%s' must be more than zero" % text)
+ return value
+
+
+def physical_memory_mib() -> int:
+ try:
+ return os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") // (1024 * 1024)
+ except (ValueError, OSError):
+ pass
+ try:
+ done = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=10)
+ return int(done.stdout.strip()) // (1024 * 1024)
+ except (OSError, ValueError, subprocess.TimeoutExpired) as error:
+ raise WrapperError("cannot read the memory of the machine: %s" % error)
+
+
+def _limits_upward(root: str, path: str, name: str) -> List[Tuple[int, str]]:
+ found = []
+ relative = path.strip("/")
+ while True:
+ directory = os.path.join(root, relative)
+ try:
+ with open(os.path.join(directory, name)) as handle:
+ found.append((int(handle.read().strip()), directory))
+ except (OSError, ValueError):
+ pass
+ if not relative:
+ return found
+ relative = os.path.dirname(relative)
+
+
+def _cgroup_limits(proc_root: str, cgroup_root: str) -> List[Tuple[int, str, str, str]]:
+ """Returns the memory limit in bytes of each level of the cgroup of this process, with the directory of
+ that level and the names of its use file and of the inactive file cache line in its memory.stat."""
+ try:
+ with open(os.path.join(proc_root, "self", "cgroup")) as handle:
+ text = handle.read()
+ except (OSError, ValueError):
+ return []
+ limits: List[Tuple[int, str, str, str]] = []
+ for line in text.splitlines():
+ parts = line.strip().split(":", 2)
+ if len(parts) != 3:
+ continue
+ if parts[0] == "0" and parts[1] == "":
+ for limit, directory in _limits_upward(cgroup_root, parts[2], "memory.max"):
+ limits.append((limit, directory, "memory.current", "inactive_file"))
+ elif "memory" in parts[1].split(","):
+ for limit, directory in _limits_upward(os.path.join(cgroup_root, "memory"), parts[2], "memory.limit_in_bytes"):
+ limits.append((limit, directory, "memory.usage_in_bytes", "total_inactive_file"))
+ return limits
+
+
+def cgroup_limit_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]:
+ """Returns the smallest memory limit of the cgroup of this process and of its parents, or None."""
+ limits = _cgroup_limits(proc_root, cgroup_root)
+ return min(limits)[0] // (1024 * 1024) if limits else None
+
+
+def _level_available(limit: int, directory: str, use_name: str, inactive_name: str) -> Optional[int]:
+ try:
+ with open(os.path.join(directory, use_name)) as handle:
+ use = int(handle.read().strip())
+ with open(os.path.join(directory, "memory.stat")) as handle:
+ stat_text = handle.read()
+ except (OSError, ValueError):
+ return None
+ # The kernel takes back the inactive file cache when the cgroup reaches its limit, so that cache is not use.
+ for line in stat_text.splitlines():
+ parts = line.split()
+ if len(parts) == 2 and parts[0] == inactive_name and parts[1].isdigit():
+ return max(0, limit - max(0, use - int(parts[1]))) // (1024 * 1024)
+ return None
+
+
+def cgroup_available_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]:
+ """Returns the smallest free memory of the cgroup of this process and of its parents: the limit of a
+ level less the use at that level. Returns None when the use at the smallest limit cannot be read."""
+ limits = _cgroup_limits(proc_root, cgroup_root)
+ if not limits:
+ return None
+ smallest = _level_available(*min(limits))
+ if smallest is None:
+ return None
+ others = [_level_available(*level) for level in limits]
+ return min([smallest] + [value for value in others if value is not None])
+
+
+def total_memory_mib(
+ proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup",
+ read_physical: Callable[[], int] = physical_memory_mib,
+) -> int:
+ """Returns the physical memory, or the memory limit of the cgroup of this process when that is smaller."""
+ physical = read_physical()
+ # Cgroup version 1 writes a number near 2**63 when the cgroup has no limit.
+ limit = cgroup_limit_mib(proc_root, cgroup_root)
+ return physical if limit is None else min(physical, limit)
+
+
+def default_reserve_mib(total_mib: int) -> int:
+ return max(MINIMUM_RESERVE_MIB, total_mib // 4)
+
+
+def slot_count(total_mib: int, slot_mib: int, reserve_mib: int) -> int:
+ return max(1, (total_mib - reserve_mib) // slot_mib)
+
+
+def queue_mib(total_mib: int, slot_mib: int, reserve_mib: int) -> int:
+ """Returns the most memory that the commands of the queue hold together."""
+ after_reserve = total_mib - reserve_mib
+ if after_reserve >= slot_mib:
+ return slot_count(total_mib, slot_mib, reserve_mib) * slot_mib
+ if after_reserve > 0:
+ return after_reserve
+ return max(1, min(total_mib, slot_mib))
+
+
+def slots_needed(budget_mib: int, slot_mib: int, count: int) -> int:
+ return min(count, max(1, -(-budget_mib // slot_mib)))
+
+
+def default_budget_mib(total_mib: int, slot_mib: int) -> int:
+ return max(1, min(total_mib, max(1, math.ceil(total_mib / 4 / slot_mib)) * slot_mib))
+
+
+class Settings:
+ def __init__(self, environ: Mapping[str, str], read_total: Callable[[], int] = total_memory_mib) -> None:
+ self.slot_mib = int(_number(environ, "BOUNDED_RUN_SLOT_MIB", SLOT_MIB))
+ total = environ.get("BOUNDED_RUN_TOTAL_MIB")
+ self.total_mib = int(_number(environ, "BOUNDED_RUN_TOTAL_MIB", 0)) if total else read_total()
+ self.reserve_mib = int(_number(environ, "BOUNDED_RUN_RESERVE_MIB", default_reserve_mib(self.total_mib)))
+ self.poll_seconds = _number(environ, "BOUNDED_RUN_POLL_SECONDS", POLL_SECONDS)
+ 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"))
+ 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.
+ if self.poll_seconds <= 0:
+ raise WrapperError("BOUNDED_RUN_POLL_SECONDS must be more than zero")
+ if self.sample_seconds <= 0:
+ raise WrapperError("BOUNDED_RUN_SAMPLE_SECONDS must be more than zero")
+
+
+def _number(environ: Mapping[str, str], name: str, fallback: float) -> float:
+ text = environ.get(name)
+ if text is None or text == "":
+ return fallback
+ try:
+ value = float(text)
+ except ValueError:
+ raise WrapperError("cannot read %s='%s'; use a number" % (name, text))
+ if not math.isfinite(value):
+ raise WrapperError("cannot read %s='%s'; use a number" % (name, text))
+ if value < 0:
+ raise WrapperError("%s must not be less than zero" % name)
+ return value
+
+
+def lock_directory(environ: Mapping[str, str], uid: int) -> str:
+ override = environ.get("BOUNDED_RUN_LOCK_DIR")
+ if override:
+ if not os.path.isabs(override):
+ raise WrapperError("cannot use BOUNDED_RUN_LOCK_DIR='%s'; use an absolute path" % override)
+ return override
+ runtime = environ.get("XDG_RUNTIME_DIR")
+ if runtime and os.path.isabs(runtime):
+ return os.path.join(runtime, PREFIX)
+ login_directory = "/run/user/%d" % uid
+ try:
+ if os.stat(login_directory).st_uid == uid:
+ return os.path.join(login_directory, PREFIX)
+ except OSError:
+ pass
+ return "/tmp/%s-%d" % (PREFIX, uid)
+
+
+def ensure_lock_directory(path: str, uid: int) -> None:
+ try:
+ os.makedirs(path, mode=0o700, exist_ok=True)
+ info = os.lstat(path)
+ except OSError as error:
+ raise WrapperError("cannot use the lock directory %s: %s" % (path, error))
+ if not stat.S_ISDIR(info.st_mode):
+ raise WrapperError("the lock directory %s is not a directory" % path)
+ if info.st_uid != uid:
+ raise WrapperError("the lock directory %s belongs to a different user" % path)
+ if stat.S_IMODE(info.st_mode) & 0o077:
+ try:
+ os.chmod(path, 0o700)
+ except OSError as error:
+ raise WrapperError("cannot use the lock directory %s: %s" % (path, error))
+
+
+def repository_id(directory: str) -> str:
+ root = os.path.realpath(directory)
+ try:
+ done = subprocess.run(
+ ["git", "rev-parse", "--git-common-dir"],
+ cwd=directory, capture_output=True, text=True, timeout=10,
+ env=dict(os.environ, LC_ALL="C", LANGUAGE="C"),
+ )
+ if done.returncode == 0 and done.stdout.strip():
+ root = os.path.realpath(os.path.join(directory, done.stdout.strip()))
+ elif "not a git repository" not in done.stderr:
+ # A fault of git in a worktree must not give that worktree a lock of its own.
+ lines = done.stderr.strip().splitlines()
+ raise WrapperError("cannot find the repository of %s: %s" % (directory, lines[0] if lines else "git gave no answer"))
+ except FileNotFoundError:
+ # A machine with no git has no worktrees, so the directory names the repository.
+ pass
+ except (OSError, subprocess.TimeoutExpired) as error:
+ # The directory in place of the repository gives each worktree a lock of its own.
+ raise WrapperError("cannot find the repository of %s: %s" % (directory, error))
+ return hashlib.sha256(root.encode("utf-8")).hexdigest()[:12]
+
+
+def exclusive_file_name(repository: str, name: str) -> str:
+ if re.match(r"^[A-Za-z0-9._-]+$", name) is None:
+ raise WrapperError("cannot use the name '%s'; use letters, digits, '.', '_' and '-'" % name)
+ return "exclusive-%s-%s.lock" % (repository, name)
+
+
+class Reservation:
+ def __init__(self, descriptors: Sequence[int]) -> None:
+ self.descriptors = list(descriptors)
+
+ def release(self) -> None:
+ for descriptor in self.descriptors:
+ os.close(descriptor)
+ self.descriptors = []
+
+
+def _open_lock_file(path: str) -> int:
+ try:
+ return os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
+ except OSError as error:
+ raise WrapperError("cannot open %s: %s" % (path, error.strerror if error.strerror else error))
+
+
+def _is_the_file_at(path: str, descriptor: int) -> bool:
+ try:
+ return os.path.samestat(os.stat(path), os.fstat(descriptor))
+ except OSError:
+ return False
+
+
+def _refresh(descriptor: int) -> None:
+ # A cleaner of a temporary directory deletes a file by its age, also while a lock is held on it.
+ try:
+ os.utime(descriptor)
+ except (OSError, TypeError, NotImplementedError):
+ pass
+
+
+def _lock(path: str, wait: bool) -> Optional[int]:
+ """Locks the file that the path names now. Returns None when wait is false and the lock is held."""
+ while True:
+ descriptor = _open_lock_file(path)
+ try:
+ fcntl.flock(descriptor, fcntl.LOCK_EX if wait else fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ os.close(descriptor)
+ return None
+ except OSError as error:
+ os.close(descriptor)
+ raise _lock_error(path, error)
+ except BaseException:
+ os.close(descriptor)
+ raise
+ # A file that was deleted after the open is locked by this process only: the next caller makes a new one.
+ if _is_the_file_at(path, descriptor):
+ _refresh(descriptor)
+ return descriptor
+ os.close(descriptor)
+
+
+def _try_lock(path: str) -> Optional[int]:
+ return _lock(path, wait=False)
+
+
+def _lock_error(path: str, error: OSError) -> WrapperError:
+ error_text = error.strerror if error.strerror else str(error)
+ return WrapperError("cannot lock %s: %s. The lock directory must be on a filesystem that supports file locks." % (path, error_text))
+
+
+def try_reserve(directory: str, count: int, needed: int, exclusive_files: Sequence[str]) -> Optional[Reservation]:
+ turn_path = os.path.join(directory, "reserve.lock")
+ turn = _lock(turn_path, wait=True)
+ held: List[int] = []
+ try:
+ names = list(exclusive_files) + ["slot-%03d.lock" % index for index in range(count)]
+ slots = 0
+ for position, name in enumerate(names):
+ is_slot = position >= len(exclusive_files)
+ if is_slot and slots == needed:
+ break
+ descriptor = _try_lock(os.path.join(directory, name))
+ if descriptor is None:
+ if is_slot:
+ continue
+ break
+ held.append(descriptor)
+ if is_slot:
+ slots += 1
+ if slots == needed and len(held) == needed + len(exclusive_files):
+ reservation = Reservation(held)
+ held = []
+ return reservation
+ return None
+ finally:
+ for descriptor in held:
+ os.close(descriptor)
+ os.close(turn)
+
+
+def reserve(
+ directory: str, count: int, needed: int, exclusive_files: Sequence[str], poll_seconds: float,
+ sleep: Callable[[float], None] = time.sleep,
+) -> Reservation:
+ announced = False
+ while True:
+ reservation = try_reserve(directory, count, needed, exclusive_files)
+ if reservation is not None:
+ log("holding %d of %d slot(s)" % (needed, count))
+ return reservation
+ if not announced:
+ log("waiting for %d of %d slot(s)" % (needed, count))
+ announced = True
+ sleep(poll_seconds * (0.5 + random.random()))
+
+
+def parse_meminfo(text: str) -> Optional[int]:
+ for line in text.splitlines():
+ if line.startswith("MemAvailable:"):
+ return int(line.split()[1]) // 1024
+ return None
+
+
+def parse_vm_stat(text: str) -> Optional[int]:
+ page = None
+ pages = 0
+ for line in text.splitlines():
+ size = re.search(r"page size of (\d+) bytes", line)
+ if size is not None:
+ page = int(size.group(1))
+ counted = re.match(r"^Pages (free|inactive|speculative):\s+(\d+)\.", line)
+ if counted is not None:
+ pages += int(counted.group(2))
+ if page is None:
+ return None
+ return pages * page // (1024 * 1024)
+
+
+def available_memory_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]:
+ """Returns the free memory of the machine, or the free memory of the cgroup of this process when that is smaller."""
+ try:
+ with open(os.path.join(proc_root, "meminfo")) as handle:
+ meminfo = handle.read()
+ except OSError:
+ try:
+ done = subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=10)
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ return parse_vm_stat(done.stdout)
+ found = [value for value in (parse_meminfo(meminfo), cgroup_available_mib(proc_root, cgroup_root)) if value is not None]
+ return min(found) if found else None
+
+
+def wait_for_memory(
+ budget_mib: int, limit_seconds: float, poll_seconds: float,
+ read_available: Callable[[], Optional[int]] = available_memory_mib,
+ sleep: Callable[[float], None] = time.sleep,
+) -> bool:
+ waited = 0.0
+ while True:
+ 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))
+ sleep(poll_seconds)
+ waited += poll_seconds
+
+
+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,
+ "-p", "MemoryMax=%dM" % budget_mib,
+ "-p", "MemorySwapMax=0",
+ ]
+ if oom_policy:
+ prefix += ["-p", "OOMPolicy=continue"]
+ if cpus is not None:
+ prefix += ["-p", "CPUQuota=%d%%" % (cpus * 100)]
+ return prefix + ["--"]
+
+
+def cap_usable(
+ prefix: Sequence[str], platform: str = sys.platform,
+ which: Callable[[str], Optional[str]] = shutil.which,
+ run: Callable[..., "subprocess.CompletedProcess"] = subprocess.run,
+) -> bool:
+ if not platform.startswith("linux") or which("systemd-run") is None:
+ return False
+ try:
+ done = run(list(prefix) + ["true"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return done.returncode == 0
+
+
+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."""
+ # 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)
+ return None
+
+
+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:
+ text = handle.read()
+ except OSError:
+ return None
+ for line in text.splitlines():
+ if line.startswith("0::") and line.strip().endswith("/%s.scope" % unit):
+ return cgroup_root + line.strip()[3:]
+ return None
+
+
+def cgroup_peak_mib(directory: str, names: Sequence[str] = ("memory.peak", "memory.current")) -> Optional[int]:
+ for name in names:
+ try:
+ with open(os.path.join(directory, name)) as handle:
+ return math.ceil(int(handle.read().strip()) / (1024 * 1024))
+ except (OSError, ValueError):
+ continue
+ return None
+
+
+def parse_group_rss_mib(text: str, group: int) -> Optional[int]:
+ total = 0
+ found = False
+ for line in text.splitlines():
+ parts = line.split()
+ if len(parts) == 2 and parts[0] == str(group) and parts[1].isdigit():
+ total += int(parts[1])
+ found = True
+ if not found:
+ return None
+ return math.ceil(total / 1024)
+
+
+def group_rss_mib(group: int) -> Optional[int]:
+ try:
+ done = subprocess.run(["ps", "-A", "-o", "pgid=", "-o", "rss="], capture_output=True, text=True, timeout=10)
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ return parse_group_rss_mib(done.stdout, group)
+
+
+def rusage_peak_mib(maxrss: int, platform: str = sys.platform) -> int:
+ if platform == "darwin":
+ return math.ceil(maxrss / (1024 * 1024))
+ return math.ceil(maxrss / 1024)
+
+
+def suggested_budget_mib(peak_mib: int, approximate: bool) -> int:
+ margin = MARGIN_APPROXIMATE if approximate else MARGIN_EXACT
+ return max(1, math.ceil(peak_mib * (1 + margin) / BUDGET_STEP_MIB)) * BUDGET_STEP_MIB
+
+
+class PeakTracker(threading.Thread):
+ def __init__(self, read_sample: Callable[[], Optional[int]], interval: float) -> None:
+ super().__init__(daemon=True)
+ self.read_sample = read_sample
+ self.interval = interval
+ self.peak: Optional[int] = None
+ self.done = threading.Event()
+
+ def run(self) -> None:
+ while True:
+ self.sample()
+ if self.done.wait(self.interval):
+ return
+
+ def sample(self) -> None:
+ try:
+ value = self.read_sample()
+ except Exception:
+ value = None
+ if value is not None and (self.peak is None or value > self.peak):
+ self.peak = value
+
+ def finish(self) -> Optional[int]:
+ self.done.set()
+ self.join(timeout=15)
+ return self.peak
+
+
+def exit_code_of(status: int) -> int:
+ code = os.waitstatus_to_exitcode(status)
+ if code < 0:
+ return 128 - code
+ return code
+
+
+def parent_death_signal(platform: str = sys.platform) -> Optional[Callable[[], None]]:
+ """Returns a preexec_fn that makes the kernel kill the child when this process stops, or None where no such call exists.
+
+ The kernel ties the signal to the thread that starts the child, and preexec_fn is safe only
+ while this process has no other thread: call Popen from the main thread before a tracker starts.
+ """
+ # macOS has no parent-death signal: there a command lives on after a hard kill of the wrapper.
+ if ctypes is None or not platform.startswith("linux"):
+ return None
+ try:
+ prctl = ctypes.CDLL(None, use_errno=True).prctl
+ except (OSError, AttributeError):
+ return None
+ parent = os.getpid()
+ kill = int(signal.SIGKILL)
+
+ def set_signal() -> None:
+ if prctl(PR_SET_PDEATHSIG, kill, 0, 0, 0) != 0:
+ os.write(2, ("%s: WARNING: cannot set the parent-death signal; the command lives on after a hard kill of the wrapper\n" % PREFIX).encode())
+ # A parent that stopped before the call sends no signal; the child then has a new parent.
+ if os.getppid() != parent:
+ os._exit(EXIT_WRAPPER)
+
+ return set_signal
+
+
+def _group_runs(group: int) -> bool:
+ try:
+ os.killpg(group, 0)
+ except PermissionError:
+ return True
+ except OSError:
+ return False
+ return True
+
+
+def run_command(
+ command: Sequence[str], environ: Mapping[str, str],
+ on_start: Optional[Callable[[int], None]] = None,
+) -> Tuple[int, int]:
+ """Runs the command in its own process group. Returns the exit code and ru_maxrss."""
+ received: List[int] = []
+ started: List[int] = []
+
+ def forward(signum: int, frame: object) -> None:
+ received.append(signum)
+ if started:
+ try:
+ os.killpg(started[0], signum if len(received) == 1 else signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+
+ previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)}
+ try:
+ try:
+ process = subprocess.Popen(list(command), env=dict(environ), start_new_session=True, preexec_fn=parent_death_signal())
+ except OSError as error:
+ raise WrapperError("cannot start '%s': %s" % (command[0], error))
+ started.append(process.pid)
+ try:
+ if received:
+ try:
+ os.killpg(process.pid, received[0] if len(received) == 1 else signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ if on_start is not None:
+ on_start(process.pid)
+ _, status, usage = os.wait4(process.pid, 0)
+ except BaseException:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ try:
+ os.waitpid(process.pid, 0)
+ except ChildProcessError:
+ pass
+ raise
+ process.returncode = exit_code_of(status)
+ if not received and _group_runs(process.pid):
+ log("WARNING: the command left a process that still runs; the queue does not count its memory")
+ finally:
+ for signum, handler in previous.items():
+ signal.signal(signum, handler)
+ if received:
+ return 128 + received[0], usage.ru_maxrss
+ return process.returncode, usage.ru_maxrss
+
+
+def inside_cap(
+ peak_file: str, unit: str, command: Sequence[str],
+ proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup",
+) -> int:
+ """Runs the command as a child in the cgroup of the cap, then writes the peak of that cgroup.
+
+ The cgroup exists for as long as this process is in it. Thus the peak is readable after the
+ command stops, which is not possible from outside the cgroup.
+ """
+ def keep_running(signum: int, frame: object) -> None:
+ pass
+
+ previous = {signum: signal.signal(signum, keep_running) for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)}
+ try:
+ try:
+ process = subprocess.Popen(list(command), preexec_fn=parent_death_signal())
+ except OSError as error:
+ log("cannot start '%s': %s" % (command[0], error))
+ return EXIT_WRAPPER
+ _, status = os.waitpid(process.pid, 0)
+ process.returncode = exit_code_of(status)
+ # After the kernel kills a process of the scope for memory, systemd can stop the scope with SIGTERM.
+ directory = cgroup_directory(os.getpid(), unit, proc_root, cgroup_root)
+ peak = cgroup_peak_mib(directory, names=("memory.peak",)) if directory is not None else None
+ if peak is not None:
+ try:
+ with open(peak_file, "w") as handle:
+ handle.write("%d\n" % peak)
+ except OSError:
+ pass
+ finally:
+ for signum, handler in previous.items():
+ signal.signal(signum, handler)
+ return process.returncode
+
+
+def read_peak_file(path: str) -> Optional[int]:
+ try:
+ with open(path) as handle:
+ text = handle.read().strip()
+ os.unlink(path)
+ except OSError:
+ return None
+ return int(text) if text.isdigit() else None
+
+
+class Options:
+ def __init__(self) -> None:
+ self.memory: Optional[str] = None
+ self.cpus: Optional[int] = None
+ self.exclusive: List[str] = []
+ self.measure = False
+ self.command: List[str] = []
+
+
+def parse_arguments(argv: Sequence[str]) -> Options:
+ options = Options()
+ arguments = list(argv)
+ if "--" not in arguments:
+ raise WrapperError("the '--' before the command is missing\n" + USAGE)
+ split = arguments.index("--")
+ options.command = arguments[split + 1:]
+ if not options.command:
+ raise WrapperError("the command is missing\n" + USAGE)
+ flags = arguments[:split]
+ while flags:
+ flag = flags.pop(0)
+ if flag == "--measure":
+ options.measure = True
+ continue
+ if flag not in ("--memory", "--cpus", "--exclusive"):
+ 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))
+ value = flags.pop(0)
+ if flag == "--memory":
+ options.memory = value
+ elif flag == "--exclusive":
+ if value not in options.exclusive:
+ options.exclusive.append(value)
+ 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)
+ return options
+
+
+def bounded(options: Options, environ: Mapping[str, str]) -> int:
+ settings = Settings(environ)
+ if options.memory is not None:
+ budget = parse_size_mib(options.memory)
+ else:
+ budget = default_budget_mib(settings.total_mib, settings.slot_mib)
+ command = list(options.command)
+ if shutil.which(command[0], path=environ.get("PATH")) is None:
+ raise WrapperError("cannot start '%s': the command does not exist" % command[0])
+
+ count = slot_count(settings.total_mib, settings.slot_mib, settings.reserve_mib)
+ needed = slots_needed(budget, settings.slot_mib, count)
+ if settings.reserve_mib >= settings.total_mib:
+ log("WARNING: the reserve of %d MiB leaves no memory of the %d MiB of the machine; the queue does not keep the reserve" % (settings.reserve_mib, settings.total_mib))
+ most = queue_mib(settings.total_mib, settings.slot_mib, settings.reserve_mib)
+ if budget > most:
+ log("WARNING: the budget of %d MiB is more than the %d MiB of the queue; the budget is %d MiB" % (budget, most, most))
+ budget = most
+ uid = os.getuid()
+ directory = lock_directory(environ, uid)
+ ensure_lock_directory(directory, uid)
+ repository = ""
+ if options.exclusive:
+ try:
+ repository = repository_id(os.getcwd())
+ except OSError as error:
+ raise WrapperError("cannot read the working directory for --exclusive: %s" % error)
+ 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)
+ capped = prefix is not None
+ 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, "--"]
+ command = prefix + inside + command
+ else:
+ log("no hard cap is available here; the queue and the wait for free memory are the full protection")
+
+ 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))
+
+ trackers: List[PeakTracker] = []
+
+ def start_tracker(pid: int) -> None:
+ if capped:
+ def read_sample() -> Optional[int]:
+ found = cgroup_directory(pid, unit)
+ return cgroup_peak_mib(found) if found is not None else None
+ interval = min(settings.sample_seconds, 0.5)
+ else:
+ def read_sample() -> Optional[int]:
+ return group_rss_mib(pid)
+ interval = settings.sample_seconds
+ tracker = PeakTracker(read_sample, interval)
+ tracker.start()
+ trackers.append(tracker)
+
+ reported: Optional[int] = None
+ reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds)
+ try:
+ wait_for_memory(budget, settings.memory_wait_seconds, settings.poll_seconds)
+ code, maxrss = run_command(command, child_environ, start_tracker)
+ tracked = trackers[0].finish() if trackers else None
+ finally:
+ if capped:
+ reported = read_peak_file(peak_file)
+ reservation.release()
+
+ exact = reported is not None
+ peak = max(reported or tracked or 0, rusage_peak_mib(maxrss))
+ 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")
+ if options.measure:
+ log("suggested budget %d MiB" % suggested_budget_mib(peak, not exact))
+ return code
+
+
+def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int:
+ arguments = list(sys.argv[1:] if argv is None else argv)
+ variables = os.environ if environ is None else environ
+ try:
+ if len(arguments) > 4 and arguments[0] == "--inside-cap" and arguments[3] == "--":
+ return inside_cap(arguments[1], arguments[2], arguments[4:])
+ options = parse_arguments(arguments)
+ if variables.get(ACTIVE_VARIABLE):
+ log("nested call; running the command directly")
+ try:
+ os.execvpe(options.command[0], options.command, dict(variables))
+ except OSError as error:
+ raise WrapperError("cannot start '%s': %s" % (options.command[0], error))
+ try:
+ return bounded(options, variables)
+ except KeyboardInterrupt:
+ log("interrupted while waiting")
+ return 130
+ except WrapperError as error:
+ log(str(error))
+ return EXIT_WRAPPER
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py
new file mode 100644
index 0000000..9b3aade
--- /dev/null
+++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py
@@ -0,0 +1,1842 @@
+from __future__ import annotations
+
+import errno
+import os
+import re
+import select
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+from unittest import mock
+
+SCRIPTS = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(SCRIPTS))
+
+import bounded_run # noqa: E402
+
+WRAPPER = str(SCRIPTS / "bounded_run.py")
+
+# Appends one event line to the file in EVENTS, holds, then appends the end event.
+# The hold stops after HOLD seconds, or when the file in RELEASE exists.
+WORKER = (
+ "import os, sys, time\n"
+ "def event(kind):\n"
+ " descriptor = os.open(os.environ['EVENTS'], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)\n"
+ " os.write(descriptor, ('%s %s %d\\n' % (kind, sys.argv[1], os.getpid())).encode())\n"
+ " os.close(descriptor)\n"
+ "event('start')\n"
+ "release = os.environ.get('RELEASE')\n"
+ "deadline = time.time() + float(os.environ.get('HOLD', '0.3'))\n"
+ "while time.time() < deadline and not (release and os.path.exists(release)):\n"
+ " time.sleep(0.02)\n"
+ "event('end')\n"
+)
+
+
+class UsageTextTest(unittest.TestCase):
+ def test_says_who_sets_the_environment_variables(self):
+ self.assertIn(
+ "A normal call sets none of the environment variables below.",
+ bounded_run.__doc__,
+ )
+
+ def test_names_the_risk_of_a_variable_for_a_single_call(self):
+ text = " ".join(bounded_run.__doc__.split())
+ self.assertIn(
+ "Do not set one of them for a single call. A call with its own slot size, reserve, or lock "
+ "directory does not share the queue with the other sessions of the machine, and a call with "
+ "no cap can take the memory of all of them.",
+ text,
+ )
+
+ def test_says_who_the_test_values_are_for(self):
+ text = " ".join(bounded_run.__doc__.split())
+ self.assertIn("The tests of this script set the rest, and so do its maintainers when they look for a fault of the script.", text)
+ self.assertIn("Values for the tests of this script, and for its maintainers:", text)
+ self.assertNotIn("diagnosis", text)
+
+
+class SizeTest(unittest.TestCase):
+ def test_reads_gibibytes(self):
+ self.assertEqual(bounded_run.parse_size_mib("6G"), 6144)
+
+ def test_reads_mebibytes(self):
+ self.assertEqual(bounded_run.parse_size_mib("4096M"), 4096)
+
+ def test_reads_a_number_without_a_unit_as_mebibytes(self):
+ self.assertEqual(bounded_run.parse_size_mib("512"), 512)
+
+ def test_reads_a_lower_case_unit(self):
+ self.assertEqual(bounded_run.parse_size_mib("2g"), 2048)
+
+ def test_rejects_text_that_is_not_a_size(self):
+ for text in ("", "six", "6GB", "-1G", "1.5G", "0"):
+ with self.subTest(text=text):
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.parse_size_mib(text)
+
+
+class SlotCountTest(unittest.TestCase):
+ def test_divides_the_memory_after_the_reserve(self):
+ self.assertEqual(bounded_run.slot_count(32768, 2048, 8192), 12)
+
+ def test_gives_one_slot_on_a_small_machine(self):
+ self.assertEqual(bounded_run.slot_count(2048, 2048, 2048), 1)
+
+ def test_the_queue_holds_its_slots_when_the_reserve_leaves_one_or_more(self):
+ self.assertEqual(bounded_run.queue_mib(32768, 2048, 8192), 24576)
+
+ def test_the_queue_keeps_the_reserve_on_a_machine_with_less_than_one_slot_after_it(self):
+ self.assertEqual(bounded_run.queue_mib(3072, 2048, 2048), 1024)
+
+ def test_the_queue_has_the_memory_of_the_machine_when_the_reserve_leaves_nothing(self):
+ self.assertEqual(bounded_run.queue_mib(1024, 2048, 2048), 1024)
+ self.assertEqual(bounded_run.queue_mib(4096, 2048, 4096), 2048)
+
+ def test_default_reserve_is_a_quarter_with_a_minimum(self):
+ self.assertEqual(bounded_run.default_reserve_mib(32768), 8192)
+ self.assertEqual(bounded_run.default_reserve_mib(4096), 2048)
+
+ def test_a_budget_takes_the_slots_that_cover_it(self):
+ self.assertEqual(bounded_run.slots_needed(6144, 2048, 12), 3)
+ self.assertEqual(bounded_run.slots_needed(6145, 2048, 12), 4)
+ self.assertEqual(bounded_run.slots_needed(100, 2048, 12), 1)
+
+ def test_a_budget_too_large_for_a_float_takes_all_slots(self):
+ self.assertEqual(bounded_run.slots_needed(10 ** 400, 2048, 12), 12)
+
+ def test_a_budget_larger_than_the_queue_takes_all_slots(self):
+ self.assertEqual(bounded_run.slots_needed(99999, 2048, 3), 3)
+
+ def test_default_budget_is_a_quarter_in_full_slots(self):
+ self.assertEqual(bounded_run.default_budget_mib(32768, 2048), 8192)
+ self.assertEqual(bounded_run.default_budget_mib(6000, 2048), 2048)
+
+ def test_default_budget_is_never_zero(self):
+ self.assertEqual(bounded_run.default_budget_mib(0, 2048), 1)
+
+ def test_default_budget_is_never_more_than_the_total(self):
+ self.assertEqual(bounded_run.default_budget_mib(1024, 2048), 1024)
+ self.assertEqual(bounded_run.default_budget_mib(2048, 2048), 2048)
+
+ def test_total_memory_of_this_machine_is_positive(self):
+ self.assertGreater(bounded_run.total_memory_mib(), 0)
+
+ def test_a_physical_memory_that_cannot_be_read_is_reported(self):
+ failures = (
+ FileNotFoundError(errno.ENOENT, "No such file or directory"),
+ subprocess.TimeoutExpired("sysctl", 10),
+ subprocess.CompletedProcess(["sysctl"], 1, stdout=""),
+ )
+ for failure in failures:
+ with self.subTest(failure=failure):
+ run = mock.Mock(side_effect=failure) if isinstance(failure, Exception) else mock.Mock(return_value=failure)
+ with mock.patch.object(bounded_run.os, "sysconf", side_effect=ValueError("unknown")), \
+ mock.patch.object(bounded_run.subprocess, "run", run):
+ with self.assertRaises(bounded_run.WrapperError) as caught:
+ bounded_run.physical_memory_mib()
+ self.assertIn("cannot read the memory of the machine", str(caught.exception))
+
+
+class CgroupLimitTest(unittest.TestCase):
+ """Gives total_memory_mib a /proc and a cgroup filesystem in a temporary directory, and 16 GiB of physical memory."""
+
+ def setUp(self):
+ self.base = tempfile.TemporaryDirectory()
+ self.addCleanup(self.base.cleanup)
+ self.proc = os.path.join(self.base.name, "proc")
+ self.cgroups = os.path.join(self.base.name, "cgroups")
+ os.makedirs(os.path.join(self.proc, "self"))
+ os.makedirs(self.cgroups)
+
+ def membership(self, text):
+ Path(self.proc, "self", "cgroup").write_text(text)
+
+ def limit(self, relative, name, value):
+ directory = os.path.join(self.cgroups, relative)
+ os.makedirs(directory, exist_ok=True)
+ Path(directory, name).write_text(value + "\n")
+
+ def total(self):
+ return bounded_run.total_memory_mib(proc_root=self.proc, cgroup_root=self.cgroups, read_physical=lambda: 16384)
+
+ def test_a_limit_in_the_cgroup_of_the_process(self):
+ self.membership("0::/user.slice/unit-1.scope\n")
+ self.limit("user.slice/unit-1.scope", "memory.max", str(6 * 1024 ** 3))
+ self.assertEqual(self.total(), 6144)
+
+ def test_a_limit_in_a_parent_only(self):
+ self.membership("0::/user.slice/unit-1.scope\n")
+ self.limit("user.slice/unit-1.scope", "memory.max", "max")
+ self.limit("user.slice", "memory.max", str(4 * 1024 ** 3))
+ self.assertEqual(self.total(), 4096)
+
+ def test_the_smallest_limit_wins(self):
+ self.membership("0::/user.slice/unit-1.scope\n")
+ self.limit("user.slice/unit-1.scope", "memory.max", str(8 * 1024 ** 3))
+ self.limit("user.slice", "memory.max", str(3 * 1024 ** 3))
+ self.limit("", "memory.max", str(5 * 1024 ** 3))
+ self.assertEqual(self.total(), 3072)
+
+ def test_max_on_each_level_is_no_limit(self):
+ self.membership("0::/user.slice/unit-1.scope\n")
+ for relative in ("user.slice/unit-1.scope", "user.slice", ""):
+ self.limit(relative, "memory.max", "max")
+ self.assertEqual(self.total(), 16384)
+
+ def test_no_cgroup_files_is_no_limit(self):
+ self.assertEqual(self.total(), 16384)
+
+ def test_a_membership_without_limit_files_is_no_limit(self):
+ self.membership("0::/user.slice/unit-1.scope\n")
+ self.assertEqual(self.total(), 16384)
+
+ def test_a_limit_larger_than_the_physical_memory_is_no_limit(self):
+ self.membership("0::/\n")
+ self.limit("", "memory.max", str(64 * 1024 ** 3))
+ self.assertEqual(self.total(), 16384)
+
+ def test_a_file_that_is_not_readable_is_no_limit(self):
+ self.membership("0::/user.slice\n")
+ os.makedirs(os.path.join(self.cgroups, "user.slice", "memory.max"))
+ self.assertEqual(self.total(), 16384)
+
+ def test_cgroup_version_1(self):
+ self.membership("12:cpu,cpuacct:/user.slice\n5:memory:/user.slice/unit-1.scope\n0::/user.slice/unit-1.scope\n")
+ self.limit("memory/user.slice/unit-1.scope", "memory.limit_in_bytes", "9223372036854771712")
+ self.limit("memory/user.slice", "memory.limit_in_bytes", str(2 * 1024 ** 3))
+ self.assertEqual(self.total(), 2048)
+
+ def test_cgroup_version_1_without_a_limit(self):
+ self.membership("5:memory:/user.slice\n")
+ self.limit("memory/user.slice", "memory.limit_in_bytes", "9223372036854771712")
+ self.limit("memory", "memory.limit_in_bytes", "9223372036854771712")
+ self.assertEqual(self.total(), 16384)
+
+
+class SettingsTest(unittest.TestCase):
+ def test_defaults(self):
+ settings = bounded_run.Settings({}, read_total=lambda: 16384)
+ self.assertEqual(settings.slot_mib, 2048)
+ self.assertEqual(settings.total_mib, 16384)
+ self.assertEqual(settings.reserve_mib, 4096)
+ self.assertEqual(settings.poll_seconds, 2.0)
+ self.assertEqual(settings.memory_wait_seconds, 300.0)
+ self.assertFalse(settings.no_cap)
+
+ def test_overrides(self):
+ settings = bounded_run.Settings({
+ "BOUNDED_RUN_SLOT_MIB": "1024", "BOUNDED_RUN_TOTAL_MIB": "4096",
+ "BOUNDED_RUN_RESERVE_MIB": "1024", "BOUNDED_RUN_POLL_SECONDS": "0.05",
+ "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", "BOUNDED_RUN_NO_CAP": "1",
+ }, read_total=lambda: 1)
+ self.assertEqual((settings.slot_mib, settings.total_mib, settings.reserve_mib), (1024, 4096, 1024))
+ self.assertEqual((settings.poll_seconds, settings.memory_wait_seconds), (0.05, 0.0))
+ self.assertTrue(settings.no_cap)
+
+ def test_a_set_total_reads_nothing_of_the_machine(self):
+ with mock.patch("builtins.open", side_effect=AssertionError("open")), \
+ mock.patch.object(bounded_run.os, "sysconf", side_effect=AssertionError("sysconf")), \
+ mock.patch.object(bounded_run.subprocess, "run", side_effect=AssertionError("run")):
+ settings = bounded_run.Settings({"BOUNDED_RUN_TOTAL_MIB": "4096"})
+ self.assertEqual(settings.total_mib, 4096)
+
+ def test_rejects_an_interval_of_zero(self):
+ for name in ("BOUNDED_RUN_POLL_SECONDS", "BOUNDED_RUN_SAMPLE_SECONDS"):
+ with self.subTest(name=name):
+ with self.assertRaisesRegex(bounded_run.WrapperError, name + " must be more than zero"):
+ bounded_run.Settings({name: "0"}, read_total=lambda: 1)
+
+ def test_rejects_a_value_that_is_not_a_number(self):
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.Settings({"BOUNDED_RUN_POLL_SECONDS": "fast"}, read_total=lambda: 1)
+
+ def test_rejects_a_value_that_is_not_finite(self):
+ for name in ("BOUNDED_RUN_SLOT_MIB", "BOUNDED_RUN_TOTAL_MIB", "BOUNDED_RUN_POLL_SECONDS"):
+ for text in ("nan", "inf", "1e400"):
+ with self.subTest(name=name, text=text):
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.Settings({name: text}, read_total=lambda: 16384)
+
+
+class LockDirectoryTest(unittest.TestCase):
+ def test_override_wins(self):
+ environ = {"BOUNDED_RUN_LOCK_DIR": "/x/locks", "XDG_RUNTIME_DIR": "/run/user/7"}
+ self.assertEqual(bounded_run.lock_directory(environ, 7), "/x/locks")
+
+ def test_rejects_an_override_that_is_not_an_absolute_path(self):
+ for value in ("locks", "./locks", "../x/locks"):
+ with self.subTest(value=value):
+ with self.assertRaises(bounded_run.WrapperError) as caught:
+ bounded_run.lock_directory({"BOUNDED_RUN_LOCK_DIR": value}, 7)
+ self.assertIn("BOUNDED_RUN_LOCK_DIR", str(caught.exception))
+ self.assertIn("'%s'" % value, str(caught.exception))
+
+ def test_uses_the_runtime_directory(self):
+ self.assertEqual(bounded_run.lock_directory({"XDG_RUNTIME_DIR": "/run/user/7"}, 7), "/run/user/7/bounded-run")
+
+ def test_ignores_a_runtime_directory_that_is_not_an_absolute_path(self):
+ self.assertEqual(bounded_run.lock_directory({"XDG_RUNTIME_DIR": "run"}, 999999999), "/tmp/bounded-run-999999999")
+
+ def test_falls_back_to_a_directory_for_the_user(self):
+ self.assertEqual(bounded_run.lock_directory({}, 999999999), "/tmp/bounded-run-999999999")
+
+ def test_does_not_depend_on_TMPDIR(self):
+ self.assertEqual(bounded_run.lock_directory({"TMPDIR": "/elsewhere"}, 999999999), "/tmp/bounded-run-999999999")
+
+ def test_creates_the_directory_for_the_user_only(self):
+ with tempfile.TemporaryDirectory() as base:
+ path = os.path.join(base, "locks")
+ bounded_run.ensure_lock_directory(path, os.getuid())
+ self.assertEqual(os.stat(path).st_mode & 0o777, 0o700)
+
+ def test_closes_a_directory_that_other_users_can_read(self):
+ with tempfile.TemporaryDirectory() as base:
+ path = os.path.join(base, "locks")
+ os.mkdir(path, 0o755)
+ bounded_run.ensure_lock_directory(path, os.getuid())
+ self.assertEqual(os.stat(path).st_mode & 0o777, 0o700)
+
+ def test_a_directory_that_cannot_be_closed_is_reported(self):
+ with tempfile.TemporaryDirectory() as base:
+ path = os.path.join(base, "locks")
+ os.mkdir(path, 0o755)
+ error = PermissionError(errno.EPERM, "Operation not permitted")
+ with mock.patch.object(bounded_run.os, "chmod", side_effect=error):
+ with self.assertRaises(bounded_run.WrapperError) as caught:
+ bounded_run.ensure_lock_directory(path, os.getuid())
+ self.assertIn(path, str(caught.exception))
+ self.assertIn("Operation not permitted", str(caught.exception))
+
+ def test_rejects_a_directory_of_a_different_user(self):
+ with tempfile.TemporaryDirectory() as base:
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.ensure_lock_directory(base, os.getuid() + 1)
+
+ def test_rejects_a_symbolic_link(self):
+ with tempfile.TemporaryDirectory() as base:
+ link = os.path.join(base, "link")
+ os.symlink(base, link)
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.ensure_lock_directory(link, os.getuid())
+
+
+class ReserveTest(unittest.TestCase):
+ def setUp(self):
+ patcher = mock.patch.object(bounded_run, "log")
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.base = tempfile.TemporaryDirectory()
+ self.addCleanup(self.base.cleanup)
+ self.directory = self.base.name
+
+ def test_takes_the_slots_that_it_needs(self):
+ reservation = bounded_run.try_reserve(self.directory, 3, 2, [])
+ self.addCleanup(reservation.release)
+ self.assertEqual(len(reservation.descriptors), 2)
+
+ def test_gives_nothing_when_too_few_slots_are_free(self):
+ first = bounded_run.try_reserve(self.directory, 3, 2, [])
+ self.addCleanup(first.release)
+ self.assertIsNone(bounded_run.try_reserve(self.directory, 3, 2, []))
+
+ def test_holds_no_slot_after_a_failed_try(self):
+ first = bounded_run.try_reserve(self.directory, 3, 2, [])
+ self.addCleanup(first.release)
+ self.assertIsNone(bounded_run.try_reserve(self.directory, 3, 2, []))
+ third = bounded_run.try_reserve(self.directory, 3, 1, [])
+ self.assertIsNotNone(third)
+ third.release()
+
+ def test_release_frees_the_slots(self):
+ first = bounded_run.try_reserve(self.directory, 2, 2, [])
+ first.release()
+ second = bounded_run.try_reserve(self.directory, 2, 2, [])
+ self.assertIsNotNone(second)
+ second.release()
+
+ def test_an_exclusive_lock_blocks_the_same_name(self):
+ first = bounded_run.try_reserve(self.directory, 4, 1, ["exclusive-abc-port.lock"])
+ self.addCleanup(first.release)
+ self.assertIsNone(bounded_run.try_reserve(self.directory, 4, 1, ["exclusive-abc-port.lock"]))
+
+ def test_a_blocked_exclusive_lock_holds_no_slot(self):
+ first = bounded_run.try_reserve(self.directory, 2, 1, ["exclusive-abc-port.lock"])
+ self.addCleanup(first.release)
+ self.assertIsNone(bounded_run.try_reserve(self.directory, 2, 1, ["exclusive-abc-port.lock"]))
+ other = bounded_run.try_reserve(self.directory, 2, 1, [])
+ self.assertIsNotNone(other)
+ other.release()
+
+ def test_a_different_name_does_not_block(self):
+ first = bounded_run.try_reserve(self.directory, 4, 1, ["exclusive-abc-port.lock"])
+ self.addCleanup(first.release)
+ second = bounded_run.try_reserve(self.directory, 4, 1, ["exclusive-abc-tool.lock"])
+ self.assertIsNotNone(second)
+ second.release()
+
+ def test_the_descriptors_are_not_inheritable(self):
+ reservation = bounded_run.try_reserve(self.directory, 2, 2, ["exclusive-abc-port.lock"])
+ self.addCleanup(reservation.release)
+ for descriptor in reservation.descriptors:
+ self.assertFalse(os.get_inheritable(descriptor))
+
+ def test_reserve_tries_again_until_the_slots_are_free(self):
+ first = bounded_run.try_reserve(self.directory, 1, 1, [])
+ sleeps = []
+
+ def sleep(seconds):
+ sleeps.append(seconds)
+ if len(sleeps) == 2:
+ first.release()
+
+ second = bounded_run.reserve(self.directory, 1, 1, [], 0.2, sleep=sleep)
+ self.addCleanup(second.release)
+ self.assertEqual(len(sleeps), 2)
+ for seconds in sleeps:
+ self.assertGreaterEqual(seconds, 0.1)
+ self.assertLess(seconds, 0.3)
+
+ def test_a_lock_error_that_is_not_a_busy_lock_is_reported(self):
+ with mock.patch.object(bounded_run.fcntl, "flock") as mock_flock:
+ def flock_side_effect(fd, flags):
+ # Call the real flock for the turn lock, raise ENOLCK for slot files
+ if flags & bounded_run.fcntl.LOCK_EX and not (flags & bounded_run.fcntl.LOCK_NB):
+ # This is the turn lock (blocking), allow it
+ return None
+ # This is a slot lock (non-blocking), fail with ENOLCK
+ raise OSError(errno.ENOLCK, "No locks available")
+
+ mock_flock.side_effect = flock_side_effect
+ with self.assertRaises(bounded_run.WrapperError) as cm:
+ bounded_run.try_reserve(self.directory, 1, 1, [])
+ self.assertIn("cannot lock", str(cm.exception))
+ self.assertIn("No locks available", str(cm.exception))
+
+ def test_a_lock_error_of_the_turn_file_is_reported(self):
+ with mock.patch.object(bounded_run.fcntl, "flock", side_effect=OSError(errno.ENOLCK, "No locks available")):
+ with self.assertRaises(bounded_run.WrapperError) as caught:
+ bounded_run.try_reserve(self.directory, 1, 1, [])
+ self.assertIn("cannot lock", str(caught.exception))
+ self.assertIn("reserve.lock", str(caught.exception))
+ self.assertIn("No locks available", str(caught.exception))
+
+ def test_a_lock_error_leaves_no_slot_held(self):
+ # Prove that when try_reserve fails mid-way, all locks it took are released.
+ # Wrap os.open to track fd -> path mapping, then use it in a flock stub.
+ fd_to_path = {}
+ real_os_open = os.open
+
+ def tracked_open(path, *args, **kwargs):
+ fd = real_os_open(path, *args, **kwargs)
+ fd_to_path[fd] = path
+ return fd
+
+ # flock will count calls and fail on the second slot file.
+ flock_calls_per_file = {}
+ real_flock = bounded_run.fcntl.flock
+
+ def counting_flock(fd, flags):
+ path = fd_to_path.get(fd, "")
+ if path not in flock_calls_per_file:
+ flock_calls_per_file[path] = 0
+ flock_calls_per_file[path] += 1
+
+ # Allow the turn lock and first slot to succeed.
+ if "reserve.lock" in path or "slot-000.lock" in path:
+ return real_flock(fd, flags)
+
+ # Fail on the second slot with ENOLCK.
+ if "slot-001.lock" in path:
+ raise OSError(errno.ENOLCK, "No locks available")
+
+ # Any other file succeeds.
+ return real_flock(fd, flags)
+
+ with mock.patch.object(os, "open", tracked_open):
+ with mock.patch.object(bounded_run.fcntl, "flock", counting_flock):
+ # Call try_reserve for 2 slots; it should fail after locking slot-000.
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.try_reserve(self.directory, 2, 2, [])
+
+ # Now call try_reserve again with real functions (no patches).
+ # If the first slot was not released, this will fail to get 2 slots.
+ second_try = bounded_run.try_reserve(self.directory, 2, 2, [])
+ self.assertIsNotNone(second_try)
+ self.addCleanup(second_try.release)
+ self.assertEqual(len(second_try.descriptors), 2)
+
+ def test_a_slot_file_that_cannot_be_opened_is_reported(self):
+ os.mkdir(os.path.join(self.directory, "slot-000.lock"))
+ with self.assertRaises(bounded_run.WrapperError) as caught:
+ bounded_run.try_reserve(self.directory, 1, 1, [])
+ self.assertIn("slot-000.lock", str(caught.exception))
+ self.assertIn(os.strerror(errno.EISDIR), str(caught.exception))
+
+ def test_a_turn_file_that_cannot_be_opened_is_reported(self):
+ os.mkdir(os.path.join(self.directory, "reserve.lock"))
+ with self.assertRaises(bounded_run.WrapperError) as caught:
+ bounded_run.try_reserve(self.directory, 1, 1, [])
+ self.assertIn("reserve.lock", str(caught.exception))
+ self.assertIn(os.strerror(errno.EISDIR), str(caught.exception))
+
+ def test_an_open_error_leaves_no_slot_held(self):
+ blocked = os.path.join(self.directory, "slot-001.lock")
+ os.mkdir(blocked)
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.try_reserve(self.directory, 2, 2, ["exclusive-abc-port.lock"])
+ os.rmdir(blocked)
+ second = bounded_run.try_reserve(self.directory, 2, 2, ["exclusive-abc-port.lock"])
+ self.assertIsNotNone(second, "a slot or the exclusive lock is still held")
+ second.release()
+
+ def test_the_turn_lock_is_free_while_the_wrapper_waits(self):
+ # Hold all slots so reserve has to wait
+ blocker = bounded_run.try_reserve(self.directory, 1, 1, [])
+ self.addCleanup(blocker.release)
+
+ turn_lock_acquired = []
+
+ def sleep_and_check(seconds):
+ # Try to acquire the turn lock while reserve is waiting
+ turn_path = os.path.join(self.directory, "reserve.lock")
+ turn_fd = os.open(turn_path, os.O_RDWR | os.O_CREAT, 0o600)
+ try:
+ import fcntl
+ fcntl.flock(turn_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ turn_lock_acquired.append(True)
+ except OSError:
+ turn_lock_acquired.append(False)
+ finally:
+ os.close(turn_fd)
+ # Release the blocker so reserve can succeed
+ blocker.release()
+
+ reservation = bounded_run.reserve(self.directory, 1, 1, [], 0.2, sleep=sleep_and_check)
+ self.addCleanup(reservation.release)
+ self.assertTrue(turn_lock_acquired[0], "turn lock should be free while reserve waits")
+
+
+class LockFileTest(unittest.TestCase):
+ def setUp(self):
+ self.base = tempfile.TemporaryDirectory()
+ self.addCleanup(self.base.cleanup)
+ self.path = os.path.join(self.base.name, "slot-000.lock")
+
+ def test_a_file_that_was_deleted_before_the_lock_is_not_the_lock(self):
+ real_open = bounded_run._open_lock_file
+ calls = []
+
+ def open_then_delete(path):
+ descriptor = real_open(path)
+ calls.append(descriptor)
+ if len(calls) == 1:
+ os.unlink(path)
+ return descriptor
+
+ with mock.patch.object(bounded_run, "_open_lock_file", open_then_delete):
+ descriptor = bounded_run._try_lock(self.path)
+ self.addCleanup(os.close, descriptor)
+ self.assertEqual(len(calls), 2)
+ self.assertTrue(os.path.samestat(os.stat(self.path), os.fstat(descriptor)))
+
+ def test_a_lock_makes_the_file_new_for_a_cleaner_of_old_files(self):
+ Path(self.path).write_text("")
+ os.utime(self.path, (1000, 1000))
+ descriptor = bounded_run._try_lock(self.path)
+ self.addCleanup(os.close, descriptor)
+ self.assertGreater(os.stat(self.path).st_mtime, time.time() - 60)
+ self.assertGreater(os.stat(self.path).st_atime, time.time() - 60)
+
+ def test_the_turn_lock_is_not_a_file_that_was_deleted_before_the_lock(self):
+ real_open = bounded_run._open_lock_file
+ turn_path = os.path.join(self.base.name, "reserve.lock")
+ opened = []
+
+ def open_then_delete(path):
+ descriptor = real_open(path)
+ if path == turn_path:
+ opened.append(descriptor)
+ if len(opened) == 1:
+ os.unlink(path)
+ return descriptor
+
+ with mock.patch.object(bounded_run, "_open_lock_file", open_then_delete):
+ reservation = bounded_run.try_reserve(self.base.name, 1, 1, [])
+ self.addCleanup(reservation.release)
+ self.assertEqual(len(opened), 2)
+
+
+class ExclusiveNameTest(unittest.TestCase):
+ def test_name_holds_the_repository_and_the_resource(self):
+ self.assertEqual(bounded_run.exclusive_file_name("abc123", "port-8080"), "exclusive-abc123-port-8080.lock")
+
+ def test_rejects_a_name_with_a_path(self):
+ for name in ("../x", "a/b", "", "a b"):
+ with self.subTest(name=name):
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.exclusive_file_name("abc123", name)
+
+ def test_worktrees_of_one_repository_have_the_same_id(self):
+ with tempfile.TemporaryDirectory() as base:
+ main = os.path.join(base, "main")
+ other = os.path.join(base, "other")
+ os.mkdir(main)
+ git = ["git", "-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false"]
+ subprocess.run(git + ["init", "--quiet", main], check=True)
+ subprocess.run(git + ["-C", main, "commit", "--quiet", "--allow-empty", "-m", "first"], check=True)
+ subprocess.run(git + ["-C", main, "worktree", "add", "--quiet", "--detach", other], check=True)
+ self.assertEqual(bounded_run.repository_id(main), bounded_run.repository_id(other))
+
+ def test_a_git_call_that_takes_too_long_gives_an_error(self):
+ slow = subprocess.TimeoutExpired(["git"], 10)
+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(bounded_run.subprocess, "run", side_effect=slow):
+ with self.assertRaisesRegex(bounded_run.WrapperError, "cannot find the repository of"):
+ bounded_run.repository_id(directory)
+
+ def test_a_git_fault_other_than_no_repository_gives_an_error(self):
+ done = subprocess.CompletedProcess(["git"], 128, "", "fatal: detected dubious ownership in repository at '/x'\n")
+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(bounded_run.subprocess, "run", return_value=done):
+ with self.assertRaisesRegex(bounded_run.WrapperError, "cannot find the repository of .*dubious ownership"):
+ bounded_run.repository_id(directory)
+
+ def test_git_answers_in_the_language_that_the_wrapper_reads(self):
+ done = subprocess.CompletedProcess(["git"], 128, "", "fatal: not a git repository (or any of the parent directories): .git\n")
+ with tempfile.TemporaryDirectory() as directory, mock.patch.object(bounded_run.subprocess, "run", return_value=done) as run:
+ bounded_run.repository_id(directory)
+ self.assertEqual(run.call_args.kwargs["env"]["LC_ALL"], "C")
+
+ def test_a_machine_with_no_git_uses_the_directory(self):
+ with tempfile.TemporaryDirectory() as directory:
+ with mock.patch.object(bounded_run.subprocess, "run", side_effect=FileNotFoundError("git")):
+ without = bounded_run.repository_id(directory)
+ self.assertEqual(without, bounded_run.repository_id(directory))
+
+ def test_two_directories_have_different_ids(self):
+ with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
+ self.assertNotEqual(bounded_run.repository_id(first), bounded_run.repository_id(second))
+
+
+class MemoryReadTest(unittest.TestCase):
+ def test_reads_the_available_memory_of_meminfo(self):
+ text = "MemTotal: 32000000 kB\nMemFree: 1000000 kB\nMemAvailable: 8388608 kB\n"
+ self.assertEqual(bounded_run.parse_meminfo(text), 8192)
+
+ def test_meminfo_without_the_line_gives_nothing(self):
+ self.assertIsNone(bounded_run.parse_meminfo("MemTotal: 1 kB\n"))
+
+ def test_reads_the_pages_of_vm_stat(self):
+ text = (
+ "Mach Virtual Memory Statistics: (page size of 16384 bytes)\n"
+ "Pages free: 10000.\n"
+ "Pages active: 900000.\n"
+ "Pages inactive: 20000.\n"
+ "Pages speculative: 2000.\n"
+ "Pages wired down: 100000.\n"
+ )
+ self.assertEqual(bounded_run.parse_vm_stat(text), 32000 * 16384 // (1024 * 1024))
+
+ def test_vm_stat_without_a_page_size_gives_nothing(self):
+ self.assertIsNone(bounded_run.parse_vm_stat("Pages free: 10.\n"))
+
+
+class CgroupFreeMemoryTest(unittest.TestCase):
+ """Gives available_memory_mib a /proc with 16 GiB free and a cgroup filesystem in a temporary directory."""
+
+ def setUp(self):
+ self.base = tempfile.TemporaryDirectory()
+ self.addCleanup(self.base.cleanup)
+ self.proc = os.path.join(self.base.name, "proc")
+ self.cgroups = os.path.join(self.base.name, "cgroups")
+ os.makedirs(os.path.join(self.proc, "self"))
+ os.makedirs(self.cgroups)
+ Path(self.proc, "meminfo").write_text("MemTotal: 33554432 kB\nMemAvailable: 16777216 kB\n")
+
+ def membership(self, text):
+ Path(self.proc, "self", "cgroup").write_text(text)
+
+ def write(self, relative, name, value):
+ directory = os.path.join(self.cgroups, relative)
+ os.makedirs(directory, exist_ok=True)
+ Path(directory, name).write_text(value + "\n")
+
+ def available(self):
+ return bounded_run.available_memory_mib(proc_root=self.proc, cgroup_root=self.cgroups)
+
+ def test_a_cgroup_that_is_nearly_full_on_a_free_host(self):
+ self.membership("0::/container\n")
+ self.write("container", "memory.max", str(4096 * 1024 ** 2))
+ self.write("container", "memory.current", str(4000 * 1024 ** 2))
+ self.write("container", "memory.stat", "anon 1\ninactive_file %d\nactive_file 5\n" % (100 * 1024 ** 2))
+ self.assertEqual(self.available(), 196)
+
+ def test_a_cgroup_without_a_limit_gives_the_free_memory_of_the_host(self):
+ self.membership("0::/container\n")
+ self.write("container", "memory.max", "max")
+ self.write("container", "memory.current", str(4000 * 1024 ** 2))
+ self.write("container", "memory.stat", "inactive_file 0\n")
+ self.assertEqual(self.available(), 16384)
+
+ def test_a_cgroup_whose_use_cannot_be_read_gives_the_free_memory_of_the_host(self):
+ cases = {
+ "no files of use": {},
+ "no memory.stat": {"memory.current": str(4000 * 1024 ** 2)},
+ "no memory.current": {"memory.stat": "inactive_file 0\n"},
+ "no inactive_file line": {"memory.current": str(4000 * 1024 ** 2), "memory.stat": "anon 1\n"},
+ "not a number": {"memory.current": "many", "memory.stat": "inactive_file 0\n"},
+ }
+ for name, files in cases.items():
+ with self.subTest(name):
+ shutil.rmtree(self.cgroups)
+ self.membership("0::/container\n")
+ self.write("container", "memory.max", str(4096 * 1024 ** 2))
+ for file_name, text in files.items():
+ self.write("container", file_name, text)
+ self.assertEqual(self.available(), 16384)
+
+ def test_no_cgroup_files_gives_the_free_memory_of_the_host(self):
+ self.assertEqual(self.available(), 16384)
+
+ def test_a_parent_with_a_larger_limit_and_less_free_memory_decides(self):
+ self.membership("0::/container/unit-1.scope\n")
+ self.write("container/unit-1.scope", "memory.max", str(4096 * 1024 ** 2))
+ self.write("container/unit-1.scope", "memory.current", str(1024 * 1024 ** 2))
+ self.write("container/unit-1.scope", "memory.stat", "inactive_file 0\n")
+ self.write("container", "memory.max", str(8192 * 1024 ** 2))
+ self.write("container", "memory.current", str(8000 * 1024 ** 2))
+ self.write("container", "memory.stat", "inactive_file 0\n")
+ self.assertEqual(self.available(), 192)
+
+ def test_levels_with_the_same_limit_give_the_smallest_free_memory(self):
+ for full in ("container", "container/unit-1.scope"):
+ with self.subTest(full=full):
+ shutil.rmtree(self.cgroups)
+ self.membership("0::/container/unit-1.scope\n")
+ for level in ("container", "container/unit-1.scope"):
+ self.write(level, "memory.max", str(4096 * 1024 ** 2))
+ self.write(level, "memory.current", str((4000 if level == full else 1024) * 1024 ** 2))
+ self.write(level, "memory.stat", "inactive_file 0\n")
+ self.assertEqual(self.available(), 96)
+
+ def test_the_use_is_read_at_the_level_of_the_limit_in_a_parent(self):
+ self.membership("0::/container/unit-1.scope\n")
+ self.write("container/unit-1.scope", "memory.max", "max")
+ self.write("container/unit-1.scope", "memory.current", str(100 * 1024 ** 2))
+ self.write("container/unit-1.scope", "memory.stat", "inactive_file 0\n")
+ self.write("container", "memory.max", str(4096 * 1024 ** 2))
+ self.write("container", "memory.current", str(3072 * 1024 ** 2))
+ self.write("container", "memory.stat", "inactive_file %d\n" % (512 * 1024 ** 2))
+ self.assertEqual(self.available(), 1536)
+
+ def test_cgroup_version_1(self):
+ self.membership("12:cpu,cpuacct:/user.slice\n5:memory:/container\n0::/container\n")
+ self.write("memory/container", "memory.limit_in_bytes", str(2048 * 1024 ** 2))
+ self.write("memory/container", "memory.usage_in_bytes", str(1536 * 1024 ** 2))
+ self.write("memory/container", "memory.stat", "cache 1\ninactive_file 7\ntotal_inactive_file %d\n" % (256 * 1024 ** 2))
+ self.write("memory", "memory.limit_in_bytes", "9223372036854771712")
+ self.assertEqual(self.available(), 768)
+
+ def test_a_use_above_the_limit_gives_zero(self):
+ self.membership("0::/container\n")
+ self.write("container", "memory.max", str(1024 * 1024 ** 2))
+ self.write("container", "memory.current", str(2048 * 1024 ** 2))
+ self.write("container", "memory.stat", "inactive_file 0\n")
+ self.assertEqual(self.available(), 0)
+
+ def test_an_inactive_file_cache_larger_than_the_use_is_no_use(self):
+ self.membership("0::/container\n")
+ self.write("container", "memory.max", str(1024 * 1024 ** 2))
+ self.write("container", "memory.current", str(100 * 1024 ** 2))
+ self.write("container", "memory.stat", "inactive_file %d\n" % (200 * 1024 ** 2))
+ self.assertEqual(self.available(), 1024)
+
+
+class MemoryWaitTest(unittest.TestCase):
+ def setUp(self):
+ patcher = mock.patch.object(bounded_run, "log")
+ self.log = patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def wait(self, values, limit):
+ readings = list(values)
+ sleeps = []
+ result = bounded_run.wait_for_memory(
+ 4096, limit, 5.0, read_available=lambda: readings.pop(0), sleep=sleeps.append,
+ )
+ return result, sleeps
+
+ def test_starts_at_once_when_the_memory_is_free(self):
+ self.assertEqual(self.wait([8000], 300), (True, []))
+
+ def test_waits_until_the_memory_is_free(self):
+ self.assertEqual(self.wait([1000, 2000, 5000], 300), (True, [5.0, 5.0]))
+
+ 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_wait(self):
+ self.assertEqual(self.wait([1000], 0), (False, []))
+
+ 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_starts_when_the_memory_is_not_readable(self):
+ self.assertEqual(self.wait([None], 300), (True, []))
+
+
+class CapTest(unittest.TestCase):
+ def test_prefix_holds_the_limits(self):
+ self.assertEqual(bounded_run.cap_prefix(6144, 4, "unit-1"), [
+ "systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", "unit-1",
+ "-p", "MemoryMax=6144M", "-p", "MemorySwapMax=0", "-p", "OOMPolicy=continue",
+ "-p", "CPUQuota=400%", "--",
+ ])
+
+ def test_prefix_without_cpus_has_no_quota(self):
+ self.assertNotIn("CPUQuota", " ".join(bounded_run.cap_prefix(6144, None, "unit-1")))
+
+ def test_prefix_without_the_oom_policy(self):
+ prefix = bounded_run.cap_prefix(6144, None, "unit-1", oom_policy=False)
+ self.assertNotIn("OOMPolicy", " ".join(prefix))
+ self.assertIn("MemoryMax=6144M", prefix)
+
+ def choose(self, answers):
+ probes = []
+
+ def usable(prefix):
+ probes.append(list(prefix))
+ return answers[len(probes) - 1]
+
+ return bounded_run.choose_cap_prefix(1024, 2, "unit-1", usable), 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"))
+ 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))
+ 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)
+ self.assertEqual(len(probes), 2)
+
+ def test_no_command_runs_on_a_different_system(self):
+ calls = []
+
+ 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)
+
+ self.assertIsNone(bounded_run.choose_cap_prefix(1024, 2, "unit-1", usable))
+ self.assertEqual(calls, [])
+
+ def probe(self, platform, tool, code=0, error=None):
+ calls = []
+
+ def run(command, **keywords):
+ calls.append(command)
+ if error is not None:
+ raise error
+ return subprocess.CompletedProcess(command, code)
+
+ usable = bounded_run.cap_usable(
+ bounded_run.cap_prefix(1024, 2, "unit-1"), platform=platform, which=lambda name: tool, run=run,
+ )
+ return usable, 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")
+ self.assertIn("CPUQuota=200%", calls[0])
+
+ def test_not_usable_when_the_probe_fails(self):
+ self.assertFalse(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])
+
+ def test_not_usable_without_the_tool(self):
+ usable, calls = self.probe("linux", None)
+ self.assertFalse(usable)
+ self.assertEqual(calls, [])
+
+ def test_not_usable_on_a_different_system(self):
+ usable, calls = self.probe("darwin", "/usr/bin/systemd-run")
+ self.assertFalse(usable)
+ self.assertEqual(calls, [])
+
+
+class MeasurementTest(unittest.TestCase):
+ def test_finds_the_cgroup_of_the_unit(self):
+ with tempfile.TemporaryDirectory() as proc:
+ os.mkdir(os.path.join(proc, "42"))
+ Path(proc, "42", "cgroup").write_text("0::/user.slice/user-1.slice/app.slice/unit-1.scope\n")
+ self.assertEqual(
+ bounded_run.cgroup_directory(42, "unit-1", proc_root=proc, cgroup_root="/cg"),
+ "/cg/user.slice/user-1.slice/app.slice/unit-1.scope",
+ )
+
+ def test_ignores_the_cgroup_before_the_scope_exists(self):
+ with tempfile.TemporaryDirectory() as proc:
+ os.mkdir(os.path.join(proc, "42"))
+ Path(proc, "42", "cgroup").write_text("0::/user.slice/user-1.slice/session-2.scope\n")
+ self.assertIsNone(bounded_run.cgroup_directory(42, "unit-1", proc_root=proc))
+
+ def test_a_process_that_is_gone_has_no_cgroup(self):
+ with tempfile.TemporaryDirectory() as proc:
+ self.assertIsNone(bounded_run.cgroup_directory(42, "unit-1", proc_root=proc))
+
+ def test_reads_the_peak_of_the_cgroup(self):
+ with tempfile.TemporaryDirectory() as directory:
+ Path(directory, "memory.peak").write_text("%d\n" % (300 * 1024 * 1024))
+ Path(directory, "memory.current").write_text("%d\n" % (100 * 1024 * 1024))
+ self.assertEqual(bounded_run.cgroup_peak_mib(directory), 300)
+
+ def test_reads_the_current_value_when_the_peak_file_is_absent(self):
+ with tempfile.TemporaryDirectory() as directory:
+ Path(directory, "memory.current").write_text("%d\n" % (100 * 1024 * 1024))
+ self.assertEqual(bounded_run.cgroup_peak_mib(directory), 100)
+
+ def test_reads_only_the_files_that_the_caller_names(self):
+ with tempfile.TemporaryDirectory() as directory:
+ Path(directory, "memory.current").write_text("%d\n" % (100 * 1024 * 1024))
+ self.assertIsNone(bounded_run.cgroup_peak_mib(directory, names=("memory.peak",)))
+
+ def test_a_cgroup_without_files_gives_nothing(self):
+ with tempfile.TemporaryDirectory() as directory:
+ self.assertIsNone(bounded_run.cgroup_peak_mib(directory))
+
+ def test_adds_the_memory_of_the_process_group(self):
+ text = " 100 2048\n 100 1024\n 200 9999\n 1 512\n"
+ self.assertEqual(bounded_run.parse_group_rss_mib(text, 100), 3)
+
+ def test_a_group_with_no_process_gives_nothing(self):
+ self.assertIsNone(bounded_run.parse_group_rss_mib(" 200 9999\n", 100))
+
+ def test_reads_the_memory_of_a_real_process_group(self):
+ self.assertGreater(bounded_run.group_rss_mib(os.getpgrp()), 0)
+
+ def test_the_peak_of_the_system_has_a_different_unit_on_each_system(self):
+ self.assertEqual(bounded_run.rusage_peak_mib(2048 * 1024, platform="linux"), 2048)
+ self.assertEqual(bounded_run.rusage_peak_mib(2048 * 1024 * 1024, platform="darwin"), 2048)
+
+ def test_the_suggested_budget_has_a_margin(self):
+ self.assertEqual(bounded_run.suggested_budget_mib(4000, approximate=False), 5120)
+ self.assertEqual(bounded_run.suggested_budget_mib(4000, approximate=True), 6144)
+
+ def test_the_tracker_keeps_the_largest_sample(self):
+ samples = [100, None, 900, 300]
+ tracker = bounded_run.PeakTracker(lambda: samples.pop(0) if samples else 300, 0.01)
+ tracker.start()
+ deadline = time.time() + 5
+ while samples and time.time() < deadline:
+ time.sleep(0.01)
+ self.assertEqual(tracker.finish(), 900)
+
+ def test_the_tracker_survives_a_reader_that_fails(self):
+ calls = []
+
+ def read():
+ calls.append(1)
+ raise OSError("gone")
+
+ tracker = bounded_run.PeakTracker(read, 0.01)
+ tracker.start()
+ deadline = time.time() + 5
+ while not calls and time.time() < deadline:
+ time.sleep(0.01)
+ self.assertGreaterEqual(len(calls), 1, "the reader never ran")
+ self.assertIsNone(tracker.finish())
+
+
+class ArgumentTest(unittest.TestCase):
+ def test_reads_all_options(self):
+ options = bounded_run.parse_arguments(
+ ["--memory", "6G", "--cpus", "4", "--exclusive", "a", "--exclusive", "b", "--measure", "--", "tool", "--memory", "x"]
+ )
+ self.assertEqual(
+ (options.memory, options.cpus, options.exclusive, options.measure, options.command),
+ ("6G", 4, ["a", "b"], True, ["tool", "--memory", "x"]),
+ )
+
+ def test_rejects_bad_arguments(self):
+ for arguments in (["tool"], ["--memory", "6G", "--"], ["--fast", "--", "tool"], ["--memory", "--", "tool"], ["--cpus", "0", "--", "tool"], ["--cpus", "two", "--", "tool"]):
+ with self.subTest(arguments=arguments):
+ with self.assertRaises(bounded_run.WrapperError):
+ bounded_run.parse_arguments(arguments)
+
+ def test_a_repeated_exclusive_name_is_kept_one_time(self):
+ options = bounded_run.parse_arguments(
+ ["--exclusive", "port", "--exclusive", "cache", "--exclusive", "port", "--", "tool"]
+ )
+ self.assertEqual(options.exclusive, ["port", "cache"])
+
+
+class InsideCapTest(unittest.TestCase):
+ def setUp(self):
+ patcher = mock.patch.object(bounded_run, "log")
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.base = tempfile.TemporaryDirectory()
+ self.addCleanup(self.base.cleanup)
+ self.proc = os.path.join(self.base.name, "proc")
+ self.cgroups = os.path.join(self.base.name, "cgroups")
+ self.peak_file = os.path.join(self.base.name, "peak")
+ os.makedirs(os.path.join(self.proc, str(os.getpid())))
+ Path(self.proc, str(os.getpid()), "cgroup").write_text("0::/user.slice/unit-1.scope\n")
+ self.cgroup = os.path.join(self.cgroups, "user.slice", "unit-1.scope")
+ os.makedirs(self.cgroup)
+
+ def inside(self, command, unit="unit-1"):
+ return bounded_run.inside_cap(self.peak_file, unit, command, proc_root=self.proc, cgroup_root=self.cgroups)
+
+ def test_writes_the_peak_after_the_command_stops(self):
+ Path(self.cgroup, "memory.peak").write_text("%d\n" % (300 * 1024 * 1024))
+ self.assertEqual(self.inside([sys.executable, "-c", "import sys; sys.exit(6)"]), 6)
+ self.assertEqual(bounded_run.read_peak_file(self.peak_file), 300)
+ self.assertFalse(os.path.exists(self.peak_file))
+
+ def test_writes_nothing_without_the_peak_file_of_the_kernel(self):
+ Path(self.cgroup, "memory.current").write_text("%d\n" % (100 * 1024 * 1024))
+ self.assertEqual(self.inside([sys.executable, "-c", "pass"]), 0)
+ self.assertIsNone(bounded_run.read_peak_file(self.peak_file))
+
+ def test_writes_nothing_outside_the_cgroup_of_the_unit(self):
+ Path(self.cgroup, "memory.peak").write_text("%d\n" % (300 * 1024 * 1024))
+ self.assertEqual(self.inside([sys.executable, "-c", "pass"], unit="unit-2"), 0)
+ self.assertIsNone(bounded_run.read_peak_file(self.peak_file))
+
+ def test_a_command_that_a_signal_stopped_gives_128_plus_the_signal(self):
+ script = "import os, signal; os.kill(os.getpid(), signal.SIGKILL)"
+ self.assertEqual(self.inside([sys.executable, "-c", script]), 137)
+
+ def test_a_command_that_does_not_exist_gives_125(self):
+ self.assertEqual(self.inside(["/nonexistent/tool-for-the-test"]), 125)
+
+ def test_puts_the_signal_handlers_back(self):
+ before = signal.getsignal(signal.SIGTERM)
+ self.inside([sys.executable, "-c", "pass"])
+ self.assertIs(signal.getsignal(signal.SIGTERM), before)
+
+ def test_a_stop_signal_while_the_peak_is_read_does_not_end_the_process(self):
+ # A signal with its default action ends the process that runs the test, so a child process runs inside_cap.
+ script = (
+ "import os, signal, sys\n"
+ "sys.path.insert(0, sys.argv[1])\n"
+ "import bounded_run\n"
+ "proc, cgroups, peak_file = sys.argv[2:5]\n"
+ "os.makedirs(os.path.join(proc, str(os.getpid())))\n"
+ "with open(os.path.join(proc, str(os.getpid()), 'cgroup'), 'w') as handle:\n"
+ " handle.write('0::/user.slice/unit-1.scope\\n')\n"
+ "def read_peak(directory, names=()):\n"
+ " os.kill(os.getpid(), signal.SIGTERM)\n"
+ " return 300\n"
+ "bounded_run.cgroup_peak_mib = read_peak\n"
+ "sys.exit(bounded_run.inside_cap(peak_file, 'unit-1', [sys.executable, '-c', 'import sys; sys.exit(6)'], proc_root=proc, cgroup_root=cgroups))\n"
+ )
+ child_proc = os.path.join(self.base.name, "child-proc")
+ done = subprocess.run(
+ [sys.executable, "-c", script, str(SCRIPTS), child_proc, self.cgroups, self.peak_file],
+ capture_output=True, text=True, timeout=60,
+ )
+ self.assertEqual(done.returncode, 6, done.stderr)
+ self.assertEqual(bounded_run.read_peak_file(self.peak_file), 300)
+
+ def test_a_peak_file_with_other_text_gives_nothing(self):
+ Path(self.peak_file).write_text("not a number\n")
+ self.assertIsNone(bounded_run.read_peak_file(self.peak_file))
+
+
+class RunCommandTest(unittest.TestCase):
+ def test_an_error_after_the_start_stops_the_command(self):
+ pids = []
+
+ def cleanup():
+ for pid in pids:
+ try:
+ os.killpg(pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ try:
+ os.waitpid(pid, 0)
+ except ChildProcessError:
+ pass
+
+ self.addCleanup(cleanup)
+
+ def on_start(pid):
+ pids.append(pid)
+ raise RuntimeError("boom")
+
+ command = [sys.executable, "-c", "import time; time.sleep(300)", "run-command-test-marker-8f2c1"]
+ with self.assertRaises(RuntimeError):
+ bounded_run.run_command(command, dict(os.environ), on_start=on_start)
+ self.assertEqual(len(pids), 1)
+ deadline = time.time() + 10
+ alive = True
+ while alive and time.time() < deadline:
+ try:
+ os.kill(pids[0], 0)
+ time.sleep(0.05)
+ except ProcessLookupError:
+ alive = False
+ self.assertFalse(alive, "the command still runs")
+
+
+class SignalAtStartTest(unittest.TestCase):
+ def test_two_stop_signals_before_the_command_runs_end_a_command_that_ignores_the_first(self):
+ real = subprocess.Popen
+
+ base = tempfile.TemporaryDirectory()
+ self.addCleanup(base.cleanup)
+ ready = os.path.join(base.name, "ready")
+
+ def start_then_signal(*args, **kwargs):
+ process = real(*args, **kwargs)
+ limit = time.monotonic() + 30
+ while not os.path.exists(ready) and time.monotonic() < limit:
+ time.sleep(0.02)
+ os.kill(os.getpid(), signal.SIGTERM)
+ os.kill(os.getpid(), signal.SIGTERM)
+ return process
+
+ script = "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); open(%r, 'w').close(); time.sleep(20)" % ready
+ started = time.monotonic()
+ with mock.patch.object(bounded_run.subprocess, "Popen", start_then_signal):
+ code, _ = bounded_run.run_command([sys.executable, "-c", script], os.environ)
+ self.assertEqual(code, 128 + signal.SIGTERM)
+ self.assertLess(time.monotonic() - started, 10)
+
+
+class LeftProcessTest(unittest.TestCase):
+ def setUp(self):
+ patcher = mock.patch.object(bounded_run, "log")
+ self.log = patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_a_process_that_the_command_leaves_running_gives_a_warning(self):
+ groups = []
+
+ def stop():
+ for group in groups:
+ try:
+ os.killpg(group, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+
+ self.addCleanup(stop)
+ code, _ = bounded_run.run_command(["sh", "-c", "sleep 300 >/dev/null 2>&1 &"], os.environ, on_start=groups.append)
+ self.assertEqual(code, 0)
+ self.log.assert_called_once_with("WARNING: the command left a process that still runs; the queue does not count its memory")
+
+ def test_a_command_that_leaves_no_process_gives_no_warning(self):
+ code, _ = bounded_run.run_command(["sh", "-c", "sleep 0.1 & wait"], os.environ)
+ self.assertEqual(code, 0)
+ self.log.assert_not_called()
+
+
+class ParentDeathSignalTest(unittest.TestCase):
+ def setUp(self):
+ patcher = mock.patch.object(bounded_run, "log")
+ self.log = patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def test_nothing_on_a_different_system(self):
+ self.assertIsNone(bounded_run.parent_death_signal(platform="darwin"))
+
+ def test_nothing_without_ctypes(self):
+ with mock.patch.object(bounded_run, "ctypes", None):
+ self.assertIsNone(bounded_run.parent_death_signal(platform="linux"))
+ self.log.assert_not_called()
+
+ def test_nothing_without_prctl(self):
+ for library in (mock.Mock(side_effect=OSError("no library")), mock.Mock(return_value=object())):
+ with self.subTest(library=library):
+ with mock.patch.object(bounded_run, "ctypes", mock.Mock(CDLL=library)):
+ self.assertIsNone(bounded_run.parent_death_signal(platform="linux"))
+ self.log.assert_not_called()
+
+ @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal")
+ def test_a_child_whose_parent_is_already_gone_exits(self):
+ with mock.patch.object(bounded_run.os, "getpid", return_value=1):
+ set_signal = bounded_run.parent_death_signal()
+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"], preexec_fn=set_signal)
+
+ def stop():
+ if process.poll() is None:
+ process.kill()
+ process.wait()
+
+ self.addCleanup(stop)
+ self.assertEqual(process.wait(timeout=60), bounded_run.EXIT_WRAPPER)
+
+ def test_a_call_that_the_kernel_refuses_gives_a_warning_and_the_child_runs(self):
+ library = mock.Mock(return_value=mock.Mock(prctl=mock.Mock(return_value=-1)))
+ with mock.patch.object(bounded_run, "ctypes", mock.Mock(CDLL=library)):
+ set_signal = bounded_run.parent_death_signal(platform="linux")
+ process = subprocess.Popen([sys.executable, "-c", "pass"], preexec_fn=set_signal, stderr=subprocess.PIPE, text=True)
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 0, errors)
+ self.assertIn("bounded-run: WARNING: cannot set the parent-death signal; the command lives on after a hard kill of the wrapper", errors)
+
+ @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal")
+ def test_a_child_of_this_process_runs(self):
+ process = subprocess.Popen([sys.executable, "-c", "pass"], preexec_fn=bounded_run.parent_death_signal(), stderr=subprocess.PIPE, text=True)
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, errors), (0, ""))
+
+ @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal")
+ def test_a_child_of_this_process_runs_with_no_pipe(self):
+ process = subprocess.Popen([sys.executable, "-c", "pass"], preexec_fn=bounded_run.parent_death_signal())
+ self.assertEqual(process.wait(timeout=60), 0)
+
+
+class BoundedCleanupTest(unittest.TestCase):
+ """Calls bounded() in this process, with run_command and cap_usable replaced by stubs.
+
+ No real command, no real cgroup, and no real subprocess run outside the stubs.
+ """
+
+ def setUp(self):
+ patcher = mock.patch.object(bounded_run, "log")
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.base = tempfile.TemporaryDirectory()
+ self.addCleanup(self.base.cleanup)
+ self.directory = os.path.join(self.base.name, "locks")
+ self.environ = dict(os.environ)
+ self.environ.pop("BOUNDED_RUN_ACTIVE", None)
+ self.environ.pop("BOUNDED_RUN_NO_CAP", None)
+ self.environ.update({
+ "BOUNDED_RUN_LOCK_DIR": self.directory,
+ "BOUNDED_RUN_TOTAL_MIB": "4096",
+ "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",
+ })
+
+ def test_the_peak_file_is_removed_when_the_run_fails_after_the_start(self):
+ def fake_run_command(command, environ, on_start=None):
+ index = command.index("--inside-cap")
+ with open(command[index + 1], "w") as handle:
+ handle.write("123\n")
+ raise RuntimeError("boom")
+
+ options = bounded_run.Options()
+ options.memory = "2G"
+ options.command = [sys.executable, "-c", "pass"]
+
+ with mock.patch.object(bounded_run, "cap_usable", return_value=True), \
+ mock.patch.object(bounded_run, "run_command", fake_run_command):
+ with self.assertRaises(RuntimeError):
+ bounded_run.bounded(options, self.environ)
+
+ names = os.listdir(self.directory)
+ self.assertEqual([name for name in names if name.startswith("peak-")], [])
+
+ reservation = bounded_run.try_reserve(self.directory, 2, 2, [])
+ self.assertIsNotNone(reservation, "the slots are still held")
+ reservation.release()
+
+ def test_a_budget_larger_than_the_queue_caps_and_waits_at_the_memory_of_the_queue(self):
+ commands = []
+ waits = []
+
+ def fake_run_command(command, environ, on_start=None):
+ commands.append(list(command))
+ return 0, 0
+
+ options = bounded_run.Options()
+ 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)), \
+ 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])
+
+
+class WrapperProcessCase(unittest.TestCase):
+ """Runs the script as a process, with two slots of 2 GiB and no hard cap."""
+
+ def setUp(self):
+ self.base = tempfile.TemporaryDirectory()
+ self.addCleanup(self.base.cleanup)
+ self.events = os.path.join(self.base.name, "events")
+ 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": "6144",
+ "BOUNDED_RUN_RESERVE_MIB": "2048",
+ "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",
+ "EVENTS": self.events,
+ })
+ self.processes = []
+ self._stderr_buffers = {}
+
+ def tearDown(self):
+ for process in self.processes:
+ if process.poll() is None:
+ process.kill()
+ process.wait()
+ for stream in (process.stdout, process.stderr):
+ if stream is not None:
+ stream.close()
+ for line in self.read_events():
+ try:
+ os.kill(int(line.split()[2]), signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+
+ def wrapper(self, options, command, **environ):
+ variables = dict(self.environ)
+ variables.update(environ)
+ process = subprocess.Popen(
+ [sys.executable, WRAPPER] + options + ["--"] + command,
+ env=variables, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ self.processes.append(process)
+ return process
+
+ def worker(self, name, memory, hold="0.3", options=(), release=""):
+ command = [sys.executable, "-c", WORKER, name]
+ return self.wrapper(["--memory", memory] + list(options), command, HOLD=hold, RELEASE=release)
+
+ def read_events(self):
+ try:
+ with open(self.events) as handle:
+ return handle.read().splitlines()
+ except OSError:
+ return []
+
+ def wait_for_event(self, kind, name, seconds=60.0):
+ deadline = time.time() + seconds
+ while time.time() < deadline:
+ for line in self.read_events():
+ if line.split()[:2] == [kind, name]:
+ return line
+ time.sleep(0.02)
+ self.fail("no '%s %s' event after %s seconds; events: %s" % (kind, name, seconds, self.read_events()))
+
+ def wait_for_stderr(self, process, substring, seconds=60.0):
+ """Reads the process's raw error-stream descriptor until substring appears, or fails by seconds.
+
+ Reads os.read() on the raw descriptor, never process.stderr's own buffered readline()/read():
+ select() only reports the descriptor ready, it says nothing about how many lines are
+ sitting in the pipe. A buffered readline() can pull more than one already-arrived line
+ out of the pipe in a single call and return just the first, leaving the rest sitting in
+ Python's own buffer where select() can no longer see them and this loop would wait for a
+ line it already holds. Keeps what it reads in self._stderr_buffers, keyed by process, so
+ a later call to stderr_of() for the same process resumes from here instead of losing or
+ re-reading any of it.
+ """
+ deadline = time.time() + seconds
+ buffer = self._stderr_buffers.setdefault(process, "")
+ fd = process.stderr.fileno()
+ while substring not in buffer:
+ remaining = deadline - time.time()
+ if remaining <= 0:
+ self.fail("no line with %r on the error stream after %s seconds; stderr so far: %s" % (substring, seconds, buffer))
+ ready, _, _ = select.select([fd], [], [], min(remaining, 0.5))
+ if ready:
+ chunk = os.read(fd, 65536)
+ if not chunk:
+ self.fail("the error stream closed with no line %r; stderr so far: %s" % (substring, buffer))
+ buffer += chunk.decode(errors="replace")
+ self._stderr_buffers[process] = buffer
+ return buffer
+
+ def stderr_of(self, process):
+ """Returns everything the process wrote to its error stream, once it has stopped.
+
+ Combines what wait_for_stderr already took off the raw descriptor (if any) with a final
+ raw read of whatever is left, so the two never compete for the same bytes through two
+ different buffers. Call only after the process has exited, so the final read reaches
+ end-of-file instead of blocking.
+ """
+ buffer = self._stderr_buffers.pop(process, "")
+ fd = process.stderr.fileno()
+ while True:
+ chunk = os.read(fd, 65536)
+ if not chunk:
+ return buffer
+ buffer += chunk.decode(errors="replace")
+
+ def gone(self, pid, seconds=10.0):
+ """Returns True when the process stops, or is a zombie, within seconds."""
+ deadline = time.time() + seconds
+ while time.time() < deadline:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return True
+ try:
+ if Path("/proc/%d/stat" % pid).read_text().rsplit(")", 1)[1].split()[0] == "Z":
+ return True
+ except OSError:
+ return True
+ time.sleep(0.05)
+ return False
+
+ def kill_later(self, pid):
+ def kill():
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ self.addCleanup(kill)
+
+ def peak_concurrency(self):
+ running = 0
+ peak = 0
+ for line in self.read_events():
+ running += 1 if line.startswith("start ") else -1
+ peak = max(peak, running)
+ return peak
+
+
+class WrapperProcessTest(WrapperProcessCase):
+ def test_passes_the_exit_code(self):
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "import sys; sys.exit(7)"])
+ self.assertEqual(process.wait(timeout=60), 7)
+
+ def test_passes_the_output(self):
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "print('from the command')"])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(output, "from the command\n")
+ self.assertIn("bounded-run: budget 2048 MiB", errors)
+
+ def test_a_command_that_a_signal_stopped_gives_128_plus_the_signal(self):
+ script = "import os, signal; os.kill(os.getpid(), signal.SIGKILL)"
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", script])
+ self.assertEqual(process.wait(timeout=60), 137)
+
+ def test_a_failure_of_the_wrapper_gives_125(self):
+ process = subprocess.Popen(
+ [sys.executable, WRAPPER, "--memory", "2G", "tool"], env=self.environ,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ self.processes.append(process)
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 125)
+ self.assertTrue(errors.startswith("bounded-run: "), errors)
+
+ def test_a_command_that_does_not_exist_gives_125(self):
+ process = self.wrapper(["--memory", "2G"], ["/nonexistent/tool-for-the-test"])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 125)
+ self.assertIn("cannot start", errors)
+ follower = self.worker("after", "4G", hold="0") # ends at once; the test waits for it to end
+ self.assertEqual(follower.wait(timeout=60), 0)
+
+ def test_the_command_gets_the_budget_and_the_marker(self):
+ script = "import os; print(os.environ['BOUNDED_RUN_ACTIVE'], os.environ['BOUNDED_RUN_MEMORY_MIB'], os.environ['BOUNDED_RUN_CPUS'])"
+ process = self.wrapper(["--memory", "2G", "--cpus", "3"], [sys.executable, "-c", script])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(output, "1 2048 3\n")
+
+ def test_the_command_reads_the_input_of_the_wrapper(self):
+ variables = dict(self.environ)
+ process = subprocess.Popen(
+ [sys.executable, WRAPPER, "--memory", "2G", "--", sys.executable, "-c", "import sys; print(sys.stdin.read().upper())"],
+ env=variables, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ self.processes.append(process)
+ output, errors = process.communicate("text for the command", timeout=60)
+ self.assertEqual((process.returncode, output), (0, "TEXT FOR THE COMMAND\n"), errors)
+
+ def test_a_nested_call_does_not_wait_for_its_own_slots(self):
+ inner = [sys.executable, WRAPPER, "--memory", "4G", "--", sys.executable, "-c", "import sys; print('inner'); sys.exit(3)"]
+ process = self.wrapper(["--memory", "4G"], inner)
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, output), (3, "inner\n"), errors)
+ self.assertIn("nested call", errors)
+
+ def test_a_nested_call_of_a_command_that_does_not_exist_gives_125(self):
+ process = self.wrapper(["--memory", "2G"], ["/nonexistent/tool-for-the-test"], BOUNDED_RUN_ACTIVE="1")
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 125, errors)
+ self.assertNotIn("Traceback", errors)
+
+ def test_a_stop_signal_stops_the_command(self):
+ for signum, code in ((signal.SIGTERM, 143), (signal.SIGINT, 130)):
+ with self.subTest(signal=signum):
+ name = "stopped-%d" % code
+ process = self.worker(name, "2G", hold="300")
+ line = self.wait_for_event("start", name)
+ process.send_signal(signum)
+ self.assertEqual(process.wait(timeout=60), code)
+ child = int(line.split()[2])
+ deadline = time.time() + 5
+ alive = True
+ while alive and time.time() < deadline:
+ try:
+ os.kill(child, 0)
+ time.sleep(0.05)
+ except ProcessLookupError:
+ alive = False
+ self.assertFalse(alive, "the command still runs")
+
+ def test_a_hangup_stops_the_command_and_gives_129(self):
+ name = "hangup-129"
+ process = self.worker(name, "2G", hold="300")
+ line = self.wait_for_event("start", name)
+ process.send_signal(signal.SIGHUP)
+ self.assertEqual(process.wait(timeout=60), 129)
+ child = int(line.split()[2])
+ deadline = time.time() + 5
+ alive = True
+ while alive and time.time() < deadline:
+ try:
+ os.kill(child, 0)
+ time.sleep(0.05)
+ except ProcessLookupError:
+ alive = False
+ self.assertFalse(alive, "the command still runs")
+
+ def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self):
+ script = (
+ "import os, signal, sys, time\n"
+ "def event(kind):\n"
+ " descriptor = os.open(os.environ['EVENTS'], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)\n"
+ " os.write(descriptor, ('%s stubborn %d\\n' % (kind, os.getpid())).encode())\n"
+ " os.close(descriptor)\n"
+ "def ignore(signum, frame):\n"
+ " event('signaled')\n"
+ "signal.signal(signal.SIGTERM, ignore)\n"
+ "event('start')\n"
+ "time.sleep(300)\n" # runs until the second signal kills it; never meant to end on its own
+ )
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", script])
+ line = self.wait_for_event("start", "stubborn")
+ process.send_signal(signal.SIGTERM)
+ self.wait_for_event("signaled", "stubborn", seconds=60.0)
+ self.assertIsNone(process.poll())
+ process.send_signal(signal.SIGTERM)
+ self.assertEqual(process.wait(timeout=60), 143)
+ child = int(line.split()[2])
+ deadline = time.time() + 5
+ alive = True
+ while alive and time.time() < deadline:
+ try:
+ os.kill(child, 0)
+ time.sleep(0.05)
+ except ProcessLookupError:
+ alive = False
+ self.assertFalse(alive, "the command still runs")
+
+ def test_commands_never_run_together_beyond_the_slots(self):
+ workers = [self.worker("w%d" % index, "2G", hold="0.3") for index in range(6)] # brief; the test waits for each to end
+ for process in workers:
+ self.assertEqual(process.wait(timeout=60), 0)
+ events = self.read_events()
+ self.assertEqual(len([line for line in events if line.startswith("start ")]), 6)
+ self.assertEqual(len([line for line in events if line.startswith("end ")]), 6)
+ self.assertLessEqual(self.peak_concurrency(), 2)
+
+ def test_a_command_that_needs_all_slots_runs_alone(self):
+ workers = [self.worker("w%d" % index, "4G", hold="0.2") for index in range(3)] # brief; the test waits for each to end
+ for process in workers:
+ self.assertEqual(process.wait(timeout=60), 0)
+ self.assertEqual(self.peak_concurrency(), 1)
+
+ def test_a_waiting_command_holds_no_slot(self):
+ release = os.path.join(self.base.name, "release")
+ long_holder = self.worker("holder", "2G", hold="300", release=release) # runs until the release file below ends it early
+ self.wait_for_event("start", "holder")
+ large = self.worker("large", "4G", hold="0") # ends at once once it gets its slots; the test waits for it to end
+ self.wait_for_stderr(large, "waiting for")
+ small = self.worker("small", "2G", hold="0") # ends at once; the test waits for it to end
+ self.assertEqual(small.wait(timeout=60), 0)
+ names = [line.split()[1] for line in self.read_events() if line.startswith("end ")]
+ self.assertEqual(names, ["small"])
+ Path(release).write_text("")
+ self.assertEqual(large.wait(timeout=60), 0)
+ self.assertEqual(long_holder.wait(timeout=60), 0)
+ order = [line.split()[:2] for line in self.read_events()]
+ self.assertLess(order.index(["end", "holder"]), order.index(["start", "large"]))
+
+ def test_a_hard_kill_of_the_wrapper_frees_the_slots_at_once(self):
+ holder = self.worker("holder", "4G", hold="300") # runs until the kill below ends it
+ self.wait_for_event("start", "holder")
+ holder.kill()
+ holder.wait(timeout=60)
+ started = time.time()
+ follower = self.worker("follower", "4G", hold="0") # ends at once; the test waits for it to end
+ self.assertEqual(follower.wait(timeout=60), 0)
+ self.assertLess(time.time() - started, 30.0)
+
+ @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal")
+ def test_a_hard_kill_of_the_wrapper_stops_the_command(self):
+ process = self.worker("orphan", "2G", hold="300") # runs until the kill below ends it
+ command = int(self.wait_for_event("start", "orphan").split()[2])
+ self.kill_later(command)
+ process.kill()
+ process.wait(timeout=60)
+ self.assertTrue(self.gone(command), "the command still runs")
+
+ def test_the_command_does_not_inherit_the_locks(self):
+ script = (
+ "import os\n"
+ "directory = os.environ['BOUNDED_RUN_LOCK_DIR']\n"
+ "locks = set()\n"
+ "for name in os.listdir(directory):\n"
+ " info = os.stat(os.path.join(directory, name))\n"
+ " locks.add((info.st_dev, info.st_ino))\n"
+ "found = 0\n"
+ "for descriptor in range(3, 256):\n"
+ " try:\n"
+ " info = os.fstat(descriptor)\n"
+ " except OSError:\n"
+ " continue\n"
+ " if (info.st_dev, info.st_ino) in locks:\n"
+ " found += 1\n"
+ "print('locks', len(locks), 'inherited', found)\n"
+ )
+ 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)
+
+ 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
+ for process in workers:
+ self.assertEqual(process.wait(timeout=60), 0)
+ self.assertEqual(self.peak_concurrency(), 1)
+
+ def test_a_budget_larger_than_the_queue_runs_with_a_warning(self):
+ first = self.worker("first", "64G", hold="0.3") # brief; the test waits for each to end
+ second = self.worker("second", "64G", hold="0.3")
+ output, errors = first.communicate(timeout=60)
+ self.assertEqual(first.returncode, 0, errors)
+ self.assertIn("WARNING: the budget of 65536 MiB is more than the 4096 MiB of the queue; the budget is 4096 MiB", errors)
+ self.assertRegex(errors, r"bounded-run: budget 4096 MiB, peak ")
+ self.assertEqual(second.wait(timeout=60), 0)
+ self.assertEqual(self.peak_concurrency(), 1)
+
+ def test_a_budget_too_large_for_a_float_gives_the_budget_of_the_queue(self):
+ process = self.wrapper(["--memory", "1" + "0" * 400 + "G"], [sys.executable, "-c", "pass"])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 0, errors)
+ self.assertNotIn("Traceback", errors)
+ self.assertRegex(errors, r"bounded-run: budget 4096 MiB, peak ")
+
+ def test_a_budget_larger_than_the_queue_gives_the_command_the_budget_of_the_queue(self):
+ script = "import os; print(os.environ['BOUNDED_RUN_MEMORY_MIB'])"
+ process = self.wrapper(["--memory", "64G"], [sys.executable, "-c", script])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, output), (0, "4096\n"), errors)
+
+ def test_a_lock_directory_that_is_a_file_gives_125(self):
+ path = os.path.join(self.base.name, "a-file")
+ Path(path).write_text("")
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "print('ran')"], BOUNDED_RUN_LOCK_DIR=path)
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, output), (125, ""), errors)
+ self.assertIn("bounded-run: cannot use the lock directory", errors)
+
+ def test_a_relative_lock_directory_gives_125(self):
+ variables = dict(self.environ, BOUNDED_RUN_LOCK_DIR="locks")
+ process = subprocess.Popen(
+ [sys.executable, WRAPPER, "--memory", "2G", "--", sys.executable, "-c", "print('ran')"],
+ env=variables, cwd=self.base.name, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ self.processes.append(process)
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, output), (125, ""), errors)
+ self.assertTrue(errors.startswith("bounded-run: "), errors)
+ self.assertIn("BOUNDED_RUN_LOCK_DIR", errors)
+ self.assertNotIn("Traceback", errors)
+ self.assertFalse(os.path.exists(os.path.join(self.base.name, "locks")))
+
+ def test_a_lock_file_that_cannot_be_opened_gives_125(self):
+ os.makedirs(os.path.join(self.environ["BOUNDED_RUN_LOCK_DIR"], "reserve.lock"))
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "print('ran')"])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, output), (125, ""), errors)
+ self.assertTrue(errors.startswith("bounded-run: "), errors)
+ self.assertNotIn("Traceback", errors)
+
+ def test_an_exclusive_name_in_a_removed_working_directory_gives_125(self):
+ script = 'mkdir gone && cd gone && rmdir ../gone && exec "$@"'
+ process = subprocess.Popen(
+ ["sh", "-c", script, "sh", sys.executable, WRAPPER, "--memory", "2G", "--exclusive", "port", "--", sys.executable, "-c", "print('ran')"],
+ env=self.environ, cwd=self.base.name, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ )
+ self.processes.append(process)
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, output), (125, ""), errors)
+ self.assertTrue(errors.startswith("bounded-run: "), errors)
+ self.assertNotIn("Traceback", errors)
+
+ def test_each_run_reports_the_budget_and_the_peak(self):
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"])
+ output, errors = process.communicate(timeout=60)
+ self.assertRegex(errors, r"bounded-run: budget 2048 MiB, peak \d+ MiB \(sampled, approximate\), exit 0\n")
+ self.assertNotIn("suggested budget", errors)
+
+ def test_the_default_budget_on_a_small_machine_is_not_more_than_its_memory(self):
+ process = self.wrapper([], [sys.executable, "-c", "pass"], BOUNDED_RUN_TOTAL_MIB="1024", BOUNDED_RUN_RESERVE_MIB="")
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 0, errors)
+ budget = int(re.search(r"bounded-run: budget (\d+) MiB, peak", errors).group(1))
+ self.assertLessEqual(budget, 1024)
+
+ def test_a_budget_on_a_machine_smaller_than_one_slot_is_not_more_than_its_memory(self):
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"], BOUNDED_RUN_TOTAL_MIB="1024", BOUNDED_RUN_RESERVE_MIB="")
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 0, errors)
+ self.assertIn("WARNING: the budget of 2048 MiB is more than the 1024 MiB of the queue; the budget is 1024 MiB", errors)
+ self.assertRegex(errors, r"bounded-run: budget 1024 MiB, peak ")
+
+ def test_a_budget_on_a_machine_with_less_than_one_slot_after_the_reserve_keeps_the_reserve(self):
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"], BOUNDED_RUN_TOTAL_MIB="3072", BOUNDED_RUN_RESERVE_MIB="")
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 0, errors)
+ self.assertIn("WARNING: the budget of 2048 MiB is more than the 1024 MiB of the queue; the budget is 1024 MiB", errors)
+ self.assertNotIn("reserve", errors)
+
+ def test_a_reserve_that_leaves_nothing_gives_a_warning(self):
+ process = self.wrapper(["--memory", "1G"], [sys.executable, "-c", "pass"], BOUNDED_RUN_TOTAL_MIB="1024", BOUNDED_RUN_RESERVE_MIB="")
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 0, errors)
+ self.assertIn("WARNING: the reserve of 2048 MiB leaves no memory of the 1024 MiB of the machine; the queue does not keep the reserve", errors)
+
+ def test_without_a_cap_the_output_says_so(self):
+ process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"])
+ output, errors = process.communicate(timeout=60)
+ self.assertIn("no hard cap is available here", errors)
+
+ def test_measure_mode_reports_a_peak_and_a_budget(self):
+ script = "import time\ndata = bytearray(150 * 1024 * 1024)\nfor index in range(0, len(data), 4096):\n data[index] = 1\ntime.sleep(1.0)\n"
+ process = self.wrapper(["--measure"], [sys.executable, "-c", script])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 0, errors)
+ peak = [line for line in errors.splitlines() if " peak " in line][0]
+ value = int(peak.split(" peak ")[1].split()[0])
+ self.assertGreaterEqual(value, 140)
+ self.assertLess(value, 1024)
+ self.assertIn("sampled, approximate", peak)
+ suggested = [line for line in errors.splitlines() if "suggested budget" in line][0]
+ self.assertEqual(int(suggested.split()[-2]) % 256, 0)
+ self.assertGreaterEqual(int(suggested.split()[-2]), value * 1.5)
+
+ 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")
+ waiting = self.worker("waiting", "4G", hold="0") # never reached; interrupted while still queued
+
+ self.wait_for_stderr(waiting, "waiting for")
+
+ waiting.send_signal(signal.SIGINT)
+ self.assertEqual(waiting.wait(timeout=60), 130)
+ buffer = self.stderr_of(waiting)
+ self.assertNotIn("Traceback", buffer)
+ for line in buffer.splitlines():
+ self.assertTrue(line.startswith("bounded-run: "), buffer)
+
+ holder.send_signal(signal.SIGTERM)
+ self.assertEqual(holder.wait(timeout=60), 143)
+
+
+@unittest.skipUnless(
+ bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.cap_usable) is not None,
+ "no hard cap on this machine",
+)
+class HardCapTest(WrapperProcessCase):
+ def setUp(self):
+ super().setUp()
+ del self.environ["BOUNDED_RUN_NO_CAP"]
+
+ def test_a_command_that_does_not_exist_gives_125(self):
+ process = self.wrapper(["--memory", "2G"], ["/nonexistent/tool-for-the-test"])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 125, errors)
+
+ def test_the_cap_stops_a_command_that_passes_its_budget(self):
+ script = "data = bytearray(1024 * 1024 * 1024)\nfor index in range(0, len(data), 4096):\n data[index] = 1\nprint('survived')\n"
+ process = self.wrapper(["--memory", "256M", "--cpus", "1"], [sys.executable, "-c", script])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, output), (137, ""), errors)
+ self.assertIn("the hard cap stopped it", errors)
+
+ def test_a_short_command_gets_its_peak_from_the_cgroup(self):
+ for attempt in range(5):
+ with self.subTest(attempt=attempt):
+ process = self.wrapper(["--memory", "1G", "--cpus", "2"], [sys.executable, "-c", "print(1)"])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual((process.returncode, output), (0, "1\n"), errors)
+ self.assertRegex(errors, r"bounded-run: budget 1024 MiB, peak \d+ MiB \(cgroup\), exit 0\n")
+ locks = os.listdir(self.environ["BOUNDED_RUN_LOCK_DIR"])
+ self.assertEqual([name for name in locks if name.startswith("peak-")], [])
+
+ def test_a_stop_signal_stops_a_capped_command(self):
+ process = self.worker("capped", "1G", hold="300")
+ line = self.wait_for_event("start", "capped")
+ process.send_signal(signal.SIGTERM)
+ self.assertEqual(process.wait(timeout=60), 143)
+ with self.assertRaises(ProcessLookupError):
+ deadline = time.time() + 5
+ while time.time() < deadline:
+ os.kill(int(line.split()[2]), 0)
+ time.sleep(0.05)
+
+ def test_a_hard_kill_of_the_wrapper_stops_the_inside_process_and_the_command(self):
+ process = self.worker("capped-orphan", "1G", hold="300") # runs until the kill below ends it
+ command = int(self.wait_for_event("start", "capped-orphan").split()[2])
+ inside = int(Path("/proc/%d/stat" % command).read_text().rsplit(")", 1)[1].split()[1])
+ self.kill_later(inside)
+ self.kill_later(command)
+ self.assertIn(b"--inside-cap", Path("/proc/%d/cmdline" % inside).read_bytes())
+ process.kill()
+ process.wait(timeout=60)
+ self.assertTrue(self.gone(inside), "the --inside-cap process still runs")
+ self.assertTrue(self.gone(command), "the command still runs")
+
+ def test_the_peak_comes_from_the_cgroup(self):
+ script = "import time\ndata = bytearray(150 * 1024 * 1024)\nfor index in range(0, len(data), 4096):\n data[index] = 1\ntime.sleep(1.2)\n"
+ process = self.wrapper(["--memory", "1G", "--measure"], [sys.executable, "-c", script])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 0, errors)
+ peak = [line for line in errors.splitlines() if " peak " in line][0]
+ self.assertIn("(cgroup)", peak)
+ self.assertGreaterEqual(int(peak.split(" peak ")[1].split()[0]), 140)
+
+ def test_no_peak_file_is_left_behind_after_a_failing_command(self):
+ process = self.wrapper(["--memory", "1G"], [sys.executable, "-c", "import sys; sys.exit(9)"])
+ output, errors = process.communicate(timeout=60)
+ self.assertEqual(process.returncode, 9, errors)
+ self.assertIn("(cgroup)", errors)
+ locks = os.listdir(self.environ["BOUNDED_RUN_LOCK_DIR"])
+ self.assertEqual([name for name in locks if name.startswith("peak-")], [])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/skills/developing-a-feature/SKILL.md b/skills/developing-a-feature/SKILL.md
index df42f2c..6aa86cb 100644
--- a/skills/developing-a-feature/SKILL.md
+++ b/skills/developing-a-feature/SKILL.md
@@ -94,6 +94,7 @@ Record the choice as `sub_pr_target: feature-branch` or `sub_pr_target: main`. T
- **2+ independent tasks → drive the build task-by-task with review between tasks.** **REQUIRED SUB-SKILL:** `superpowers:subagent-driven-development`. The orchestrator (this session — the main loop, which *can* dispatch subagents) runs that skill's loop engine: a fresh implementer subagent per task with full task text handed in, then review, fix-loop, and continuous execution across all tasks. Two adaptations keep it consistent with the rest of this plugin:
- **Per-task review is the `review` skill** (the same mechanism `feature-dev-workflow:fanning-out-with-worktrees` uses for sub-PRs), run by the orchestrator — not the implementer subagent that wrote the task. Run it as two scoped passes, spec-compliance first as a gate, then code quality; route findings back to the implementer and re-run until clean.
- Each implementer subagent uses **`superpowers:test-driven-development`** + **`feature-dev-workflow:testing-a-feature`** for its task, and `feature-dev-workflow:writing-code-comments` for every comment the change adds, edits, or deletes, exactly as the direct path below.
+ - Each implementer subagent's prompt carries the bounded command line for every heavy command it will run, and the rule to use no other form. A subagent does not see the orchestrator's project memory. **REQUIRED SUB-SKILL:** `feature-dev-workflow:bounding-heavy-commands` (§Dispatching subagents).
Why conditional: SDD's premise is independent tasks. Below that threshold the dispatch overhead and context hand-off cost more than they return, so the direct path is correct. This is the in-session analogue of the multi-PR fan-out — same "author and reviewer are different contexts" discipline, one PR instead of many.
@@ -103,6 +104,8 @@ Record the choice as `sub_pr_target: feature-branch` or `sub_pr_target: main`. T
Either way: commits follow CLAUDE.md conventions (`(): (#)`), and you run the project's test and lint commands (and typecheck, if it has one) before claiming work is done. Discover them from the project's CLAUDE.md / AGENTS.md or its build config (Makefile, package.json, etc.).
+ **REQUIRED SUB-SKILL:** `feature-dev-workflow:bounding-heavy-commands` before you run any of them. Every test, lint, build, and typecheck command goes through its wrapper, whether or not this session looks alone: other sessions and other projects share the machine, and none of them can see the others.
+
**REQUIRED SUB-SKILL:** `feature-dev-workflow:writing-code-comments` for every comment the change adds, edits, or deletes, on both single-PR build modes. It decides whether the comment exists and what it holds.
**OPTIONAL SUB-SKILL:** `simple-english:simple-english` for the prose of every commit body and every code or doc comment you write, here and in the Step 7 teardown commit. If it is available, load it before you draft and write the sentences under it. Where its formatting rules (headings, bold, lists, or its register for chat replies) differ from the host skill or its template, the host skill and its template win. It sets sentence style only: the subject line keeps the project's commit convention (format, prefix, length), the body still carries the why and what the diff cannot show, and the project's comment rules still decide whether a comment exists and what it may say (no narration of the code, no change history). Identifiers, strings, and log messages are code and keep the project's rules. If the skill is not available, do not stop or wait for it. If you have not already done so in this session, tell the user once that it can be installed with `/plugin marketplace add AminBlg/SimpleEnglish` and then `/plugin install simple-english@simple-english`. Then write short, plain, active sentences without it.
diff --git a/skills/fanning-out-with-worktrees/SKILL.md b/skills/fanning-out-with-worktrees/SKILL.md
index 724fb3f..122f7ec 100644
--- a/skills/fanning-out-with-worktrees/SKILL.md
+++ b/skills/fanning-out-with-worktrees/SKILL.md
@@ -60,6 +60,7 @@ Each dispatch prompt MUST include:
2. **Context handoff.** State file path, plan path, spec path, the issue number it's working, the relevant contract row(s) (Name + Producer + Consumer + Shape + Realization), **and the plan's `## Conventions` block**. The subagent implements **against the contract and the conventions** — it does not re-discover or re-design either, and it does not invent its own directory layout or naming scheme. A subagent handed contracts but not conventions will name and structure locally, and the merged feature reads as written by a committee (see `feature-dev-workflow:maintaining-architectural-coherence`).
3. **Implementation skills.** `superpowers:test-driven-development` + `feature-dev-workflow:testing-a-feature` for every change, and `feature-dev-workflow:writing-code-comments` for every comment the change adds, edits, or deletes.
4. **PR completion.** A stack layer's subagent skips this item and reports to the orchestrator, which opens the stack's PRs (see the stack paragraph above). A sequential layer's subagent reports its finished branch and head commit without pushing, because the orchestrator pushes the stack's worktree with `gh stack push`. A parallel layer's subagent pushes its branch from its temporary worktree first, then reports. Every other subagent, when the implementation is done and verified, invokes `feature-dev-workflow:opening-a-pull-request`. The base and body keyword depend on `sub_pr_target` in the state file: when `feature-branch`, use `--base /` and `Towards #` in the body (`Fixes`/`Closes` don't fire on non-default-branch merges; `Towards` keeps the issue open until the orchestrator closes it manually after the merge); when `main`, use `--base main` and the type-appropriate closing keyword in the body — `Fixes #` for a bug sub-issue, `Closes #` otherwise; either fires automatically on merge to the default branch (see `feature-dev-workflow:opening-a-pull-request` for the distinction). No sub-PR keyword closes the epic, and in main mode the epic stays open for the user (see Step 7). The subagent reports the PR URL back to the orchestrator.
+5. **Bounded commands.** The bounded command line for every heavy command the subagent will run (tests, lint, build, typecheck), copied from the orchestrator's record, and the rule to use no other form. A subagent does not see the orchestrator's project memory, so a prompt without them sends it to the plain commands, and a wave of plain test runs is what freezes the machine. **REQUIRED SUB-SKILL:** `feature-dev-workflow:bounding-heavy-commands` (§Dispatching subagents) before writing the first dispatch prompt of a wave.
Each dispatch prompt also carries this instruction for the subagent: **OPTIONAL SUB-SKILL:** `simple-english:simple-english` for the prose of your commit bodies, code and doc comments, and PR body. If it is available, load it before you draft and write the sentences under it. Where its formatting rules (headings, bold, lists, or its register for chat replies) differ from the host skill or its template, the host skill and its template win. It sets sentence style only: the commit subject keeps the project's commit convention, and the project's comment rules still decide whether a comment exists and what it may say. If it is not available, do not stop or wait for it: write short, plain, active sentences and say in your report that it was missing. The orchestrator, not the subagent, gives the user the install hint (`/plugin marketplace add AminBlg/SimpleEnglish`, then `/plugin install simple-english@simple-english`), at most once per session.
@@ -143,6 +144,7 @@ When every wave is complete (every sub-issue closed, every row `self-merged`, ev
- **Orchestrator fixing review findings in place.** The worktree subagent wrote the code and holds the context; it fixes, then the orchestrator re-reviews. A silent orchestrator fix skips the author and erodes the shared understanding the parallel agents run on.
- **Letting the worktree subagent review its own PR.** A subagent reviewing the code it just wrote has the same blind spots in review that it had in implementation. The orchestrator owns sub-PR review precisely because it didn't write the code.
- **Letting a bubble-up concern die in one subagent.** Propagation is the whole point of the watch loop.
+- **Shrinking the wave to spare the machine.** The number of subagents does not decide the load; the commands they run do. Dispatch the wave the plan calls for and hand every subagent the bounded commands (dispatch item 5). Subagents that wait in the queue cost time, not memory. On a machine on which the wrapper cannot run, no queue exists: dispatch the same wave, and let only one subagent at a time run a heavy command, as `feature-dev-workflow:bounding-heavy-commands` says.
- **Forgetting to manually close the sub-issue when `sub_pr_target: feature-branch`.** The keyword doesn't fire on non-default-branch merges; the issue page silently shows "open" even though the work shipped.
- **Using `Towards #` when `sub_pr_target: main`.** `Closes` fires on merge to the default branch; `Towards` intentionally blocks auto-close. Using the wrong keyword silently leaves sub-issues open after they merge to main and forces a manual cleanup pass.
- **Letting the state file go stale.** A resumed session reads it as ground truth. Update every row as reality moves; commit **and push** the state-file diff per phase transition — an unpushed local commit diverges the feature branch the moment the next sub-PR squash-merges on GitHub (see Step 5.4).
diff --git a/skills/reviewing-feature-progress/SKILL.md b/skills/reviewing-feature-progress/SKILL.md
index 8244879..bf2880a 100644
--- a/skills/reviewing-feature-progress/SKILL.md
+++ b/skills/reviewing-feature-progress/SKILL.md
@@ -87,6 +87,8 @@ What this step writes depends on whether a later wave in the plan is still to be
At the same checkpoint, with the feature whole and its behavior settled, write or update the public-facing docs the feature touches before the integration PR opens or flips ready (or before the fan-out hands back when `sub_pr_target: main`) — the integration PR is the external-review surface, and its docs are part of the first impression. **REQUIRED SUB-SKILL:** `feature-dev-workflow:writing-docs` for what earns a doc and how to verify a reader can actually use it.
+**REQUIRED SUB-SKILL:** `feature-dev-workflow:bounding-heavy-commands` for how to run the checks below. The project-wide suite is the heaviest command of the feature, and a checkpoint often runs while other sessions verify their own work. Run it through the wrapper.
+
**REQUIRED SUB-SKILL:** `superpowers:verification-before-completion`. Run the project-wide checks where the integrated code lives, which depends on the state file's `sub_pr_target`:
- **`feature-branch`**: the main feature worktree, which holds the integration state (sub-worktrees only hold their own sub-branch):
diff --git a/templates/project-CLAUDE.md b/templates/project-CLAUDE.md
index 4a8af76..3b37761 100644
--- a/templates/project-CLAUDE.md
+++ b/templates/project-CLAUDE.md
@@ -17,7 +17,7 @@ flowchart TD
Shape -->|single PR| IssueOne[File one issue
feature or bug]
IssueOne --> PlanS[Write the plan
ordered tasks · dependencies]
PlanS --> Build[Implement directly
test-first · one commit per task]
- Build --> VerifyS[Verify green
tests · lint · typecheck]
+ Build --> VerifyS[Verify green
tests · lint · typecheck
each through the memory queue]
VerifyS --> PR1[Open PR → main
Fixes / Closes the issue]
Shape -->|many PRs| Epic[File an epic
+ one sub-issue per PR, linked]
@@ -27,7 +27,7 @@ flowchart TD
Wave --> Merge[Orchestrator reviews each sub-PR,
merges it, closes its sub-issue]
Merge --> Done{All sub-PRs
merged?}
Done -->|next wave| Wave
- Done -->|yes| VerifyM[Verify the integrated branch
green end to end]
+ Done -->|yes| VerifyM[Verify the integrated branch
green end to end, through the memory queue]
VerifyM --> PR2[Open the integration PR
feature → main · Closes the epic]
PR1 --> Ship([External review → act on the feedback,
comments checked for growth → merge
plan + state torn down in the same diff])
@@ -48,6 +48,7 @@ Invoke `feature-dev-workflow:planning-a-feature` at conception. It and the `**RE
| Code comments and doc comments (whether one exists, and what it holds) | `feature-dev-workflow:writing-code-comments` |
| Public-facing docs for what the feature changed (once structurally complete) | `feature-dev-workflow:writing-docs` |
| Verify-before-done | `superpowers:verification-before-completion` |
+| Run tests, lint, builds, and other heavy commands without exhausting the machine | `feature-dev-workflow:bounding-heavy-commands` |
| Open / flip pull requests | `feature-dev-workflow:opening-a-pull-request` |
| Loop a PR through automated (Copilot) review until clean (opt-in) | `feature-dev-workflow:copilot-review-loop` |
| Act on review feedback without growing comments into a second account of the code (every round of a review) | `feature-dev-workflow:addressing-review-feedback` |