Answer architecture round 1: 0 🔴, 3 🟡 (0 misread); keep the slot's share beside ROOM_SHARE in machine_load, move the rule's predicate into rule_hook, and have capped set both limits itself instead of leaning on docker taking the last option
This commit is contained in:
+29
-19
@@ -1,16 +1,18 @@
|
||||
"""What a docker command asks of docker: its subcommand, and whether a container it starts has a memory limit and a swap limit."""
|
||||
"""What a docker command asks of docker: its subcommand, whether a container it makes has a memory limit and a swap limit, and those arguments with the limits a container lacks."""
|
||||
import re
|
||||
|
||||
from shell_command import launched
|
||||
|
||||
# The options of docker, docker buildx and docker compose that take a value, so the value is not read as a subcommand.
|
||||
DOCKER_VALUED = frozenset({"--ansi", "--builder", "--config", "--context", "--env-file", "--file", "--host", "--log-level", "--parallel", "--profile", "--progress", "--project-directory", "--project-name", "--tlscacert", "--tlscert", "--tlskey", "-c", "-f", "-H", "-l", "-p"})
|
||||
# The subcommands that make a container, whose memory limits docker reads from the same options.
|
||||
STARTS_CONTAINER = (["container", "create"], ["container", "run"], ["create"], ["run"])
|
||||
# A size as docker reads one, such as 4g, 512M or 1.5GiB: the pattern go-units' RAMInBytes parses.
|
||||
SIZE = r"\d+(?:\.\d+)*[kKmMgGtTpP]?[iI]?[bB]?"
|
||||
MEMORY_OPTIONS = ("-m", "--memory")
|
||||
SWAP_OPTIONS = ("--memory-swap",)
|
||||
# A swap limit is a size other than 0: docker reads --memory-swap -1 as unlimited swap, and 0 as unset.
|
||||
SWAP = rf"(?!0+(?:\.0+)*[kKmMgGtTpP]?[iI]?[bB]?$){SIZE}"
|
||||
# Any value --memory-swap takes, -1 and 0 among them.
|
||||
ANY_SWAP = rf"-1|{SIZE}"
|
||||
|
||||
|
||||
def docker_subcommand(arguments: list[str]) -> list[str]:
|
||||
@@ -35,39 +37,47 @@ 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 = option_value(arguments, ("-m", "--memory"), SIZE) and option_value(arguments, ("--memory-swap",), SWAP)
|
||||
limited = option_value(arguments, MEMORY_OPTIONS, SIZE) and option_value(arguments, SWAP_OPTIONS, SWAP)
|
||||
return subcommand in STARTS_CONTAINER and not limited and not helped(arguments, subcommand)
|
||||
|
||||
|
||||
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."""
|
||||
"""docker's arguments with both limits set right after the subcommand, where a container they make lacks one: the container's own memory limit, or else its swap limit, or else share, for each. Its swap limit stays where it has one; an unlimited or unset one gives way."""
|
||||
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:]]
|
||||
memory = option_value(arguments, MEMORY_OPTIONS, SIZE) or option_value(arguments, SWAP_OPTIONS, SWAP) or share
|
||||
swap = option_value(arguments, SWAP_OPTIONS, SWAP) or memory
|
||||
rest = without(without(arguments, MEMORY_OPTIONS, SIZE), SWAP_OPTIONS, ANY_SWAP)
|
||||
after = rest.index(docker_subcommand(rest)[-1]) + 1
|
||||
return [*rest[:after], "--memory", memory, "--memory-swap", swap, *rest[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:], ""]):
|
||||
found = option_at(arguments, options, pattern)
|
||||
return found[2] if found else None
|
||||
|
||||
|
||||
def without(arguments: list[str], options: tuple[str, ...], pattern: str) -> list[str]:
|
||||
"""The arguments with each of the options removed, with its value, where pattern matches the value."""
|
||||
while found := option_at(arguments, options, pattern):
|
||||
start, length, _ = found
|
||||
arguments = [*arguments[:start], *arguments[start + length:]]
|
||||
return arguments
|
||||
|
||||
|
||||
def option_at(arguments: list[str], options: tuple[str, ...], pattern: str) -> tuple[int, int, str] | None:
|
||||
"""Where the arguments first give one of the options a value pattern matches: its index, its length in words and the value."""
|
||||
for at, (word, following) in enumerate(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
|
||||
return at, 1, attached
|
||||
if word == option and re.fullmatch(pattern, following):
|
||||
return following
|
||||
return at, 2, 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"})
|
||||
# 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:
|
||||
"""Whether docker only prints its help: a --help before the subcommand or as the first word after it, not one the container's own command takes."""
|
||||
after = arguments.index(subcommand[-1]) + 1
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it, and whether at least ROOM_SHARE of it is available, which leaves room for a worker."""
|
||||
"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it, whether at least ROOM_SHARE of it is available, which leaves room for a worker, and each heavy slot's share of the rest."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
@@ -17,6 +17,10 @@ class Memory:
|
||||
def has_room(self) -> bool:
|
||||
return self.available >= ROOM_SHARE * self.total
|
||||
|
||||
def slot_share(self, slots: int) -> str:
|
||||
"""The memory each heavy slot's containers may take, as docker writes a size: what ROOM_SHARE leaves, split evenly across the slots."""
|
||||
return f"{int(self.total * (1 - ROOM_SHARE)) // slots // 1024}m"
|
||||
|
||||
|
||||
def parsed(meminfo: str) -> Memory | None:
|
||||
"""The memory a /proc/meminfo text states; None where it lacks MemAvailable or MemTotal."""
|
||||
|
||||
@@ -6,9 +6,9 @@ import typing
|
||||
from round_titles import CAP, lacks_counts, past_cap
|
||||
from git_command import commits
|
||||
from rule_hook.heavy_command import heavy
|
||||
from shell_command import launched, Simple
|
||||
from review_folder import REPORTS
|
||||
from shell_command import Simple
|
||||
from docker_command import unlimited_container
|
||||
from docker_command import unlimited
|
||||
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]
|
||||
|
||||
@@ -151,6 +151,13 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre
|
||||
return breaches
|
||||
|
||||
|
||||
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"})
|
||||
# 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 file_breaches(path: str, before: str, added: str, after: str) -> list[Breach]:
|
||||
"""Breaches in an edit of path: added is the text the edit writes, after the whole file it leaves."""
|
||||
breaches = [Breach("no-ai-attribution", f"{path} would carry an attribution", posixpath.dirname(path))] if ATTRIBUTION.search(added) else []
|
||||
|
||||
@@ -12,8 +12,9 @@ until the command, and every process that inherited the lock, exits. Its exit co
|
||||
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.
|
||||
container that sets one of the two limits keeps it, and gets the other as large; an unlimited
|
||||
swap, --memory-swap -1, gives way. 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.
|
||||
@@ -55,10 +56,10 @@ def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memor
|
||||
|
||||
|
||||
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."""
|
||||
"""What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; 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", "")])}
|
||||
return {SHARE: memory.slot_share(slots), "PATH": os.pathsep.join([str(FOLDER), env.get("PATH", "")])}
|
||||
|
||||
|
||||
def held_slot(folder: pathlib.Path, slots: int) -> int | Failure:
|
||||
|
||||
@@ -14,9 +14,16 @@ class Capped(unittest.TestCase):
|
||||
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_s_own_limit_is_kept_and_sets_the_limit_it_lacks(self):
|
||||
for given, expected in [
|
||||
(["run", "-m", "10g", "img"], ["run", "--memory", "10g", "--memory-swap", "10g", "img"]),
|
||||
(["run", "--memory=12g", "img"], ["run", "--memory", "12g", "--memory-swap", "12g", "img"]),
|
||||
(["run", "--memory-swap", "2g", "img"], ["run", "--memory", "2g", "--memory-swap", "2g", "img"]),
|
||||
(["run", "-m", "4g", "--memory-swap", "-1", "img"], ["run", "--memory", "4g", "--memory-swap", "4g", "img"]),
|
||||
(["run", "-m4g", "--memory-swap=0", "img", "python", "-m", "pytest"], ["run", "--memory", "4g", "--memory-swap", "4g", "img", "python", "-m", "pytest"]),
|
||||
]:
|
||||
with self.subTest(given):
|
||||
self.assertEqual(capped(given, "6144m"), expected)
|
||||
|
||||
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"]]:
|
||||
|
||||
Reference in New Issue
Block a user