From fbaa3075c432f2710cf5ad54deb65667818106df Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 24 Oct 2026 00:15:44 +0200 Subject: [PATCH] Block a docker run or docker create that sets no memory limit, and read docker's TLS and buildx --builder options as taking a value --- bin/rule_hook/docker_command.py | 53 +++++++++++++++++++++++++++++++++ bin/rule_hook/heavy_command.py | 43 +++++--------------------- bin/rule_hook/rules.py | 9 +++++- bin/rule_hook/test_rule_hook.py | 16 ++++++++-- docs/decisions.md | 2 +- todo.md | 8 ++--- 6 files changed, 86 insertions(+), 45 deletions(-) create mode 100644 bin/rule_hook/docker_command.py diff --git a/bin/rule_hook/docker_command.py b/bin/rule_hook/docker_command.py new file mode 100644 index 00000000..bfdd8062 --- /dev/null +++ b/bin/rule_hook/docker_command.py @@ -0,0 +1,53 @@ +"""What a simple command asks of docker, for rule-hook's rules: its subcommand, and whether a container it starts has a memory limit.""" +import posixpath +import re + +# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run. +LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "run-heavy", "time", "uvx", "yarn"}) +# 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 start a container, which takes the memory limit docker run's -m sets. +STARTS_CONTAINER = (["run"], ["create"], ["container", "run"], ["container", "create"]) +# -m4g is -m with its value attached; --memory-swap alone sets no limit. +MEMORY_LIMIT = re.compile(r"-m.*|--memory(=.*)?") + + +def tool_name(word: str) -> str: + """The tool a word names, such as mutmut for `mutmut>=3,<4` or `.venv/bin/mutmut`; empty for a word that names none, such as a file name.""" + named = re.fullmatch(r"([A-Za-z_-]+)(?:[<>=!~@].*)?", posixpath.basename(word)) + return named.group(1) if named else "" + + +def docker_arguments(words: list[str]) -> list[str] | None: + """The words after docker where the simple command runs it directly or through a launcher, as in nice -n 19 docker build .; None where it runs no docker.""" + names = [tool_name(word) for word in words] + # Past a launcher, docker may follow the launcher's own options and assignments; without one, the command itself is the tool. + reachable = names if names[:1] and names[0] in LAUNCHERS else names[:1] + return words[reachable.index("docker") + 1:] if "docker" in reachable else None + + +def docker_subcommand(words: list[str]) -> list[str]: + """The subcommand docker's words name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"].""" + positional: list[str] = [] + skip = False + for word in words: + if skip: + skip = False + elif word.startswith("-"): + skip = word in DOCKER_VALUED + else: + positional.append(word) + if positional[0] not in ("buildx", "compose", "container") or len(positional) == 2: + break + return positional + + +def unlimited_container(words: list[str]) -> bool: + """Whether the simple command starts a container through docker run or docker create, directly or through a launcher, and sets no memory limit. + + A --memory among the container's own arguments, past its image, reads as the limit too: telling it apart needs every value-taking option of docker run. + """ + arguments = docker_arguments(words) + if arguments is None or "--help" in arguments: + return False + return docker_subcommand(arguments) in STARTS_CONTAINER and not any(MEMORY_LIMIT.fullmatch(word) for word in arguments) diff --git a/bin/rule_hook/heavy_command.py b/bin/rule_hook/heavy_command.py index 635e7c26..a8b85175 100644 --- a/bin/rule_hook/heavy_command.py +++ b/bin/rule_hook/heavy_command.py @@ -1,21 +1,10 @@ """Whether a simple command is a heavy one, for the `run-heavy` rule: a docker build, or a run of a mutation tool.""" -import posixpath -import re +from rule_hook.docker_command import LAUNCHERS, docker_arguments, docker_subcommand, tool_name -# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run. -LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "time", "uvx", "yarn"}) # Each mutation tool, and the words that make its call a mutation run when one of them follows it within two words; where the set is empty, every call is one. MUTATORS = {"cargo": {"mutants"}, "infection": set(), "mutmut": {"run"}, "stryker": {"run"}} # Flags with which a tool only prints its help, version or list, so a call that carries one is light. Not -h, which docker run reads as the container's hostname. LIGHT_FLAGS = frozenset({"--help", "--list", "--version"}) -# The options of docker and docker compose that take a value, so the value is not read as a subcommand. -DOCKER_VALUED = frozenset({"--ansi", "--config", "--context", "--env-file", "--file", "--host", "--log-level", "--parallel", "--profile", "--progress", "--project-directory", "--project-name", "-c", "-f", "-H", "-l", "-p"}) - - -def tool_name(word: str) -> str: - """The tool a word names, such as mutmut for `mutmut>=3,<4` or `.venv/bin/mutmut`; empty for a word that names none, such as a file name.""" - named = re.fullmatch(r"([A-Za-z_-]+)(?:[<>=!~@].*)?", posixpath.basename(word)) - return named.group(1) if named else "" def heavy(words: list[str]) -> bool: @@ -23,31 +12,13 @@ def heavy(words: list[str]) -> bool: names = [tool_name(word) for word in words] if not names or "run-heavy" in names or LIGHT_FLAGS & set(words): return False - # Past a launcher, the tool may follow the launcher's own options and assignments, as in nice -n 19 docker build or uvx --with pytest mutmut run; without one, the command itself is the tool. - launched = names[0] in LAUNCHERS - reachable = names if launched else names[:1] - docker_at = reachable.index("docker") if "docker" in reachable else None - if docker_at is not None: - subcommand = docker_subcommand(words[docker_at + 1:]) - return subcommand in (["build"], ["buildx", "build"], ["compose", "build"]) or (subcommand[-1:] in (["run"], ["exec"]) and mutation_run(names[docker_at + 1:])) - return (launched or names[0] in MUTATORS) and mutation_run(names) + docker = docker_arguments(words) + if docker is not None: + subcommand = docker_subcommand(docker) + return subcommand in (["build"], ["buildx", "build"], ["compose", "build"]) or (subcommand[-1:] in (["run"], ["exec"]) and mutation_run(names[len(words) - len(docker):])) + # Past a launcher, the mutation tool may follow the launcher's own options, as in uvx --with pytest mutmut run. + return (names[0] in LAUNCHERS or names[0] in MUTATORS) and mutation_run(names) def mutation_run(names: list[str]) -> bool: return any(name in MUTATORS and (not MUTATORS[name] or MUTATORS[name] & set(names[i + 1:i + 3])) for i, name in enumerate(names)) - - -def docker_subcommand(words: list[str]) -> list[str]: - """The subcommand docker's words name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"].""" - positional: list[str] = [] - skip = False - for word in words: - if skip: - skip = False - elif word.startswith("-"): - skip = word in DOCKER_VALUED - else: - positional.append(word) - if positional[0] not in ("buildx", "compose") or len(positional) == 2: - break - return positional diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 178d00f4..cd039cd5 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -5,11 +5,12 @@ import typing from round_titles import CAP, lacks_counts, past_cap from git_command import commits +from rule_hook.docker_command import unlimited_container from rule_hook.heavy_command import heavy from review_folder import REPORTS from shell_command import Simple -RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"] +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"] @dataclasses.dataclass(frozen=True) @@ -29,6 +30,10 @@ RULES: dict[RuleName, Rule] = { "a commit message is one line, prefixed with the ticket ID when the work has one", "git commit takes its message as one -m with no line break; -F, a second -m and a heredoc are blocked", ), + "docker-run-memory": Rule( + "a container started with docker run or docker create has a memory limit, such as `--memory 4g --memory-swap 4g`, so one runaway container cannot starve the machine; --memory-swap equal to --memory keeps it out of swap", + "docker run, docker create, docker container run and docker container create, whether direct or through a launcher such as nice. A container a script or docker compose starts is not checked", + ), "ignorefile-sorted": Rule( "each block of an ignore file is sorted in code-point order, as LC_ALL=C sort does, since its order carries no meaning; where order matters, such as a re-include after its exclude, split the block with a blank line or a comment", "a .*ignore file; a block already unsorted before the edit is left alone", @@ -132,6 +137,8 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre for simple in simples: if heavy(simple.words): breaches.append(Breach("run-heavy", f"run `{' '.join(simple.words)[:80]}` under `~/.claude/bin/run-heavy`, in the background", simple.directory)) + if unlimited_container(simple.words): + breaches.append(Breach("docker-run-memory", f"give `{' '.join(simple.words)[:80]}` a memory limit, such as `--memory 4g --memory-swap 4g`", simple.directory)) for commit in found: if commit.from_file: breaches.append(Breach("commit-one-line", "pass the message as one -m '', not from a file", commit.directory)) diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 8925758c..850dd441 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -107,12 +107,22 @@ class CommandBreaches(unittest.TestCase): self.assertEqual(checked("git commit -m 'Answer the question in the README'"), []) def test_a_docker_build_or_a_mutation_run_outside_run_heavy_breaks_run_heavy(self): - for command in ["docker build -t x .", "cd /w && docker buildx build .", "docker compose build", "docker compose -f x.yml --verbose build app", "uvx --with pytest 'mutmut>=3,<4' run", "cargo mutants --in-diff d", "npx stryker run", "vendor/bin/infection --git-diff-lines", "docker compose run --rm app mutmut run", "docker run --rm -v /w:/w rust:1.90.0 cargo mutants", "docker compose exec app npx stryker run", "docker run -h box rust:1.90.0 cargo mutants", "nice -n 19 docker build .", "env DOCKER_BUILDKIT=1 docker build .", "time -p docker compose build"]: + for command in ["docker build -t x .", "cd /w && docker buildx build .", "docker compose build", "docker compose -f x.yml --verbose build app", "uvx --with pytest 'mutmut>=3,<4' run", "cargo mutants --in-diff d", "npx stryker run", "vendor/bin/infection --git-diff-lines", "docker compose run --rm app mutmut run", "docker run --rm -m 4g -v /w:/w rust:1.90.0 cargo mutants", "docker compose exec app npx stryker run", "docker run -h box -m 4g rust:1.90.0 cargo mutants", "nice -n 19 docker build .", "env DOCKER_BUILDKIT=1 docker build .", "time -p docker compose build", "docker --tlscacert ca.pem build .", "docker --tlscert c.pem --tlskey k.pem build .", "docker buildx --builder b build .", "docker container run -m 4g rust:1.90.0 cargo mutants", "uvx mutmut --verbose run"]: with self.subTest(command): self.assertEqual(checked(command), ["run-heavy"]) def test_a_heavy_command_under_run_heavy_or_a_light_docker_or_mutmut_call_passes(self): - for command in ["~/.claude/bin/run-heavy docker build -t x .", "/home/me/.claude/bin/run-heavy uvx mutmut run", "nice -n 19 ~/.claude/bin/run-heavy docker build .", "env X=1 run-heavy docker compose run app mutmut run", "docker images", "docker compose run --rm app go vet", "docker compose run app make build", "uvx 'mutmut>=3,<4' results", "echo docker build", "npx prettier --check infection.json5", "echo mutmut run", "env", "docker build --help", "cargo mutants --list", "infection --version"]: + for command in ["~/.claude/bin/run-heavy docker build -t x .", "/home/me/.claude/bin/run-heavy uvx mutmut run", "nice -n 19 ~/.claude/bin/run-heavy docker build .", "env X=1 run-heavy docker compose run app mutmut run", "docker images", "docker compose run --rm app go vet", "docker compose run app make build", "uvx 'mutmut>=3,<4' results", "echo docker build", "npx prettier --check infection.json5", "echo mutmut run", "env", "docker build --help", "cargo mutants --list", "infection --version", "uvx mutmut a b run"]: + with self.subTest(command): + 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", "~/.claude/bin/run-heavy docker run alpine:3.22.2 true"]: + 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 alpine:3.22.2 true", "docker run -m4g alpine:3.22.2 true", "docker run --memory 4g alpine:3.22.2 true", "docker run --rm --memory=4g --memory-swap=4g alpine:3.22.2 true", "docker container create -m 1g alpine:3.22.2", "docker run --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"]: with self.subTest(command): self.assertEqual(checked(command), []) @@ -467,7 +477,7 @@ class Hook(unittest.TestCase): def test_help_lists_every_rule(self): helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout - for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]: + for rule in ["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"]: self.assertIn(f" {rule}\n The rule: ", helped) self.assertIn("reviewer-report\n The rule: a reviewer writes nothing but its report", helped) self.assertRegex(helped, r" reviewer-report\n( .*\n){2} Takes no override\.\n") diff --git a/docs/decisions.md b/docs/decisions.md index 290f7dde..848847a4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -74,7 +74,7 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the ## machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available -2026-10-23, lilleman. Serves goal 1.5. On 2026-10-22 ai-sandbox, with 8 CPUs and 16 GiB, thrashed for hours: four to six loops ran mutation tests, full gates, `docker build`s and QEMU-booting e2e tests at once, and nothing told one loop how busy the machine was. lilleman chose both limits; no standard sets either, and GNU parallel's `--memfree`, which does the memory wait's job, has no default. A slot is a file lock, so a session that dies frees its slot. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/machine_load/` holds the slots and the memory share, `bin/run-heavy` takes a slot, `CLAUDE.md` → "Working with the codebase" has every session use it, and loop-claude's worker waits for the share. rule-hook's rule `run-heavy` blocks a `docker build`, and a run of a mutation tool stability-reviewer names, outside run-heavy, whether direct or inside a container. No program can tell a gate script from a light one, so only `CLAUDE.md` asks a session to run a gate under run-heavy. Valid while one machine runs several loops at once. +2026-10-23, lilleman. Serves goal 1.5. On 2026-10-22 ai-sandbox, with 8 CPUs and 16 GiB, thrashed for hours: four to six loops ran mutation tests, full gates, `docker build`s and QEMU-booting e2e tests at once, and nothing told one loop how busy the machine was. lilleman chose both limits; no standard sets either, and GNU parallel's `--memfree`, which does the memory wait's job, has no default. A slot is a file lock, so a session that dies frees its slot. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/machine_load/` holds the slots and the memory share, `bin/run-heavy` takes a slot, `CLAUDE.md` → "Working with the codebase" has every session use it, and loop-claude's worker waits for the share. rule-hook's rule `run-heavy` blocks a `docker build`, and a run of a mutation tool stability-reviewer names, outside run-heavy, whether direct or inside a container. No program can tell a gate script from a light one, so only `CLAUDE.md` asks a session to run a gate under run-heavy. On 2026-10-23 a slot alone did not stop a hang: a reviewer's stress probes ran in `docker run` with no memory limit, each to 2 GiB, beside a mutation run in its slot. So rule-hook's rule `docker-run-memory` blocks a `docker run` or `docker create` a session types without `--memory` (todo item 228); a container a script starts is out of its sight. Valid while one machine runs several loops at once. ## principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason diff --git a/todo.md b/todo.md index 9f7ff6b6..cc6f6dc0 100644 --- a/todo.md +++ b/todo.md @@ -16,7 +16,7 @@ | 59 | 0.4.0 | | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 2 | 1 | 3 | 4 | 3 | 1.4 by 6 | 6.0 | | 167 | 0.4.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 5.6 | | 6 | 0.4.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 5.3 | -| 228 | 0.4.0 | | | **Block a `docker run` or `docker create` that sets no memory limit outside run-heavy, in a rule-hook rule `docker-run-memory`.** | 2 | 1 | 3 | 4 | 3 | 1.5 by 3 | 2.9 | +| 228 | 0.4.0 | | | **Block a `docker run` or `docker create` that sets no memory limit, in a rule-hook rule `docker-run-memory`.** | 2 | 1 | 3 | 4 | 3 | 1.5 by 3 | 2.9 | | 225 | 0.4.0 | | | **Add the value-taking options of docker that `DOCKER_VALUED` lacks, so rule-hook's `run-heavy` rule reads their value as a value and not as the subcommand.** | 1 | 1 | 3 | 3 | 2 | 1.5 by 2 | 2.6 | | 227 | 0.4.0 | | | **Cap the memory of each container a heavy command starts under run-heavy at its slot's share, and have stability-reviewer size a mutation run's concurrency to fit that cap.** | 3 | 2 | 3 | 6 | 5 | 1.5 by 5 | 1.9 | | 1 | 0.5.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 | @@ -89,9 +89,9 @@ rule-hook checks Agent calls (item 163) but no Skill calls. A worker that invoke Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost. -### 228. Block a `docker run` or `docker create` that sets no memory limit outside run-heavy, in a rule-hook rule `docker-run-memory`. +### 228. Block a `docker run` or `docker create` that sets no memory limit, in a rule-hook rule `docker-run-memory`. -Part of the 2026-10-23 hang item 227 describes: a reviewer's probes ran in `docker run` with no `--memory`, and each grew to 2 GiB. The rule reads `-m`, `--memory` and `--memory=…`, through the launchers and docker options `bin/rule_hook/heavy_command.py` already reads. A command under run-heavy passes, as item 227 caps it there. A container a script starts, such as a project's `in_image` function, is out of the rule's sight. Test first in `bin/rule_hook/test_rule_hook.py`. +Part of the 2026-10-23 hang item 227 describes: a reviewer's probes ran in `docker run` with no `--memory`, and each grew to 2 GiB. The rule reads `-m`, `--memory` and `--memory=…`, through the launchers and docker options `bin/rule_hook/heavy_command.py` already reads. A container a script starts, such as a project's `in_image` function, is out of the rule's sight. Test first in `bin/rule_hook/test_rule_hook.py`. ### 225. Add the value-taking options of docker that `DOCKER_VALUED` lacks, so rule-hook's `run-heavy` rule reads their value as a value and not as the subcommand. @@ -101,7 +101,7 @@ Found by review of PR #370, against code that moved unchanged into `bin/rule_hoo On 2026-10-23 ai-sandbox, with 8 CPUs and 7.6 GiB, hung in swap until a hard reset. One heavy command held its slot as the `machine load:` decision asks: adf-codec's stability reviewer ran Stryker with concurrency 4, each copy running the whole `node --test` suite, in one container that reached 4 GiB. Beside it, the same reviewer ran stress probes in `docker run` outside run-heavy, each to V8's 2 GiB heap limit. The slots cap how many heavy commands run at once, not how much memory one takes. -run-heavy cannot place the command in a cgroup: none is delegated to the user, and dockerd starts the containers outside the command's process tree. So run-heavy puts first on the command's `PATH` a `docker` that adds `--memory` and `--memory-swap`, both at the slot's share, to each `docker run`, `docker create` and `docker container run|create` that sets neither, then runs the real docker. The share is the memory the `machine load:` decision leaves to heavy commands, three quarters of MemTotal, split evenly across the slots. A `docker compose` service, and a docker named by its full path, keep no cap. Update the `machine load:` decision, run-heavy's help and stability-reviewer's mutation step, which sizes Stryker's or mutmut's concurrency so the run fits the cap. Test first in `bin/run_heavy/test_run_heavy.py`. +run-heavy cannot place the command in a cgroup: none is delegated to the user, and dockerd starts the containers outside the command's process tree. So run-heavy puts first on the command's `PATH` a `docker` that adds `--memory` and `--memory-swap`, both at the slot's share, to each `docker run`, `docker create` and `docker container run|create` that sets neither, then runs the real docker. The share is the memory the `machine load:` decision leaves to heavy commands, three quarters of MemTotal, split evenly across the slots. A `docker compose` service, and a docker named by its full path, keep no cap. Update the `machine load:` decision, run-heavy's help and stability-reviewer's mutation step, which sizes Stryker's or mutmut's concurrency so the run fits the cap. Once run-heavy caps them, let rule-hook's `docker-run-memory` pass a `docker run` under run-heavy. Test first in `bin/run_heavy/test_run_heavy.py`. ### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.