Cap the memory of each container a heavy command makes under run-heavy at its slot's share, and have stability-reviewer size a mutation run's concurrency to fit it
This commit is contained in:
+23
-6
@@ -35,20 +35,37 @@ def unlimited(arguments: list[str]) -> bool:
|
||||
The container's own arguments, past its image, are read too: telling them apart needs every value-taking option of docker run. So a -m 4g there reads as a limit, while python -m pytest does not, since pytest is no size.
|
||||
"""
|
||||
subcommand = docker_subcommand(arguments)
|
||||
limited = given(arguments, ("-m", "--memory"), SIZE) and given(arguments, ("--memory-swap",), SWAP)
|
||||
limited = option_value(arguments, ("-m", "--memory"), SIZE) and option_value(arguments, ("--memory-swap",), SWAP)
|
||||
return subcommand in STARTS_CONTAINER and not limited and not helped(arguments, subcommand)
|
||||
|
||||
|
||||
def given(arguments: list[str], options: tuple[str, ...], pattern: str) -> bool:
|
||||
"""Whether the arguments give one of the options a value pattern matches, as its next word or attached, as in -m4g or --memory=4g."""
|
||||
attached = re.compile("|".join(re.escape(option) + ("" if len(option) == 2 else "=") + f"(?:{pattern})" for option in options))
|
||||
return any(attached.fullmatch(word) or (word in options and re.fullmatch(pattern, following)) for word, following in zip(arguments, [*arguments[1:], ""]))
|
||||
def capped(arguments: list[str], share: str) -> list[str]:
|
||||
"""docker's arguments with the limits a container they make lacks, put right after the subcommand: share for each, except a swap limit beside the container's own memory limit, which takes that limit, as docker refuses less swap than memory."""
|
||||
if not unlimited(arguments):
|
||||
return arguments
|
||||
memory = option_value(arguments, ("-m", "--memory"), SIZE)
|
||||
after = arguments.index(docker_subcommand(arguments)[-1]) + 1
|
||||
limits = ["--memory-swap", memory] if memory else ["--memory", share, "--memory-swap", share]
|
||||
return [*arguments[:after], *limits, *arguments[after:]]
|
||||
|
||||
|
||||
def option_value(arguments: list[str], options: tuple[str, ...], pattern: str) -> str | None:
|
||||
"""The value the arguments give one of the options, where pattern matches it, as its next word or attached, as in -m4g or --memory=4g; None where they give none."""
|
||||
for word, following in zip(arguments, [*arguments[1:], ""]):
|
||||
for option in options:
|
||||
attached = word.removeprefix(option if len(option) == 2 else option + "=")
|
||||
if attached != word and re.fullmatch(pattern, attached):
|
||||
return attached
|
||||
if word == option and re.fullmatch(pattern, following):
|
||||
return following
|
||||
return None
|
||||
|
||||
|
||||
def unlimited_container(words: list[str]) -> bool:
|
||||
"""Whether the simple command, directly or through a launcher, starts a container that lacks a memory limit or a swap limit."""
|
||||
docker = launched(words, {"docker"})
|
||||
return docker is not None and unlimited(docker.arguments)
|
||||
# Under run-heavy, its docker adds the limits a container lacks.
|
||||
return docker is not None and "run-heavy" not in docker.launchers and unlimited(docker.arguments)
|
||||
|
||||
|
||||
def helped(arguments: list[str], subcommand: list[str]) -> bool:
|
||||
|
||||
@@ -117,12 +117,12 @@ class CommandBreaches(unittest.TestCase):
|
||||
self.assertEqual(checked(command), [])
|
||||
|
||||
def test_a_docker_run_or_create_without_a_memory_limit_breaks_docker_run_memory(self):
|
||||
for command in ["docker run --rm node:24.22.1-alpine3.24 node x.js", "cd /w && docker run -v /w:/w alpine:3.22.2 true", "docker create alpine:3.22.2", "docker container run alpine:3.22.2 true", "docker container create alpine:3.22.2", "nice -n 19 docker run alpine:3.22.2 true", "docker -H unix:///d.sock run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 true", "docker run -m 4g alpine:3.22.2 true", "docker run --memory=4g alpine:3.22.2 sh -c 'x --memory-swap 4g'", "docker run -m 4g alpine:3.22.2 tool --memory-swap", "docker run -m 4g --memory-swap -1 alpine:3.22.2 true", "docker run -m 4g --memory-swap=0 alpine:3.22.2 true", "~/.claude/bin/run-heavy docker run alpine:3.22.2 true", "docker run --rm python:3.13.1 python -m pytest", "docker run alpine:3.22.2 git commit -m x", "timeout 60 docker run alpine:3.22.2 true", "docker run node:24.22.1-alpine3.24 node --help", "docker run alpine:3.22.2 --help", "docker run -m 4g alpine:3.22.2 sleep 60"]:
|
||||
for command in ["docker run --rm node:24.22.1-alpine3.24 node x.js", "cd /w && docker run -v /w:/w alpine:3.22.2 true", "docker create alpine:3.22.2", "docker container run alpine:3.22.2 true", "docker container create alpine:3.22.2", "nice -n 19 docker run alpine:3.22.2 true", "docker -H unix:///d.sock run alpine:3.22.2 true", "docker run --memory-swap 4g alpine:3.22.2 true", "docker run -m 4g alpine:3.22.2 true", "docker run --memory=4g alpine:3.22.2 sh -c 'x --memory-swap 4g'", "docker run -m 4g alpine:3.22.2 tool --memory-swap", "docker run -m 4g --memory-swap -1 alpine:3.22.2 true", "docker run -m 4g --memory-swap=0 alpine:3.22.2 true", "docker run --rm python:3.13.1 python -m pytest", "docker run alpine:3.22.2 git commit -m x", "timeout 60 docker run alpine:3.22.2 true", "docker run node:24.22.1-alpine3.24 node --help", "docker run alpine:3.22.2 --help", "docker run -m 4g alpine:3.22.2 sleep 60"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(checked(command), ["docker-run-memory"])
|
||||
|
||||
def test_a_docker_run_with_a_memory_limit_or_another_docker_call_passes_docker_run_memory(self):
|
||||
for command in ["docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run -m4g --memory-swap=4g alpine:3.22.2 true", "docker run --memory 512M --memory-swap 1g alpine:3.22.2 true", "docker run -m 1073741824 --memory-swap 2g alpine:3.22.2 true", "timeout 60 docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run --rm --memory=1.5GiB --memory-swap=1.5GiB alpine:3.22.2 true", "docker container create -m 1g --memory-swap 1g alpine:3.22.2", "docker run --help", "docker container run --help", "docker --help", "docker ps", "docker images", "docker container ls", "docker compose run --rm app go vet", "docker exec box true", "echo docker run alpine:3.22.2"]:
|
||||
for command in ["docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run -m4g --memory-swap=4g alpine:3.22.2 true", "docker run --memory 512M --memory-swap 1g alpine:3.22.2 true", "docker run -m 1073741824 --memory-swap 2g alpine:3.22.2 true", "timeout 60 docker run -m 4g --memory-swap 4g alpine:3.22.2 true", "docker run --rm --memory=1.5GiB --memory-swap=1.5GiB alpine:3.22.2 true", "docker container create -m 1g --memory-swap 1g alpine:3.22.2", "docker run --help", "docker container run --help", "docker --help", "docker ps", "docker images", "docker container ls", "docker compose run --rm app go vet", "docker exec box true", "echo docker run alpine:3.22.2", "~/.claude/bin/run-heavy docker run alpine:3.22.2 true"]:
|
||||
with self.subTest(command):
|
||||
self.assertEqual(checked(command), [])
|
||||
|
||||
|
||||
+2
-1
@@ -5,7 +5,8 @@ import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from machine_load.memory import read_memory
|
||||
from machine_load.slots import usable_cpus
|
||||
from run_heavy import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, usable_cpus()))
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, usable_cpus(), read_memory()))
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""The docker a heavy command finds first on its PATH: it gives a container the command makes the limits it lacks, the slot's memory share in RUN_HEAVY_MEMORY, then runs the real docker."""
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from docker_command import capped
|
||||
|
||||
FOLDER = pathlib.Path(__file__).resolve().parent / "path_entry"
|
||||
SHARE = "RUN_HEAVY_MEMORY"
|
||||
NOT_FOUND = 127
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
"""Replaces this process with the real docker; returns only where none is found."""
|
||||
path = os.pathsep.join(entry for entry in env.get("PATH", "").split(os.pathsep) if pathlib.Path(entry or ".").resolve() != FOLDER)
|
||||
docker = shutil.which("docker", path=path)
|
||||
if docker is None:
|
||||
print("run-heavy: docker: command not found", file=sys.stderr)
|
||||
return NOT_FOUND
|
||||
share = env.get(SHARE)
|
||||
os.execve(docker, [docker, *(capped(argv, share) if share else argv)], {**env, "PATH": path})
|
||||
+17
-2
@@ -9,6 +9,12 @@ $XDG_STATE_HOME/run-heavy (default ~/.local/state/run-heavy). While every slot i
|
||||
says so once on stderr and waits. It then replaces itself with the command. The slot's lock stays held
|
||||
until the command, and every process that inherited the lock, exits. Its exit code is the command's.
|
||||
|
||||
Each container the command makes with docker run or docker create gets a memory limit and a swap limit,
|
||||
both the slot's share, where it sets neither: three quarters of the machine's memory, split across the
|
||||
slots. A docker first on the command's PATH adds them, and passes every other call on unchanged. A
|
||||
container that sets its own memory limit keeps it, with a swap limit as large. The share is in
|
||||
RUN_HEAVY_MEMORY. A docker compose service, or a docker named by its full path, gets no limit.
|
||||
|
||||
A command it runs carries the slot's number in RUN_HEAVY_SLOT, and run-heavy called with that set
|
||||
runs its command at once, so a gate that wraps its own steps cannot wait on itself.
|
||||
|
||||
@@ -21,6 +27,8 @@ import sys
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from run_heavy.capped_docker import FOLDER, SHARE
|
||||
from machine_load.memory import Memory
|
||||
from machine_load.slots import slot_count, slot_folder, waited_slot
|
||||
|
||||
OWN_FAILURE = 125
|
||||
@@ -30,7 +38,7 @@ HELD = "RUN_HEAVY_SLOT"
|
||||
USAGE = "usage: run-heavy <command> [<arg>...]"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None) -> int:
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memory: Memory | None) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
@@ -42,10 +50,17 @@ def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None) -> in
|
||||
if isinstance(slot, Failure):
|
||||
print(f"run-heavy: {slot.reason}", file=sys.stderr)
|
||||
return OWN_FAILURE
|
||||
env = {**env, HELD: str(slot)}
|
||||
env = {**env, HELD: str(slot), **capping(memory, slot_count(cpus), env)}
|
||||
return run(argv, env)
|
||||
|
||||
|
||||
def capping(memory: Memory | None, slots: int, env: typing.Mapping[str, str]) -> dict[str, str]:
|
||||
"""What the command's environment needs for its docker to cap each container it makes at the slot's share: three quarters of the memory, which the quarter loop-claude keeps free for a worker leaves, split across the slots. Nothing where the memory is unknown, as off Linux."""
|
||||
if memory is None:
|
||||
return {}
|
||||
return {SHARE: f"{memory.total * 3 // 4 // slots // 1024}m", "PATH": os.pathsep.join([str(FOLDER), env.get("PATH", "")])}
|
||||
|
||||
|
||||
def held_slot(folder: pathlib.Path, slots: int) -> int | Failure:
|
||||
"""The number of the slot this call holds, its lock left for the command to inherit, or why no slot could be taken."""
|
||||
try:
|
||||
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
|
||||
|
||||
from run_heavy import capped_docker
|
||||
|
||||
sys.exit(capped_docker.main(sys.argv[1:], os.environ))
|
||||
@@ -10,6 +10,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from run_heavy import main
|
||||
from machine_load.memory import read_memory
|
||||
from machine_load.slots import slot_count, usable_cpus
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "run-heavy"
|
||||
@@ -82,6 +83,37 @@ class RunHeavy(unittest.TestCase):
|
||||
self.assertEqual((denied.returncode, denied.stdout), (126, ""))
|
||||
self.assertIn(unrunnable.name, denied.stderr)
|
||||
|
||||
def fake_docker(self) -> dict[str, str]:
|
||||
"""An environment whose PATH finds, ahead of any real one, a docker that prints the arguments it was given."""
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
docker = pathlib.Path(folder.name) / "docker"
|
||||
docker.write_text("#!/bin/sh\necho \"$@\"\n")
|
||||
docker.chmod(0o755)
|
||||
return {**self.env, "PATH": f"{folder.name}:{self.env['PATH']}"}
|
||||
|
||||
def test_a_docker_run_without_limits_gets_three_quarters_of_the_memory_split_across_the_slots(self):
|
||||
memory = read_memory()
|
||||
assert memory is not None
|
||||
share = f"{memory.total * 3 // 4 // slot_count(usable_cpus()) // 1024}m"
|
||||
result = self.run_tool("docker", "run", "--rm", "img", "true", env=self.fake_docker())
|
||||
self.assertEqual((result.returncode, result.stdout), (0, f"run --memory {share} --memory-swap {share} --rm img true\n"))
|
||||
|
||||
def test_a_docker_call_with_its_own_limits_or_that_starts_no_container_is_passed_on_unchanged(self):
|
||||
env = self.fake_docker()
|
||||
for args in [["run", "-m", "40g", "--memory-swap", "40g", "img"], ["ps", "-a"], ["build", "."]]:
|
||||
with self.subTest(args):
|
||||
result = self.run_tool("docker", *args, env=env)
|
||||
self.assertEqual((result.returncode, result.stdout), (0, " ".join(args) + "\n"))
|
||||
|
||||
def test_a_capped_docker_that_finds_no_docker_exits_127_saying_so(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
(pathlib.Path(folder.name) / "python3").symlink_to(sys.executable)
|
||||
result = self.run_tool("docker", "ps", env={**self.env, "PATH": folder.name})
|
||||
self.assertEqual((result.returncode, result.stdout), (127, ""))
|
||||
self.assertIn("docker", result.stderr)
|
||||
|
||||
def test_no_command_exits_125_with_the_usage_and_help_exits_0(self):
|
||||
bare = self.run_tool()
|
||||
self.assertEqual((bare.returncode, bare.stdout), (125, ""))
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import unittest
|
||||
|
||||
from docker_command import capped
|
||||
|
||||
|
||||
class Capped(unittest.TestCase):
|
||||
def test_a_container_without_limits_gets_the_share_for_both(self):
|
||||
for given, expected in [
|
||||
(["run", "--rm", "img", "true"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "--rm", "img", "true"]),
|
||||
(["-H", "unix:///d.sock", "run", "img"], ["-H", "unix:///d.sock", "run", "--memory", "6144m", "--memory-swap", "6144m", "img"]),
|
||||
(["container", "create", "img"], ["container", "create", "--memory", "6144m", "--memory-swap", "6144m", "img"]),
|
||||
(["run", "img", "python", "-m", "pytest"], ["run", "--memory", "6144m", "--memory-swap", "6144m", "img", "python", "-m", "pytest"]),
|
||||
]:
|
||||
with self.subTest(given):
|
||||
self.assertEqual(capped(given, "6144m"), expected)
|
||||
|
||||
def test_a_container_s_own_memory_limit_is_kept_and_caps_its_swap(self):
|
||||
self.assertEqual(capped(["run", "-m", "10g", "img"], "6144m"), ["run", "--memory-swap", "10g", "-m", "10g", "img"])
|
||||
self.assertEqual(capped(["run", "--memory=12g", "img"], "6144m"), ["run", "--memory-swap", "12g", "--memory=12g", "img"])
|
||||
|
||||
def test_a_container_with_both_limits_or_another_docker_call_is_left_alone(self):
|
||||
for given in [["run", "-m", "10g", "--memory-swap", "12g", "img"], ["ps"], ["build", "."], ["run", "--help"], ["compose", "run", "app"], ["exec", "box", "true"]]:
|
||||
with self.subTest(given):
|
||||
self.assertEqual(capped(given, "6144m"), given)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user