diff --git a/.gitignore b/.gitignore index e44d9417..d6945d7b 100644 --- a/.gitignore +++ b/.gitignore @@ -65,6 +65,9 @@ !bin/rule_hook/*.py !bin/rung_replay/ !bin/rung_replay/*.py +!bin/run-heavy +!bin/run_heavy/ +!bin/run_heavy/*.py !bin/score-outcomes !bin/score_outcomes/ !bin/score_outcomes/*.py diff --git a/AGENTS.md b/AGENTS.md index 28ab0c76..31be7dec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,7 @@ Decisions live in `docs/decisions.md`: - loop-claude: every claude it starts bypasses permissions inside its sandbox - 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 a slot per 4 CPUs that every session on the machine shares, and loop-claude starts a worker only while a quarter of the machine's memory is available - 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/CHANGELOG.md b/CHANGELOG.md index 3f5eeb1f..55a1380d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- Sessions running at once no longer starve the machine. A new tool, `run-heavy `, runs a heavy command, such as a full gate, mutation tests, an e2e run or a `docker build`, once it holds one of the machine's heavy slots: one per 4 CPUs, shared by every session. `CLAUDE.md` has every session run its heavy commands under it, and the stability reviewer its mutation tests. loop-claude now waits to start a worker while less than a quarter of the machine's memory is available. - larv-review's skill now says a commit answering the external auto-reviewer takes no `Answer round` title, and that `larv-review round-count` doesn't list the auto-reviewer. A worker who followed the skill used to get a "not a pass" warning. - rule-hook now blocks a larv-review round commit titled past round 3, such as `Answer stability round 4: …`, unless a `round-cap` override quotes the human's yes. - loop-claude's first prompt for a chunk that no plan item routed now also names the rung on which the worker launches its reviews for an item it takes in, as the prompt after a step-up or an unfinished verdict already did. diff --git a/CLAUDE.md b/CLAUDE.md index 41b1b081..1322284a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -65,6 +65,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i - Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along. - Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app …`. - Tear down test containers after a run. +- Run each heavy command under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. run-heavy waits for one of the heavy slots that every session on the machine shares. Run it in the background, since the wait can outlast the Bash tool's timeout. - Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a `todo.md` item; a task that changes no file, such as a search, is L 1. `` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits: 1. A reviewer, a comprehension seat or the security pass: those loop-claude's prompt gives it. Given none, pass no model or effort, so it runs on your model. 2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores `todo.md` items and that rung is higher. diff --git a/README.md b/README.md index 7ee48994..4fefe9fa 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure. - `review-replay ` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host. - `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Bash, Edit, MultiEdit, Write and Agent call, and `rule-hook --help` states the rules and the override. +- `run-heavy ` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots. - `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; `score-outcomes --help` states the measures. - `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter. - `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it. diff --git a/agents/stability-reviewer.md b/agents/stability-reviewer.md index 4e5a8f0d..7bbcfb6a 100644 --- a/agents/stability-reviewer.md +++ b/agents/stability-reviewer.md @@ -13,7 +13,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv 2. **Read every file under `~/.claude/principles/`**, the shared principles, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently. 3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them. 4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; delete nothing else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped. -5. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff `, Infection `--git-diff-lines`, Stryker `--mutate :`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling, as in step 4, on a scratch copy: the tools write files. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. +5. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff `, Infection `--git-diff-lines`, Stryker `--mutate :`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling, as in step 4, under `~/.claude/bin/run-heavy`, on a scratch copy: the tools write files. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. 6. **Two passes minimum, then hunt absences.** - *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review. - *Depth:* trace the riskiest data paths end-to-end (input → logic → persistence/response), the interactions between changed pieces, and between the change and config (timeout hierarchies, retries × idempotency, queue worker counts, env parity). diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index 8360f61d..8adf5d0c 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -114,7 +114,7 @@ class Main(unittest.TestCase): result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/loop_claude/cycle/worker.py b/bin/loop_claude/cycle/worker.py index f9190b63..1747cc3e 100644 --- a/bin/loop_claude/cycle/worker.py +++ b/bin/loop_claude/cycle/worker.py @@ -1,3 +1,5 @@ +import sys + from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until from loop_claude.effects import Effects from failure import Failure @@ -7,9 +9,12 @@ from model_routing.ladder import Rung from claude_code.session import Session PRINTED_TOOL_INPUT = 160 +# Seconds between reads of the machine's memory while too little of it is available to start a worker. +MEMORY_POLL = 60 def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None: + wait_for_memory(effects) try: proc = effects.stream_claude(args, root, env) except OSError as failure: @@ -28,6 +33,16 @@ def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects return worker_outcome(proc.wait(), result, resets) +def wait_for_memory(effects: Effects) -> None: + """Returns once the machine has room for a worker, or its memory cannot be read, so loops running at once do not push it into swap.""" + said = False + while (memory := effects.memory()) is not None and not memory.has_room(): + if not said: + print(f"waiting to start the worker until a quarter of the machine's memory is available; {memory.available // 1024} MiB of {memory.total // 1024} MiB is", file=sys.stderr, flush=True) + said = True + effects.sleep(MEMORY_POLL) + + def worker_outcome(code: int, result: dict | None, resets: list[int]) -> Failure | Limited | None: if result is not None and hit_limit(result): return Limited(max(resets, default=None), limit_said(result)) diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index ab6cfad3..b5700f2e 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -8,6 +8,7 @@ import typing from failure import Failure import git_repo +from loop_claude.memory import Memory, read_memory # Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop. PYTHON_TIMEOUT = 600 @@ -37,6 +38,8 @@ class Effects: git: Git input: typing.Callable[[str], str] local_time: typing.Callable[[float], str] + # The machine's memory; None where it cannot be read. + memory: typing.Callable[[], Memory | None] now: typing.Callable[[], float] on_terminal: typing.Callable[[], bool] # Runs a Python script in a directory, as run_python does. @@ -66,6 +69,7 @@ def system_effects() -> Effects: git=git_repo.git, input=input, local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)), + memory=read_memory, now=time.time, on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT), diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 154b39be..ae88dcfd 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -44,6 +44,11 @@ copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/ (default roo then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py. +Before each worker starts, loop-claude waits while less than a quarter of the machine's memory is +available, as /proc/meminfo's MemAvailable and MemTotal state, saying so once on stderr and reading +again each minute, so loops running at once do not push the machine into swap. Where the file cannot +be read, as off Linux, the worker starts at once. + Every claude loop-claude starts runs the project's model, saved per in ~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker, the session /talk opens and the judge on another rung, a model at an effort. A project without an diff --git a/bin/loop_claude/memory.py b/bin/loop_claude/memory.py new file mode 100644 index 00000000..a7caa670 --- /dev/null +++ b/bin/loop_claude/memory.py @@ -0,0 +1,33 @@ +import dataclasses +import pathlib +import re + +MEMINFO = pathlib.Path("/proc/meminfo") +# A worker starts only while this share of the machine's memory is available; the human chose it, as no standard sets one. +ROOM_SHARE = 0.25 + + +@dataclasses.dataclass(frozen=True) +class Memory: + """The machine's memory, in kB as /proc/meminfo counts it: what a new process can have without swapping, and all of it.""" + available: int + total: int + + def has_room(self) -> bool: + return self.available >= ROOM_SHARE * self.total + + +def parsed(meminfo: str) -> Memory | None: + """The memory a /proc/meminfo text states; None where it lacks MemAvailable or MemTotal.""" + fields = dict(re.findall(r"^(MemAvailable|MemTotal):\s+(\d+) kB$", meminfo, re.MULTILINE)) + if len(fields) != 2: + return None + return Memory(available=int(fields["MemAvailable"]), total=int(fields["MemTotal"])) + + +def read_memory(meminfo: pathlib.Path = MEMINFO) -> Memory | None: + """The machine's memory; None where meminfo cannot be read, as off Linux.""" + try: + return parsed(meminfo.read_text()) + except OSError: + return None diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 89fc845e..be1bef4b 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -22,7 +22,7 @@ from loop_claude.project import checkout, model_choice, records from chunk_pick import DefaultPlan, LastCut from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python from claude_code import entries, reply, session -from loop_claude import escalation_mark, paths, routing +from loop_claude import escalation_mark, memory, paths, routing from failure import Failure from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker @@ -59,9 +59,11 @@ def human(content): class FakeEffects: """Effects that record each call and answer from a script, one answer per call.""" - def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True): + def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()): self.calls = [] self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} + # Without a script, every read finds all memory available. + self.free_memory = list(free_memory) self.terminal = on_terminal self.worker_environments = [] self.terminal_environments = [] @@ -75,6 +77,7 @@ class FakeEffects: git=lambda *args, cwd: self.answer("git", list(args)), input=lambda prompt: self.answer("input", prompt), local_time=lambda seconds: f"<{seconds}>", + memory=self.memory, now=lambda: NOW, on_terminal=lambda: self.terminal, python=lambda args, cwd: self.answer("python", (args, cwd)), @@ -82,6 +85,10 @@ class FakeEffects: stream_claude=self.stream, ) + def memory(self): + self.calls.append(("memory", None)) + return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16) + def on_terminal_claude(self, args, cwd, env): self.terminal_environments.append(env) return self.answer("claude_on_terminal", args) @@ -583,6 +590,34 @@ class Limits(unittest.TestCase): self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want, info) +class MemoryWait(unittest.TestCase): + def test_reads_available_and_total_memory_from_meminfo(self): + meminfo = "MemTotal: 16387072 kB\nMemFree: 981236 kB\nMemAvailable: 4096000 kB\n" + self.assertEqual(memory.parsed(meminfo), memory.Memory(available=4096000, total=16387072)) + for unread in ("MemTotal: 16 kB\n", "MemTotal: x kB\nMemAvailable: 1 kB\n", ""): + self.assertIsNone(memory.parsed(unread), unread) + + def test_reads_a_meminfo_file_and_none_where_it_cannot(self): + with tempfile.TemporaryDirectory() as temp: + meminfo = pathlib.Path(temp, "meminfo") + meminfo.write_text("MemTotal: 8 kB\nMemAvailable: 2 kB\n") + self.assertEqual(memory.read_memory(meminfo), memory.Memory(available=2, total=8)) + self.assertIsNone(memory.read_memory(pathlib.Path(temp, "gone"))) + + def test_a_worker_starts_only_once_a_quarter_of_memory_is_available(self): + fake = FakeEffects(free_memory=[memory.Memory(available=3, total=16), memory.Memory(available=3, total=16), memory.Memory(available=4, total=16)], streams=[Streamed(0)]) + with contextlib.redirect_stderr(io.StringIO()) as said: + self.assertIsNone(worker.run_worker("/r", [], {}, fake.effects())) + self.assertEqual([seam for seam, _ in fake.calls], ["memory", "sleep", "memory", "sleep", "memory", "stream_claude"]) + self.assertEqual(fake.made("sleep"), [worker.MEMORY_POLL] * 2) + self.assertEqual(said.getvalue().count("waiting"), 1, said.getvalue()) + + def test_a_worker_starts_at_once_where_memory_cannot_be_read(self): + fake = FakeEffects(free_memory=[None], streams=[Streamed(0)]) + self.assertIsNone(worker.run_worker("/r", [], {}, fake.effects())) + self.assertEqual([seam for seam, _ in fake.calls], ["memory", "stream_claude"]) + + class Interrupts(unittest.TestCase): def put(self, fake, answer_here=True): with contextlib.redirect_stderr(io.StringIO()) as said: diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index d73b85b8..0711dad5 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -215,7 +215,7 @@ class Main(unittest.TestCase): result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/run-heavy b/bin/run-heavy new file mode 100755 index 00000000..2c79396b --- /dev/null +++ b/bin/run-heavy @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 +import os +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from run_heavy import main + +sys.exit(main.main(sys.argv[1:], os.environ)) diff --git a/bin/run_heavy/__init__.py b/bin/run_heavy/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/run_heavy/main.py b/bin/run_heavy/main.py new file mode 100644 index 00000000..166fc0c8 --- /dev/null +++ b/bin/run_heavy/main.py @@ -0,0 +1,84 @@ +"""Run a heavy command once it holds one of the machine's heavy slots, so sessions running at once cannot starve the machine. + +usage: run-heavy [...] + +A heavy command is one that loads the machine for minutes: a full gate, mutation tests, an e2e run, +a docker build. The machine has one heavy slot per 4 CPUs, and at least one, shared by every +session that runs run-heavy. Each slot is a file locked with flock, under +$XDG_STATE_HOME/run-heavy (default ~/.local/state/run-heavy). While every slot is held, run-heavy +says so once on stderr and waits. It then runs the command in its place, which holds the slot until +it and every process that inherited the lock exit. Its exit code is the command's. + +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. + +Exit 1, saying why, when no command is given or the slot folder cannot be made; exit 127 when the +command cannot start. +""" +import fcntl +import os +import pathlib +import sys +import time +import typing + +CPUS_PER_SLOT = 4 +# Names the slot a command runs in, so a heavy command it runs does not wait for a second slot. +HELD = "RUN_HEAVY_SLOT" +# Seconds between tries while every slot is held; a slot frees as its command exits. +POLL_SECONDS = 1 +USAGE = "usage: run-heavy [...]" + + +def slot_count(cpus: int | None) -> int: + return max(1, (cpus or 0) // CPUS_PER_SLOT) + + +def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path: + state = env.get("XDG_STATE_HOME") or str(pathlib.Path.home() / ".local" / "state") + return pathlib.Path(state) / "run-heavy" + + +def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None: + """The number and open file of a slot this call locked; None while every slot is held.""" + for slot in range(slots): + fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644) + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + os.close(fd) + continue + return slot, fd + return None + + +def main(argv: list[str], env: typing.Mapping[str, str]) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + if not argv: + print(f"run-heavy: no command given; {USAGE}", file=sys.stderr) + return 1 + if HELD not in env: + folder = slot_folder(env) + try: + folder.mkdir(parents=True, exist_ok=True) + except OSError as failure: + print(f"run-heavy: cannot make the slot folder {folder}: {failure.strerror}", file=sys.stderr) + return 1 + slots = slot_count(os.cpu_count()) + said = False + while (taken := taken_slot(folder, slots)) is None: + if not said: + print(f"run-heavy: waiting for one of the machine's {slots} heavy slots", file=sys.stderr, flush=True) + said = True + time.sleep(POLL_SECONDS) + slot, fd = taken + # The command inherits the locked file, so the slot stays held until it exits. + os.set_inheritable(fd, True) + env = {**env, HELD: str(slot)} + try: + os.execvpe(argv[0], argv, env) + except OSError as failure: + print(f"run-heavy: cannot run {argv[0]}: {failure.strerror}", file=sys.stderr) + return 127 diff --git a/bin/run_heavy/test_run_heavy.py b/bin/run_heavy/test_run_heavy.py new file mode 100644 index 00000000..592dcad0 --- /dev/null +++ b/bin/run_heavy/test_run_heavy.py @@ -0,0 +1,100 @@ +import contextlib +import fcntl +import os +import pathlib +import subprocess +import sys +import tempfile +import time +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from run_heavy import main + +TOOL = pathlib.Path(__file__).resolve().parents[1] / "run-heavy" + + +class SlotCount(unittest.TestCase): + def test_one_slot_per_four_cpus_and_never_none(self): + for cpus, slots in ((16, 4), (8, 2), (7, 1), (4, 1), (1, 1), (None, 1)): + self.assertEqual(main.slot_count(cpus), slots, cpus) + + +class RunHeavy(unittest.TestCase): + def setUp(self): + state = tempfile.TemporaryDirectory() + self.addCleanup(state.cleanup) + self.env = {**os.environ, "XDG_STATE_HOME": state.name} + self.env.pop(main.HELD, None) + self.slots = pathlib.Path(state.name) / "run-heavy" + + def run_tool(self, *args: str, env=None) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True, env=env or self.env, timeout=30) + + def start_tool(self, *args: str, env=None) -> subprocess.Popen[str]: + tool = subprocess.Popen([sys.executable, str(TOOL), *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env or self.env) + self.addCleanup(tool.kill) + return tool + + @contextlib.contextmanager + def every_slot_held(self): + self.slots.mkdir(parents=True, exist_ok=True) + with contextlib.ExitStack() as held: + for slot in range(main.slot_count(os.cpu_count())): + file = held.enter_context(open(self.slots / f"slot-{slot}", "a")) + fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB) + yield + + def free_slots(self) -> int: + free = 0 + for slot in range(main.slot_count(os.cpu_count())): + with open(self.slots / f"slot-{slot}", "a") as file: + try: + fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB) + free += 1 + except BlockingIOError: + pass + return free + + def test_runs_the_command_and_exits_with_its_code(self): + result = self.run_tool("sh", "-c", "echo out; echo err >&2; exit 3") + self.assertEqual((result.returncode, result.stdout, result.stderr), (3, "out\n", "err\n")) + + def test_holds_a_slot_while_the_command_runs_and_frees_it_after(self): + tool = self.start_tool("sh", "-c", "echo started; read line") + self.assertEqual(tool.stdout.readline(), "started\n") + self.assertEqual(self.free_slots(), main.slot_count(os.cpu_count()) - 1) + tool.communicate("\n", timeout=30) + self.assertEqual(self.free_slots(), main.slot_count(os.cpu_count())) + + def test_waits_while_every_slot_is_held_and_says_so_once(self): + with self.every_slot_held(): + tool = self.start_tool("echo", "ran") + time.sleep(3 * main.POLL_SECONDS) + self.assertIsNone(tool.poll()) + out, err = tool.communicate(timeout=30) + self.assertEqual((tool.returncode, out), (0, "ran\n")) + self.assertEqual(err.count("waiting"), 1, err) + + def test_a_command_inside_a_held_slot_runs_at_once(self): + with self.every_slot_held(): + result = self.run_tool("echo", "nested", env={**self.env, main.HELD: "0"}) + self.assertEqual((result.returncode, result.stdout), (0, "nested\n")) + + def test_a_command_that_cannot_start_exits_127_saying_why(self): + result = self.run_tool("no-such-command-anywhere") + self.assertEqual((result.returncode, result.stdout), (127, "")) + self.assertIn("no-such-command-anywhere", result.stderr) + + def test_no_command_exits_1_with_the_usage_and_help_exits_0(self): + bare = self.run_tool() + self.assertEqual((bare.returncode, bare.stdout), (1, "")) + self.assertIn("usage: run-heavy ", bare.stderr) + helped = self.run_tool("--help") + self.assertEqual(helped.returncode, 0) + self.assertIn("usage: run-heavy ", helped.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/decisions.md b/docs/decisions.md index 355c4c05..a775dd0c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -62,6 +62,10 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the 2026-09-28, lilleman. Serves goals 1 and 3: saving each transcript locally is the first step of backing it up, and it shows afterwards what an unattended run did. A copy of the `.jsonl`, deduplicated by content hash, with its outcomes beside it; a rendering drops tool results, and a second-resolution stamp names two states within one second as one file. A failed archive exits 1, since a loop that loses its record silently fails the backup goal. Valid while transcripts stay small enough to copy whole. +## machine load: a heavy command waits for one of a slot per 4 CPUs that every session on the machine shares, and loop-claude starts a worker only while 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. The human 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. A heavy command run inside a slot already held runs at once, so a gate that wraps its own steps cannot wait on itself. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/run_heavy/main.py` holds the slots, `CLAUDE.md` → "Working with the codebase" has every session use them, and `bin/loop_claude/memory.py` holds the memory share. 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 2026-10-22, lilleman asked for a rule of seven that holds at every level and is never a hard rule. Serves code health: a reader new to the project should take in each level at once. The numbers follow the sources below, since no single study sets them. diff --git a/todo.md b/todo.md index ba584b58..6f4d1aec 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 222` +`Next ID = 223` ## Items