diff --git a/.gitignore b/.gitignore index 2bcf7f05..45938304 100644 --- a/.gitignore +++ b/.gitignore @@ -25,6 +25,7 @@ !bin/claude_code/ !bin/claude_code/*.py !bin/comprehension_history.py +!bin/docker_command.py !bin/failure.py !bin/file_writes.py !bin/git_command.py diff --git a/AGENTS.md b/AGENTS.md index 534811e5..cdfa1df2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,6 +16,7 @@ Decisions live in `docs/decisions.md`: - loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop - 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 +- machine load: every container a session starts with `docker run` or `docker create` sets a memory limit as large as its work needs, which rule-hook's `docker-run-memory` enforces, and no daemon-wide cap limits all containers together - 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 - reading cost and `score-outcomes`: each waits for 10 finished chunks before it shows a median - reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item diff --git a/bin/docker_command.py b/bin/docker_command.py new file mode 100644 index 00000000..eb2004dc --- /dev/null +++ b/bin/docker_command.py @@ -0,0 +1,41 @@ +"""What a docker command asks of docker: its subcommand, and whether a container it starts has a memory limit.""" +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 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 docker_subcommand(arguments: list[str]) -> list[str]: + """The subcommand docker's arguments name, past its options: such as ["build"], ["compose", "run"] or ["buildx", "build"].""" + positional: list[str] = [] + skip = False + for word in arguments: + 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(arguments: list[str]) -> bool: + """Whether docker's arguments start a container, with docker run or docker create, and set it 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. + """ + return "--help" not in arguments and docker_subcommand(arguments) in STARTS_CONTAINER and not any(MEMORY_LIMIT.fullmatch(word) for word in arguments) + + +def unlimited_container(words: list[str]) -> bool: + """Whether the simple command, directly or through a launcher, starts a container that has no memory limit.""" + docker = launched(words, {"docker"}) + return docker is not None and unlimited(docker.arguments) diff --git a/bin/rule_hook/docker_command.py b/bin/rule_hook/docker_command.py deleted file mode 100644 index bfdd8062..00000000 --- a/bin/rule_hook/docker_command.py +++ /dev/null @@ -1,53 +0,0 @@ -"""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 1c816465..106b61a7 100644 --- a/bin/rule_hook/heavy_command.py +++ b/bin/rule_hook/heavy_command.py @@ -1,23 +1,23 @@ """Whether a simple command is a heavy one, for the `run-heavy` rule: a docker build, or a run of a mutation tool.""" -from rule_hook.docker_command import docker_arguments, docker_subcommand, LAUNCHERS, tool_name +from docker_command import docker_subcommand +from shell_command import launched, tool_name # 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"}) +BUILDS = (["build"], ["buildx", "build"], ["compose", "build"]) def heavy(words: list[str]) -> bool: """Whether the simple command, run directly or through a launcher, is a docker build or a mutation run, or runs one in a container, and is not under run-heavy.""" - names = [tool_name(word) for word in words] - if not names or "run-heavy" in names or LIGHT_FLAGS & set(words): + launch = launched(words, {"docker", *MUTATORS}) + if launch is None or "run-heavy" in launch.launchers or LIGHT_FLAGS & set(words): return False - 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) + if launch.tool == "docker": + subcommand = docker_subcommand(launch.arguments) + return subcommand in BUILDS or (subcommand[-1:] in (["run"], ["exec"]) and mutation_run([tool_name(word) for word in launch.arguments])) + return mutation_run([launch.tool, *(tool_name(word) for word in launch.arguments)]) def mutation_run(names: list[str]) -> bool: diff --git a/bin/rule_hook/rules.py b/bin/rule_hook/rules.py index 7ecfc6ce..864b6e04 100644 --- a/bin/rule_hook/rules.py +++ b/bin/rule_hook/rules.py @@ -8,7 +8,7 @@ from git_command import commits from rule_hook.heavy_command import heavy from review_folder import REPORTS from shell_command import Simple -from rule_hook.docker_command import unlimited_container +from docker_command import unlimited_container 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"] @@ -31,7 +31,7 @@ RULES: dict[RuleName, Rule] = { "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", + "a container started with docker run or docker create has a memory limit, as large as its work needs, 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( @@ -138,7 +138,7 @@ def command_breaches(command: str, simples: list[Simple], home: str) -> list[Bre 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)) + breaches.append(Breach("docker-run-memory", f"give `{' '.join(simple.words)[:80]}` a memory limit as large as its work needs, 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/shell_command.py b/bin/shell_command.py index 294bd554..38b2f562 100644 --- a/bin/shell_command.py +++ b/bin/shell_command.py @@ -3,7 +3,10 @@ import dataclasses import posixpath import re import shlex +import typing +# 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"}) HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE) ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=") OPERATOR = set("\n();&|<>") @@ -13,6 +16,14 @@ REDIRECT = re.compile(r"&>>?|[<>]+[&|]?") PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(? str: def resolved(base: str, path: str, home: str) -> str: return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path)) + + +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 launched(words: list[str], tools: typing.Collection[str]) -> Launch | None: + """The first of tools that the simple command runs, directly or through launchers; None where it runs none of them.""" + names = [tool_name(word) for word in words] + # Past a launcher, the tool may follow the launcher's own options and assignments, as in nice -n 19 docker build; without one, the command itself is the tool. + reachable = names if names[:1] and names[0] in LAUNCHERS else names[:1] + at = next((i for i, name in enumerate(reachable) if name in tools), None) + if at is None: + return None + return Launch(frozenset(LAUNCHERS.intersection(names[:at])), names[at], words[at + 1:]) diff --git a/docs/decisions.md b/docs/decisions.md index 848847a4..bcf2a971 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -74,7 +74,11 @@ 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. 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. +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. + +## machine load: every container a session starts with `docker run` or `docker create` sets a memory limit as large as its work needs, which rule-hook's `docker-run-memory` enforces, and no daemon-wide cap limits all containers together + +2026-10-24, lilleman. Serves goal 1.5. On 2026-10-23 ai-sandbox, with 8 CPUs and 7.6 GiB, hung until a hard reset, although its one heavy command held a slot: beside that mutation run, a reviewer's stress probes ran in `docker run` with no memory limit, each to 2 GiB. A limit makes a runaway container fail alone instead of taking the machine with it. The session sizes the limit, since lilleman wants a project to run heavier work where it needs to. rule-hook's rule reads only the commands a session types (todo item 228): a container a script or docker compose starts is out of its sight. lilleman turned down a daemon-wide cap, a dockerd `cgroup-parent` with a memory limit, which would see every container, on 2026-10-24: it is host config, and it would cap a project's heavy work too. Valid while sessions start their work in containers on a machine they share. ## 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 5e5c0927..655087f9 100644 --- a/todo.md +++ b/todo.md @@ -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. 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`. +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. It tells such a call apart with `bin/docker_command.py`'s `unlimited`, which rule-hook's `docker-run-memory` reads too. A container that sets its own `--memory` keeps it, so a project runs heavier work where it needs to (lilleman, 2026-10-24). 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, which `shell_command.launched` reports among a call's launchers. 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.