From cd9ab4e4ba3f0bea6f739858f055fb2ce2c7d49d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:36:19 +0100 Subject: [PATCH 01/65] docs: allow skills to ship Python scripts with tests (#45) Co-Authored-By: Claude Fable 5.1 --- CLAUDE.md | 5 ++++- README.md | 2 ++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index ee74ccf..716151e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -18,7 +18,7 @@ Before you open a PR: A single Claude Code plugin, packaged as its own single-plugin marketplace. - `.claude-plugin/plugin.json` is the plugin manifest; `.claude-plugin/marketplace.json` makes the repo installable as a marketplace. Skills are auto-discovered from `skills/`. -- The only runtime dependencies are the [superpowers](https://github.com/obra/superpowers) plugin, the `gh` CLI, and the official [`gh stack`](https://github.com/github/gh-stack) extension for `gh`, which the skills require only for stacked PRs. Keep it that way. Do not add a third-party dependency to make a skill work. +- The only runtime dependencies are the [superpowers](https://github.com/obra/superpowers) plugin, the `gh` CLI, the official [`gh stack`](https://github.com/github/gh-stack) extension for `gh`, which the skills require only for stacked PRs, and Python 3.9 or later, which the skills require only for the scripts they ship. Keep it that way. Do not add a third-party dependency to make a skill work. ## Editing skills @@ -26,6 +26,7 @@ A single Claude Code plugin, packaged as its own single-plugin marketplace. - **A skill `description:` is "Use when..." trigger text only, never a workflow summary.** A summary becomes a shortcut the agent takes instead of reading the body. - **Keep skills project-agnostic.** No hardcoded repo slug, no project-specific build commands, no domain examples. No language, framework, or product names in illustrations. A skill must read the same in a Go repo, a Next.js app, or a Python service. The honest test: would this still be correct in a project built on a completely different stack? - **Reference templates with `${CLAUDE_PLUGIN_ROOT}/skills//templates/`.** Relative paths break once the plugin is copied into the install cache. +- **Scripts live in `skills//scripts/`, use the Python standard library only, and carry tests in `skills//scripts/tests/`.** Reference them with `${CLAUDE_PLUGIN_ROOT}/skills//scripts/`. - **Intra-plugin skill invocations are namespaced `feature-dev-workflow:`.** Leave `superpowers:*` references and the external `review` skill alone. - **The `**REQUIRED SUB-SKILL:**` markers are the control flow.** If you add, rename, or remove a skill, fix every marker that points at it, in every skill, and update the diagram in `templates/project-CLAUDE.md` and the table in `README.md`. - **`simple-english:simple-english` is an optional style skill, not a dependency.** Skills that draft prose people read (PR and issue bodies and comments, review replies, docs, release notes, specs, ADRs, commit bodies, code and doc comments) reference it with an `**OPTIONAL SUB-SKILL:**` marker: load it when it is available, suggest the install to the user once per session when it is not, and continue either way. Every skill must work without it. It sets sentence style only: a template's sections, a skill's length rules, a commit subject's convention, and a project's comment rules still apply. Its own formatting rules (headings, bold, lists, and its register for chat replies) give way to the host skill and its template, and every marker says so. It does not cover PR and issue titles, commit subjects, code itself (identifiers, strings, log messages), plans and state files, or the skill files themselves. @@ -43,5 +44,7 @@ A single Claude Code plugin, packaged as its own single-plugin marketplace. ## Verify before done - The JSON in `.claude-plugin/` must parse. +- Every script's tests must pass: `python3 -m unittest discover -s skills//scripts/tests`. +- CI runs the same tests on Linux and macOS, on Python 3.9 and on the current release, from `.github/workflows/script-tests.yml`. A new script needs no change there: the workflow finds every `skills//scripts/tests/` directory. - Before committing any genericization, grep the skills for leakage: no repo slug, no project-specific build commands, no product or domain identifiers. - Read the diff cold. If a sentence only makes sense knowing what just changed, it belongs in the commit message, not the file. diff --git a/README.md b/README.md index bde49ad..9c0999e 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,8 @@ Optionally, install the [simple-english](https://github.com/AminBlg/SimpleEnglis The skills also assume the [`gh`](https://cli.github.com/) CLI is installed and authenticated. +The skills that ship a script need Python 3.9 or later as `python3`, with no extra packages. macOS provides it with the Xcode Command Line Tools. A skill whose script cannot run says so once per session and continues with a weaker fallback. + Stacked PRs (a linear chain where each PR builds on the one before it) also need GitHub's official [`gh stack`](https://github.com/github/gh-stack) extension. The skills check for it before any stacked work and ask you to install it if it is missing: ``` From 14225a04644d8691e86eae4367ea39a3f4c24d4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:40:29 +0100 Subject: [PATCH 02/65] feat(skills/bounding-heavy-commands): read memory sizes for the wrapper (#45) Co-Authored-By: Claude Haiku 4.5 --- .../scripts/bounded_run.py | 70 +++++++++++++++++++ .../scripts/tests/test_bounded_run.py | 58 +++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 skills/bounding-heavy-commands/scripts/bounded_run.py create mode 100644 skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py new file mode 100644 index 0000000..9b5f21c --- /dev/null +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Runs a command under a memory reservation that every project of the user shares. + +Usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] -- COMMAND... + +The exit code is the exit code of the command. Exit code 125 means that this +script failed before the command gave a result. + +These environment variables are settings for the machine, not for one call. +Two sessions with different values do not count the same slots. + + BOUNDED_RUN_SLOT_MIB size of one memory slot (default 2048) + BOUNDED_RUN_RESERVE_MIB memory that the queue never gives out + BOUNDED_RUN_TOTAL_MIB memory of the machine, in place of the measured value + BOUNDED_RUN_POLL_SECONDS time between two tries for the slots (default 2) + BOUNDED_RUN_MEMORY_WAIT_SECONDS time limit of the wait for free memory (default 300) + BOUNDED_RUN_SAMPLE_SECONDS time between two memory samples (default 1) + BOUNDED_RUN_LOCK_DIR directory of the lock files + BOUNDED_RUN_NO_CAP when set, do not apply the hard cap +""" +from __future__ import annotations + +import fcntl +import hashlib +import math +import os +import random +import re +import shutil +import signal +import stat +import subprocess +import sys +import threading +import time +from typing import Callable, Dict, List, Mapping, Optional, Sequence, Tuple + +PREFIX = "bounded-run" +EXIT_WRAPPER = 125 +ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE" +SLOT_MIB = 2048 +MINIMUM_RESERVE_MIB = 2048 +POLL_SECONDS = 2.0 +MEMORY_WAIT_SECONDS = 300.0 +SAMPLE_SECONDS = 1.0 +MARGIN_EXACT = 0.25 +MARGIN_APPROXIMATE = 0.5 +BUDGET_STEP_MIB = 256 +USAGE = "usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] -- COMMAND..." + + +class WrapperError(Exception): + """A failure of the wrapper, not of the command.""" + + +def log(message: str) -> None: + sys.stderr.write("%s: %s\n" % (PREFIX, message)) + sys.stderr.flush() + + +def parse_size_mib(text: str) -> int: + parts = re.match(r"^(\d+)([GgMm]?)$", text.strip()) + if parts is None: + raise WrapperError("cannot read the size '%s'; use a form such as 6G or 4096M" % text) + value = int(parts.group(1)) + if parts.group(2) in ("G", "g"): + value *= 1024 + if value <= 0: + raise WrapperError("the size '%s' must be more than zero" % text) + return value diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py new file mode 100644 index 0000000..412cb0b --- /dev/null +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +import os +import signal +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +SCRIPTS = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(SCRIPTS)) + +import bounded_run # noqa: E402 + +WRAPPER = str(SCRIPTS / "bounded_run.py") + +# Appends one event line to the file in EVENTS, holds, then appends the end event. +# The hold stops after HOLD seconds, or when the file in RELEASE exists. +WORKER = ( + "import os, sys, time\n" + "def event(kind):\n" + " descriptor = os.open(os.environ['EVENTS'], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)\n" + " os.write(descriptor, ('%s %s %d\\n' % (kind, sys.argv[1], os.getpid())).encode())\n" + " os.close(descriptor)\n" + "event('start')\n" + "release = os.environ.get('RELEASE')\n" + "deadline = time.time() + float(os.environ.get('HOLD', '0.3'))\n" + "while time.time() < deadline and not (release and os.path.exists(release)):\n" + " time.sleep(0.02)\n" + "event('end')\n" +) + + +class SizeTest(unittest.TestCase): + def test_reads_gibibytes(self): + self.assertEqual(bounded_run.parse_size_mib("6G"), 6144) + + def test_reads_mebibytes(self): + self.assertEqual(bounded_run.parse_size_mib("4096M"), 4096) + + def test_reads_a_number_without_a_unit_as_mebibytes(self): + self.assertEqual(bounded_run.parse_size_mib("512"), 512) + + def test_reads_a_lower_case_unit(self): + self.assertEqual(bounded_run.parse_size_mib("2g"), 2048) + + def test_rejects_text_that_is_not_a_size(self): + for text in ("", "six", "6GB", "-1G", "1.5G", "0"): + with self.subTest(text=text): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.parse_size_mib(text) + + +if __name__ == "__main__": + unittest.main() From 87ed00ba92b472ee41912e654c0398641447bbe9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:44:18 +0100 Subject: [PATCH 03/65] feat(skills/bounding-heavy-commands): count memory slots from the machine (#45) Co-Authored-By: Claude Haiku 4.5 --- .../scripts/bounded_run.py | 51 ++++++++++++++++++ .../scripts/tests/test_bounded_run.py | 52 +++++++++++++++++++ 2 files changed, 103 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 9b5f21c..eefbd2d 100644 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -68,3 +68,54 @@ def parse_size_mib(text: str) -> int: if value <= 0: raise WrapperError("the size '%s' must be more than zero" % text) return value + + +def total_memory_mib() -> int: + try: + return os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") // (1024 * 1024) + except (ValueError, OSError): + done = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=10) + return int(done.stdout.strip()) // (1024 * 1024) + + +def default_reserve_mib(total_mib: int) -> int: + return max(MINIMUM_RESERVE_MIB, total_mib // 4) + + +def slot_count(total_mib: int, slot_mib: int, reserve_mib: int) -> int: + return max(1, (total_mib - reserve_mib) // slot_mib) + + +def slots_needed(budget_mib: int, slot_mib: int, count: int) -> int: + return min(count, max(1, math.ceil(budget_mib / slot_mib))) + + +def default_budget_mib(total_mib: int, slot_mib: int) -> int: + return max(1, math.ceil(total_mib / 4 / slot_mib)) * slot_mib + + +class Settings: + def __init__(self, environ: Mapping[str, str], read_total: Callable[[], int] = total_memory_mib) -> None: + self.slot_mib = int(_number(environ, "BOUNDED_RUN_SLOT_MIB", SLOT_MIB)) + total = environ.get("BOUNDED_RUN_TOTAL_MIB") + self.total_mib = int(_number(environ, "BOUNDED_RUN_TOTAL_MIB", 0)) if total else read_total() + self.reserve_mib = int(_number(environ, "BOUNDED_RUN_RESERVE_MIB", default_reserve_mib(self.total_mib))) + self.poll_seconds = _number(environ, "BOUNDED_RUN_POLL_SECONDS", POLL_SECONDS) + self.memory_wait_seconds = _number(environ, "BOUNDED_RUN_MEMORY_WAIT_SECONDS", MEMORY_WAIT_SECONDS) + self.sample_seconds = _number(environ, "BOUNDED_RUN_SAMPLE_SECONDS", SAMPLE_SECONDS) + self.no_cap = bool(environ.get("BOUNDED_RUN_NO_CAP")) + if self.slot_mib <= 0: + raise WrapperError("BOUNDED_RUN_SLOT_MIB must be more than zero") + + +def _number(environ: Mapping[str, str], name: str, fallback: float) -> float: + text = environ.get(name) + if text is None or text == "": + return fallback + try: + value = float(text) + except ValueError: + raise WrapperError("cannot read %s='%s'; use a number" % (name, text)) + if value < 0: + raise WrapperError("%s must not be less than zero" % name) + return value diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 412cb0b..4d5fe2c 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -54,5 +54,57 @@ def test_rejects_text_that_is_not_a_size(self): bounded_run.parse_size_mib(text) +class SlotCountTest(unittest.TestCase): + def test_divides_the_memory_after_the_reserve(self): + self.assertEqual(bounded_run.slot_count(32768, 2048, 8192), 12) + + def test_gives_one_slot_on_a_small_machine(self): + self.assertEqual(bounded_run.slot_count(2048, 2048, 2048), 1) + + def test_default_reserve_is_a_quarter_with_a_minimum(self): + self.assertEqual(bounded_run.default_reserve_mib(32768), 8192) + self.assertEqual(bounded_run.default_reserve_mib(4096), 2048) + + def test_a_budget_takes_the_slots_that_cover_it(self): + self.assertEqual(bounded_run.slots_needed(6144, 2048, 12), 3) + self.assertEqual(bounded_run.slots_needed(6145, 2048, 12), 4) + self.assertEqual(bounded_run.slots_needed(100, 2048, 12), 1) + + def test_a_budget_larger_than_the_queue_takes_all_slots(self): + self.assertEqual(bounded_run.slots_needed(99999, 2048, 3), 3) + + def test_default_budget_is_a_quarter_in_full_slots(self): + self.assertEqual(bounded_run.default_budget_mib(32768, 2048), 8192) + self.assertEqual(bounded_run.default_budget_mib(6000, 2048), 2048) + + def test_total_memory_of_this_machine_is_positive(self): + self.assertGreater(bounded_run.total_memory_mib(), 0) + + +class SettingsTest(unittest.TestCase): + def test_defaults(self): + settings = bounded_run.Settings({}, read_total=lambda: 16384) + self.assertEqual(settings.slot_mib, 2048) + self.assertEqual(settings.total_mib, 16384) + self.assertEqual(settings.reserve_mib, 4096) + self.assertEqual(settings.poll_seconds, 2.0) + self.assertEqual(settings.memory_wait_seconds, 300.0) + self.assertFalse(settings.no_cap) + + def test_overrides(self): + settings = bounded_run.Settings({ + "BOUNDED_RUN_SLOT_MIB": "1024", "BOUNDED_RUN_TOTAL_MIB": "4096", + "BOUNDED_RUN_RESERVE_MIB": "1024", "BOUNDED_RUN_POLL_SECONDS": "0.05", + "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", "BOUNDED_RUN_NO_CAP": "1", + }, read_total=lambda: 1) + self.assertEqual((settings.slot_mib, settings.total_mib, settings.reserve_mib), (1024, 4096, 1024)) + self.assertEqual((settings.poll_seconds, settings.memory_wait_seconds), (0.05, 0.0)) + self.assertTrue(settings.no_cap) + + def test_rejects_a_value_that_is_not_a_number(self): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.Settings({"BOUNDED_RUN_POLL_SECONDS": "fast"}, read_total=lambda: 1) + + if __name__ == "__main__": unittest.main() From 07afb33e0235bcc2f2b739504670e01feeaf6afd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:48:47 +0100 Subject: [PATCH 04/65] feat(skills/bounding-heavy-commands): keep the lock files in a directory of the user (#45) Co-Authored-By: Claude Haiku 4.5 --- .../scripts/bounded_run.py | 30 ++++++++++++++ .../scripts/tests/test_bounded_run.py | 40 +++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index eefbd2d..e46f5c5 100644 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -119,3 +119,33 @@ def _number(environ: Mapping[str, str], name: str, fallback: float) -> float: if value < 0: raise WrapperError("%s must not be less than zero" % name) return value + + +def lock_directory(environ: Mapping[str, str], uid: int) -> str: + override = environ.get("BOUNDED_RUN_LOCK_DIR") + if override: + return override + runtime = environ.get("XDG_RUNTIME_DIR") + if runtime: + return os.path.join(runtime, PREFIX) + login_directory = "/run/user/%d" % uid + try: + if os.stat(login_directory).st_uid == uid: + return os.path.join(login_directory, PREFIX) + except OSError: + pass + return "/tmp/%s-%d" % (PREFIX, uid) + + +def ensure_lock_directory(path: str, uid: int) -> None: + try: + os.makedirs(path, mode=0o700, exist_ok=True) + info = os.lstat(path) + except OSError as error: + raise WrapperError("cannot use the lock directory %s: %s" % (path, error)) + if not stat.S_ISDIR(info.st_mode): + raise WrapperError("the lock directory %s is not a directory" % path) + if info.st_uid != uid: + raise WrapperError("the lock directory %s belongs to a different user" % path) + if stat.S_IMODE(info.st_mode) & 0o077: + os.chmod(path, 0o700) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 4d5fe2c..bfc90bc 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -106,5 +106,45 @@ def test_rejects_a_value_that_is_not_a_number(self): bounded_run.Settings({"BOUNDED_RUN_POLL_SECONDS": "fast"}, read_total=lambda: 1) +class LockDirectoryTest(unittest.TestCase): + def test_override_wins(self): + environ = {"BOUNDED_RUN_LOCK_DIR": "/x/locks", "XDG_RUNTIME_DIR": "/run/user/7"} + self.assertEqual(bounded_run.lock_directory(environ, 7), "/x/locks") + + def test_uses_the_runtime_directory(self): + self.assertEqual(bounded_run.lock_directory({"XDG_RUNTIME_DIR": "/run/user/7"}, 7), "/run/user/7/bounded-run") + + def test_falls_back_to_a_directory_for_the_user(self): + self.assertEqual(bounded_run.lock_directory({}, 999999999), "/tmp/bounded-run-999999999") + + def test_does_not_depend_on_TMPDIR(self): + self.assertEqual(bounded_run.lock_directory({"TMPDIR": "/elsewhere"}, 999999999), "/tmp/bounded-run-999999999") + + def test_creates_the_directory_for_the_user_only(self): + with tempfile.TemporaryDirectory() as base: + path = os.path.join(base, "locks") + bounded_run.ensure_lock_directory(path, os.getuid()) + self.assertEqual(os.stat(path).st_mode & 0o777, 0o700) + + def test_closes_a_directory_that_other_users_can_read(self): + with tempfile.TemporaryDirectory() as base: + path = os.path.join(base, "locks") + os.mkdir(path, 0o755) + bounded_run.ensure_lock_directory(path, os.getuid()) + self.assertEqual(os.stat(path).st_mode & 0o777, 0o700) + + def test_rejects_a_directory_of_a_different_user(self): + with tempfile.TemporaryDirectory() as base: + with self.assertRaises(bounded_run.WrapperError): + bounded_run.ensure_lock_directory(base, os.getuid() + 1) + + def test_rejects_a_symbolic_link(self): + with tempfile.TemporaryDirectory() as base: + link = os.path.join(base, "link") + os.symlink(base, link) + with self.assertRaises(bounded_run.WrapperError): + bounded_run.ensure_lock_directory(link, os.getuid()) + + if __name__ == "__main__": unittest.main() From 4e370eb0acf65039a1dd4718424c15a719c51d38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:53:11 +0100 Subject: [PATCH 05/65] feat(skills/bounding-heavy-commands): reserve memory slots all or none (#45) Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 66 ++++++++++++++++ .../scripts/tests/test_bounded_run.py | 77 +++++++++++++++++++ 2 files changed, 143 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index e46f5c5..9ccc970 100644 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -149,3 +149,69 @@ def ensure_lock_directory(path: str, uid: int) -> None: raise WrapperError("the lock directory %s belongs to a different user" % path) if stat.S_IMODE(info.st_mode) & 0o077: os.chmod(path, 0o700) + + +class Reservation: + def __init__(self, descriptors: Sequence[int]) -> None: + self.descriptors = list(descriptors) + + def release(self) -> None: + for descriptor in self.descriptors: + os.close(descriptor) + self.descriptors = [] + + +def _try_lock(path: str) -> Optional[int]: + descriptor = os.open(path, os.O_RDWR | os.O_CREAT, 0o600) + try: + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + os.close(descriptor) + return None + return descriptor + + +def try_reserve(directory: str, count: int, needed: int, exclusive_files: Sequence[str]) -> Optional[Reservation]: + turn = os.open(os.path.join(directory, "reserve.lock"), os.O_RDWR | os.O_CREAT, 0o600) + held: List[int] = [] + try: + fcntl.flock(turn, fcntl.LOCK_EX) + names = list(exclusive_files) + ["slot-%03d.lock" % index for index in range(count)] + slots = 0 + for position, name in enumerate(names): + is_slot = position >= len(exclusive_files) + if is_slot and slots == needed: + break + descriptor = _try_lock(os.path.join(directory, name)) + if descriptor is None: + if is_slot: + continue + break + held.append(descriptor) + if is_slot: + slots += 1 + if slots == needed and len(held) == needed + len(exclusive_files): + reservation = Reservation(held) + held = [] + return reservation + return None + finally: + for descriptor in held: + os.close(descriptor) + os.close(turn) + + +def reserve( + directory: str, count: int, needed: int, exclusive_files: Sequence[str], poll_seconds: float, + sleep: Callable[[float], None] = time.sleep, +) -> Reservation: + announced = False + while True: + reservation = try_reserve(directory, count, needed, exclusive_files) + if reservation is not None: + log("holding %d of %d slot(s)" % (needed, count)) + return reservation + if not announced: + log("waiting for %d of %d slot(s)" % (needed, count)) + announced = True + sleep(poll_seconds * (0.5 + random.random())) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index bfc90bc..aacbec3 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -146,5 +146,82 @@ def test_rejects_a_symbolic_link(self): bounded_run.ensure_lock_directory(link, os.getuid()) +class ReserveTest(unittest.TestCase): + def setUp(self): + patcher = mock.patch.object(bounded_run, "log") + patcher.start() + self.addCleanup(patcher.stop) + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.directory = self.base.name + + def test_takes_the_slots_that_it_needs(self): + reservation = bounded_run.try_reserve(self.directory, 3, 2, []) + self.addCleanup(reservation.release) + self.assertEqual(len(reservation.descriptors), 2) + + def test_gives_nothing_when_too_few_slots_are_free(self): + first = bounded_run.try_reserve(self.directory, 3, 2, []) + self.addCleanup(first.release) + self.assertIsNone(bounded_run.try_reserve(self.directory, 3, 2, [])) + + def test_holds_no_slot_after_a_failed_try(self): + first = bounded_run.try_reserve(self.directory, 3, 2, []) + self.addCleanup(first.release) + self.assertIsNone(bounded_run.try_reserve(self.directory, 3, 2, [])) + third = bounded_run.try_reserve(self.directory, 3, 1, []) + self.assertIsNotNone(third) + third.release() + + def test_release_frees_the_slots(self): + first = bounded_run.try_reserve(self.directory, 2, 2, []) + first.release() + second = bounded_run.try_reserve(self.directory, 2, 2, []) + self.assertIsNotNone(second) + second.release() + + def test_an_exclusive_lock_blocks_the_same_name(self): + first = bounded_run.try_reserve(self.directory, 4, 1, ["exclusive-abc-port.lock"]) + self.addCleanup(first.release) + self.assertIsNone(bounded_run.try_reserve(self.directory, 4, 1, ["exclusive-abc-port.lock"])) + + def test_a_blocked_exclusive_lock_holds_no_slot(self): + first = bounded_run.try_reserve(self.directory, 2, 1, ["exclusive-abc-port.lock"]) + self.addCleanup(first.release) + self.assertIsNone(bounded_run.try_reserve(self.directory, 2, 1, ["exclusive-abc-port.lock"])) + other = bounded_run.try_reserve(self.directory, 2, 1, []) + self.assertIsNotNone(other) + other.release() + + def test_a_different_name_does_not_block(self): + first = bounded_run.try_reserve(self.directory, 4, 1, ["exclusive-abc-port.lock"]) + self.addCleanup(first.release) + second = bounded_run.try_reserve(self.directory, 4, 1, ["exclusive-abc-tool.lock"]) + self.assertIsNotNone(second) + second.release() + + def test_the_descriptors_are_not_inheritable(self): + reservation = bounded_run.try_reserve(self.directory, 2, 2, ["exclusive-abc-port.lock"]) + self.addCleanup(reservation.release) + for descriptor in reservation.descriptors: + self.assertFalse(os.get_inheritable(descriptor)) + + def test_reserve_tries_again_until_the_slots_are_free(self): + first = bounded_run.try_reserve(self.directory, 1, 1, []) + sleeps = [] + + def sleep(seconds): + sleeps.append(seconds) + if len(sleeps) == 2: + first.release() + + second = bounded_run.reserve(self.directory, 1, 1, [], 0.2, sleep=sleep) + self.addCleanup(second.release) + self.assertEqual(len(sleeps), 2) + for seconds in sleeps: + self.assertGreaterEqual(seconds, 0.1) + self.assertLess(seconds, 0.3) + + if __name__ == "__main__": unittest.main() From 7f402443c986baac279a3ff1c18175ed454f9433 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 12:56:45 +0100 Subject: [PATCH 06/65] fix(skills/bounding-heavy-commands): report a lock error that is not a busy lock (#45) Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 6 ++- .../scripts/tests/test_bounded_run.py | 50 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 9ccc970..75cbf9c 100644 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -165,9 +165,13 @@ def _try_lock(path: str) -> Optional[int]: descriptor = os.open(path, os.O_RDWR | os.O_CREAT, 0o600) try: fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) - except OSError: + except BlockingIOError: os.close(descriptor) return None + except OSError as error: + os.close(descriptor) + error_text = error.strerror if error.strerror else str(error) + raise WrapperError("cannot lock %s: %s. The lock directory must be on a filesystem that supports file locks." % (path, error_text)) return descriptor diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index aacbec3..89c6371 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1,5 +1,6 @@ from __future__ import annotations +import errno import os import signal import subprocess @@ -222,6 +223,55 @@ def sleep(seconds): self.assertGreaterEqual(seconds, 0.1) self.assertLess(seconds, 0.3) + def test_a_lock_error_that_is_not_a_busy_lock_is_reported(self): + with mock.patch.object(bounded_run.fcntl, "flock") as mock_flock: + def flock_side_effect(fd, flags): + # Call the real flock for the turn lock, raise ENOLCK for slot files + if flags & bounded_run.fcntl.LOCK_EX and not (flags & bounded_run.fcntl.LOCK_NB): + # This is the turn lock (blocking), allow it + return None + # This is a slot lock (non-blocking), fail with ENOLCK + raise OSError(errno.ENOLCK, "No locks available") + + mock_flock.side_effect = flock_side_effect + with self.assertRaises(bounded_run.WrapperError) as cm: + bounded_run.try_reserve(self.directory, 1, 1, []) + self.assertIn("cannot lock", str(cm.exception)) + self.assertIn("No locks available", str(cm.exception)) + + def test_a_lock_error_leaves_no_slot_held(self): + # After the previous test's patch is removed, all slots should be free + reservation = bounded_run.try_reserve(self.directory, 2, 2, []) + self.assertIsNotNone(reservation) + self.addCleanup(reservation.release) + self.assertEqual(len(reservation.descriptors), 2) + + def test_the_turn_lock_is_free_while_the_wrapper_waits(self): + # Hold all slots so reserve has to wait + blocker = bounded_run.try_reserve(self.directory, 1, 1, []) + self.addCleanup(blocker.release) + + turn_lock_acquired = [] + + def sleep_and_check(seconds): + # Try to acquire the turn lock while reserve is waiting + turn_path = os.path.join(self.directory, "reserve.lock") + turn_fd = os.open(turn_path, os.O_RDWR | os.O_CREAT, 0o600) + try: + import fcntl + fcntl.flock(turn_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + turn_lock_acquired.append(True) + except OSError: + turn_lock_acquired.append(False) + finally: + os.close(turn_fd) + # Release the blocker so reserve can succeed + blocker.release() + + reservation = bounded_run.reserve(self.directory, 1, 1, [], 0.2, sleep=sleep_and_check) + self.addCleanup(reservation.release) + self.assertTrue(turn_lock_acquired[0], "turn lock should be free while reserve waits") + if __name__ == "__main__": unittest.main() From 73ea21ee13001f7fca4551a4e522b8d732a52958 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:01:04 +0100 Subject: [PATCH 07/65] test(skills/bounding-heavy-commands): prove that a lock error leaves no slot held (#45) Co-Authored-By: Claude Fable 5.1 --- .../scripts/tests/test_bounded_run.py | 48 +++++++++++++++++-- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 89c6371..be15354 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -240,11 +240,49 @@ def flock_side_effect(fd, flags): self.assertIn("No locks available", str(cm.exception)) def test_a_lock_error_leaves_no_slot_held(self): - # After the previous test's patch is removed, all slots should be free - reservation = bounded_run.try_reserve(self.directory, 2, 2, []) - self.assertIsNotNone(reservation) - self.addCleanup(reservation.release) - self.assertEqual(len(reservation.descriptors), 2) + # Prove that when try_reserve fails mid-way, all locks it took are released. + # Wrap os.open to track fd -> path mapping, then use it in a flock stub. + fd_to_path = {} + real_os_open = os.open + + def tracked_open(path, *args, **kwargs): + fd = real_os_open(path, *args, **kwargs) + fd_to_path[fd] = path + return fd + + # flock will count calls and fail on the second slot file. + flock_calls_per_file = {} + real_flock = bounded_run.fcntl.flock + + def counting_flock(fd, flags): + path = fd_to_path.get(fd, "") + if path not in flock_calls_per_file: + flock_calls_per_file[path] = 0 + flock_calls_per_file[path] += 1 + + # Allow the turn lock and first slot to succeed. + if "reserve.lock" in path or "slot-000.lock" in path: + return real_flock(fd, flags) + + # Fail on the second slot with ENOLCK. + if "slot-001.lock" in path: + raise OSError(errno.ENOLCK, "No locks available") + + # Any other file succeeds. + return real_flock(fd, flags) + + with mock.patch.object(os, "open", tracked_open): + with mock.patch.object(bounded_run.fcntl, "flock", counting_flock): + # Call try_reserve for 2 slots; it should fail after locking slot-000. + with self.assertRaises(bounded_run.WrapperError): + bounded_run.try_reserve(self.directory, 2, 2, []) + + # Now call try_reserve again with real functions (no patches). + # If the first slot was not released, this will fail to get 2 slots. + second_try = bounded_run.try_reserve(self.directory, 2, 2, []) + self.assertIsNotNone(second_try) + self.addCleanup(second_try.release) + self.assertEqual(len(second_try.descriptors), 2) def test_the_turn_lock_is_free_while_the_wrapper_waits(self): # Hold all slots so reserve has to wait From 655f022173f46ad488e44a4567fa5086a2d9d57d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:03:11 +0100 Subject: [PATCH 08/65] feat(skills/bounding-heavy-commands): name exclusive resources for each repository (#45) Co-Authored-By: Claude Haiku 4.5 --- .../scripts/bounded_run.py | 20 ++++++++++++++ .../scripts/tests/test_bounded_run.py | 26 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 75cbf9c..042eb14 100644 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -151,6 +151,26 @@ def ensure_lock_directory(path: str, uid: int) -> None: os.chmod(path, 0o700) +def repository_id(directory: str) -> str: + root = os.path.realpath(directory) + try: + done = subprocess.run( + ["git", "rev-parse", "--git-common-dir"], + cwd=directory, capture_output=True, text=True, timeout=10, + ) + if done.returncode == 0 and done.stdout.strip(): + root = os.path.realpath(os.path.join(directory, done.stdout.strip())) + except (OSError, subprocess.TimeoutExpired): + pass + return hashlib.sha256(root.encode("utf-8")).hexdigest()[:12] + + +def exclusive_file_name(repository: str, name: str) -> str: + if re.match(r"^[A-Za-z0-9._-]+$", name) is None: + raise WrapperError("cannot use the name '%s'; use letters, digits, '.', '_' and '-'" % name) + return "exclusive-%s-%s.lock" % (repository, name) + + class Reservation: def __init__(self, descriptors: Sequence[int]) -> None: self.descriptors = list(descriptors) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index be15354..40669a7 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -311,5 +311,31 @@ def sleep_and_check(seconds): self.assertTrue(turn_lock_acquired[0], "turn lock should be free while reserve waits") +class ExclusiveNameTest(unittest.TestCase): + def test_name_holds_the_repository_and_the_resource(self): + self.assertEqual(bounded_run.exclusive_file_name("abc123", "port-8080"), "exclusive-abc123-port-8080.lock") + + def test_rejects_a_name_with_a_path(self): + for name in ("../x", "a/b", "", "a b"): + with self.subTest(name=name): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.exclusive_file_name("abc123", name) + + def test_worktrees_of_one_repository_have_the_same_id(self): + with tempfile.TemporaryDirectory() as base: + main = os.path.join(base, "main") + other = os.path.join(base, "other") + os.mkdir(main) + git = ["git", "-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false"] + subprocess.run(git + ["init", "--quiet", main], check=True) + subprocess.run(git + ["-C", main, "commit", "--quiet", "--allow-empty", "-m", "first"], check=True) + subprocess.run(git + ["-C", main, "worktree", "add", "--quiet", "--detach", other], check=True) + self.assertEqual(bounded_run.repository_id(main), bounded_run.repository_id(other)) + + def test_two_directories_have_different_ids(self): + with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second: + self.assertNotEqual(bounded_run.repository_id(first), bounded_run.repository_id(second)) + + if __name__ == "__main__": unittest.main() From ced6de83d6de29b1f73859620fe9f9de99499566 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:05:07 +0100 Subject: [PATCH 09/65] feat(skills/bounding-heavy-commands): wait for free memory with a time limit (#45) Co-Authored-By: Claude Haiku 4.5 --- .../scripts/bounded_run.py | 57 +++++++++++++++++++ .../scripts/tests/test_bounded_run.py | 57 +++++++++++++++++++ 2 files changed, 114 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 042eb14..4156677 100644 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -239,3 +239,60 @@ def reserve( log("waiting for %d of %d slot(s)" % (needed, count)) announced = True sleep(poll_seconds * (0.5 + random.random())) + + +def parse_meminfo(text: str) -> Optional[int]: + for line in text.splitlines(): + if line.startswith("MemAvailable:"): + return int(line.split()[1]) // 1024 + return None + + +def parse_vm_stat(text: str) -> Optional[int]: + page = None + pages = 0 + for line in text.splitlines(): + size = re.search(r"page size of (\d+) bytes", line) + if size is not None: + page = int(size.group(1)) + counted = re.match(r"^Pages (free|inactive|speculative):\s+(\d+)\.", line) + if counted is not None: + pages += int(counted.group(2)) + if page is None: + return None + return pages * page // (1024 * 1024) + + +def available_memory_mib() -> Optional[int]: + try: + with open("/proc/meminfo") as handle: + return parse_meminfo(handle.read()) + except OSError: + pass + try: + done = subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=10) + except (OSError, subprocess.TimeoutExpired): + return None + return parse_vm_stat(done.stdout) + + +def wait_for_memory( + budget_mib: int, limit_seconds: float, poll_seconds: float, + read_available: Callable[[], Optional[int]] = available_memory_mib, + sleep: Callable[[float], None] = time.sleep, +) -> bool: + waited = 0.0 + while True: + available = read_available() + if available is None: + log("cannot read the free memory; starting") + return True + if available >= budget_mib: + log("%d MiB free, budget %d MiB; starting" % (available, budget_mib)) + return True + if waited >= limit_seconds: + log("WARNING: only %d MiB free after %ds, budget %d MiB; starting" % (available, waited, budget_mib)) + return False + log("%d MiB free, budget %d MiB; waiting (%d of %ds)" % (available, budget_mib, waited, limit_seconds)) + sleep(poll_seconds) + waited += poll_seconds diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 40669a7..949fc2e 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -337,5 +337,62 @@ def test_two_directories_have_different_ids(self): self.assertNotEqual(bounded_run.repository_id(first), bounded_run.repository_id(second)) +class MemoryReadTest(unittest.TestCase): + def test_reads_the_available_memory_of_meminfo(self): + text = "MemTotal: 32000000 kB\nMemFree: 1000000 kB\nMemAvailable: 8388608 kB\n" + self.assertEqual(bounded_run.parse_meminfo(text), 8192) + + def test_meminfo_without_the_line_gives_nothing(self): + self.assertIsNone(bounded_run.parse_meminfo("MemTotal: 1 kB\n")) + + def test_reads_the_pages_of_vm_stat(self): + text = ( + "Mach Virtual Memory Statistics: (page size of 16384 bytes)\n" + "Pages free: 10000.\n" + "Pages active: 900000.\n" + "Pages inactive: 20000.\n" + "Pages speculative: 2000.\n" + "Pages wired down: 100000.\n" + ) + self.assertEqual(bounded_run.parse_vm_stat(text), 32000 * 16384 // (1024 * 1024)) + + def test_vm_stat_without_a_page_size_gives_nothing(self): + self.assertIsNone(bounded_run.parse_vm_stat("Pages free: 10.\n")) + + +class MemoryWaitTest(unittest.TestCase): + def setUp(self): + patcher = mock.patch.object(bounded_run, "log") + self.log = patcher.start() + self.addCleanup(patcher.stop) + + def wait(self, values, limit): + readings = list(values) + sleeps = [] + result = bounded_run.wait_for_memory( + 4096, limit, 5.0, read_available=lambda: readings.pop(0), sleep=sleeps.append, + ) + return result, sleeps + + def test_starts_at_once_when_the_memory_is_free(self): + self.assertEqual(self.wait([8000], 300), (True, [])) + + def test_waits_until_the_memory_is_free(self): + self.assertEqual(self.wait([1000, 2000, 5000], 300), (True, [5.0, 5.0])) + + def test_starts_after_the_time_limit(self): + self.assertEqual(self.wait([1000, 1000, 1000], 10), (False, [5.0, 5.0])) + + def test_a_limit_of_zero_does_not_wait(self): + self.assertEqual(self.wait([1000], 0), (False, [])) + + def test_a_start_after_the_time_limit_is_a_warning(self): + self.wait([1000], 0) + self.assertTrue(self.log.call_args[0][0].startswith("WARNING: ")) + + def test_starts_when_the_memory_is_not_readable(self): + self.assertEqual(self.wait([None], 300), (True, [])) + + if __name__ == "__main__": unittest.main() From 5ba497130a732658a942c719c80e92a40b795089 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:07:08 +0100 Subject: [PATCH 10/65] feat(skills/bounding-heavy-commands): build the cgroup cap and probe it (#45) Co-Authored-By: Claude Haiku 4.5 --- .../scripts/bounded_run.py | 25 ++++++++++ .../scripts/tests/test_bounded_run.py | 49 +++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 4156677..b0492d6 100644 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -296,3 +296,28 @@ def wait_for_memory( log("%d MiB free, budget %d MiB; waiting (%d of %ds)" % (available, budget_mib, waited, limit_seconds)) sleep(poll_seconds) waited += poll_seconds + + +def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str) -> List[str]: + prefix = [ + "systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", unit, + "-p", "MemoryMax=%dM" % budget_mib, + "-p", "MemorySwapMax=0", + ] + if cpus is not None: + prefix += ["-p", "CPUQuota=%d%%" % (cpus * 100)] + return prefix + ["--"] + + +def cap_usable( + prefix: Sequence[str], platform: str = sys.platform, + which: Callable[[str], Optional[str]] = shutil.which, + run: Callable[..., "subprocess.CompletedProcess"] = subprocess.run, +) -> bool: + if not platform.startswith("linux") or which("systemd-run") is None: + return False + try: + done = run(list(prefix) + ["true"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15) + except (OSError, subprocess.TimeoutExpired): + return False + return done.returncode == 0 diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 949fc2e..763c528 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -394,5 +394,54 @@ def test_starts_when_the_memory_is_not_readable(self): self.assertEqual(self.wait([None], 300), (True, [])) +class CapTest(unittest.TestCase): + def test_prefix_holds_the_limits(self): + self.assertEqual(bounded_run.cap_prefix(6144, 4, "unit-1"), [ + "systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", "unit-1", + "-p", "MemoryMax=6144M", "-p", "MemorySwapMax=0", + "-p", "CPUQuota=400%", "--", + ]) + + def test_prefix_without_cpus_has_no_quota(self): + self.assertNotIn("CPUQuota", " ".join(bounded_run.cap_prefix(6144, None, "unit-1"))) + + def probe(self, platform, tool, code=0, error=None): + calls = [] + + def run(command, **keywords): + calls.append(command) + if error is not None: + raise error + return subprocess.CompletedProcess(command, code) + + usable = bounded_run.cap_usable( + bounded_run.cap_prefix(1024, 2, "unit-1"), platform=platform, which=lambda name: tool, run=run, + ) + return usable, calls + + def test_usable_when_the_probe_succeeds(self): + usable, calls = self.probe("linux", "/usr/bin/systemd-run") + self.assertTrue(usable) + self.assertEqual(calls[0][-1], "true") + self.assertIn("CPUQuota=200%", calls[0]) + + def test_not_usable_when_the_probe_fails(self): + self.assertFalse(self.probe("linux", "/usr/bin/systemd-run", code=1)[0]) + + def test_not_usable_when_the_probe_does_not_return(self): + error = subprocess.TimeoutExpired("systemd-run", 15) + self.assertFalse(self.probe("linux", "/usr/bin/systemd-run", error=error)[0]) + + def test_not_usable_without_the_tool(self): + usable, calls = self.probe("linux", None) + self.assertFalse(usable) + self.assertEqual(calls, []) + + def test_not_usable_on_a_different_system(self): + usable, calls = self.probe("darwin", "/usr/bin/systemd-run") + self.assertFalse(usable) + self.assertEqual(calls, []) + + if __name__ == "__main__": unittest.main() From 624bc4f29938ad2b6213071ae575ac2e2e0f7e0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:09:26 +0100 Subject: [PATCH 11/65] feat(skills/bounding-heavy-commands): measure the peak memory of a command (#45) Co-Authored-By: Claude Haiku 4.5 --- .../scripts/bounded_run.py | 82 +++++++++++++++++++ .../scripts/tests/test_bounded_run.py | 77 +++++++++++++++++ 2 files changed, 159 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index b0492d6..75c9d0b 100644 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -321,3 +321,85 @@ def cap_usable( except (OSError, subprocess.TimeoutExpired): return False return done.returncode == 0 + + +def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]: + try: + with open(os.path.join(proc_root, str(pid), "cgroup")) as handle: + text = handle.read() + except OSError: + return None + for line in text.splitlines(): + if line.startswith("0::") and line.strip().endswith("/%s.scope" % unit): + return cgroup_root + line.strip()[3:] + return None + + +def cgroup_peak_mib(directory: str, names: Sequence[str] = ("memory.peak", "memory.current")) -> Optional[int]: + for name in names: + try: + with open(os.path.join(directory, name)) as handle: + return math.ceil(int(handle.read().strip()) / (1024 * 1024)) + except (OSError, ValueError): + continue + return None + + +def parse_group_rss_mib(text: str, group: int) -> Optional[int]: + total = 0 + found = False + for line in text.splitlines(): + parts = line.split() + if len(parts) == 2 and parts[0] == str(group) and parts[1].isdigit(): + total += int(parts[1]) + found = True + if not found: + return None + return math.ceil(total / 1024) + + +def group_rss_mib(group: int) -> Optional[int]: + try: + done = subprocess.run(["ps", "-A", "-o", "pgid=", "-o", "rss="], capture_output=True, text=True, timeout=10) + except (OSError, subprocess.TimeoutExpired): + return None + return parse_group_rss_mib(done.stdout, group) + + +def rusage_peak_mib(maxrss: int, platform: str = sys.platform) -> int: + if platform == "darwin": + return math.ceil(maxrss / (1024 * 1024)) + return math.ceil(maxrss / 1024) + + +def suggested_budget_mib(peak_mib: int, approximate: bool) -> int: + margin = MARGIN_APPROXIMATE if approximate else MARGIN_EXACT + return max(1, math.ceil(peak_mib * (1 + margin) / BUDGET_STEP_MIB)) * BUDGET_STEP_MIB + + +class PeakTracker(threading.Thread): + def __init__(self, read_sample: Callable[[], Optional[int]], interval: float) -> None: + super().__init__(daemon=True) + self.read_sample = read_sample + self.interval = interval + self.peak: Optional[int] = None + self.done = threading.Event() + + def run(self) -> None: + while True: + self.sample() + if self.done.wait(self.interval): + return + + def sample(self) -> None: + try: + value = self.read_sample() + except Exception: + value = None + if value is not None and (self.peak is None or value > self.peak): + self.peak = value + + def finish(self) -> Optional[int]: + self.done.set() + self.join(timeout=15) + return self.peak diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 763c528..d84997b 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -443,5 +443,82 @@ def test_not_usable_on_a_different_system(self): self.assertEqual(calls, []) +class MeasurementTest(unittest.TestCase): + def test_finds_the_cgroup_of_the_unit(self): + with tempfile.TemporaryDirectory() as proc: + os.mkdir(os.path.join(proc, "42")) + Path(proc, "42", "cgroup").write_text("0::/user.slice/user-1.slice/app.slice/unit-1.scope\n") + self.assertEqual( + bounded_run.cgroup_directory(42, "unit-1", proc_root=proc, cgroup_root="/cg"), + "/cg/user.slice/user-1.slice/app.slice/unit-1.scope", + ) + + def test_ignores_the_cgroup_before_the_scope_exists(self): + with tempfile.TemporaryDirectory() as proc: + os.mkdir(os.path.join(proc, "42")) + Path(proc, "42", "cgroup").write_text("0::/user.slice/user-1.slice/session-2.scope\n") + self.assertIsNone(bounded_run.cgroup_directory(42, "unit-1", proc_root=proc)) + + def test_a_process_that_is_gone_has_no_cgroup(self): + with tempfile.TemporaryDirectory() as proc: + self.assertIsNone(bounded_run.cgroup_directory(42, "unit-1", proc_root=proc)) + + def test_reads_the_peak_of_the_cgroup(self): + with tempfile.TemporaryDirectory() as directory: + Path(directory, "memory.peak").write_text("%d\n" % (300 * 1024 * 1024)) + Path(directory, "memory.current").write_text("%d\n" % (100 * 1024 * 1024)) + self.assertEqual(bounded_run.cgroup_peak_mib(directory), 300) + + def test_reads_the_current_value_when_the_peak_file_is_absent(self): + with tempfile.TemporaryDirectory() as directory: + Path(directory, "memory.current").write_text("%d\n" % (100 * 1024 * 1024)) + self.assertEqual(bounded_run.cgroup_peak_mib(directory), 100) + + def test_reads_only_the_files_that_the_caller_names(self): + with tempfile.TemporaryDirectory() as directory: + Path(directory, "memory.current").write_text("%d\n" % (100 * 1024 * 1024)) + self.assertIsNone(bounded_run.cgroup_peak_mib(directory, names=("memory.peak",))) + + def test_a_cgroup_without_files_gives_nothing(self): + with tempfile.TemporaryDirectory() as directory: + self.assertIsNone(bounded_run.cgroup_peak_mib(directory)) + + def test_adds_the_memory_of_the_process_group(self): + text = " 100 2048\n 100 1024\n 200 9999\n 1 512\n" + self.assertEqual(bounded_run.parse_group_rss_mib(text, 100), 3) + + def test_a_group_with_no_process_gives_nothing(self): + self.assertIsNone(bounded_run.parse_group_rss_mib(" 200 9999\n", 100)) + + def test_reads_the_memory_of_a_real_process_group(self): + self.assertGreater(bounded_run.group_rss_mib(os.getpgrp()), 0) + + def test_the_peak_of_the_system_has_a_different_unit_on_each_system(self): + self.assertEqual(bounded_run.rusage_peak_mib(2048 * 1024, platform="linux"), 2048) + self.assertEqual(bounded_run.rusage_peak_mib(2048 * 1024 * 1024, platform="darwin"), 2048) + + def test_the_suggested_budget_has_a_margin(self): + self.assertEqual(bounded_run.suggested_budget_mib(4000, approximate=False), 5120) + self.assertEqual(bounded_run.suggested_budget_mib(4000, approximate=True), 6144) + + def test_the_tracker_keeps_the_largest_sample(self): + samples = [100, None, 900, 300] + tracker = bounded_run.PeakTracker(lambda: samples.pop(0) if samples else 300, 0.01) + tracker.start() + deadline = time.time() + 5 + while samples and time.time() < deadline: + time.sleep(0.01) + self.assertEqual(tracker.finish(), 900) + + def test_the_tracker_survives_a_reader_that_fails(self): + def read(): + raise OSError("gone") + + tracker = bounded_run.PeakTracker(read, 0.01) + tracker.start() + time.sleep(0.05) + self.assertIsNone(tracker.finish()) + + if __name__ == "__main__": unittest.main() From 46a9638bcce7b515b814297776f9454fbef471b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:17:45 +0100 Subject: [PATCH 12/65] feat(skills/bounding-heavy-commands): run a command and pass its exit code and signals (#45) Adds the command line parsing, the run of the command with its exit code and signal forwarding, the nested-call path, and main. Also dedupes repeated --exclusive names in parse_arguments so a later task does not lock the same file twice and wait on its own lock forever. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 173 ++++++++++++ .../scripts/tests/test_bounded_run.py | 250 ++++++++++++++++++ 2 files changed, 423 insertions(+) mode change 100644 => 100755 skills/bounding-heavy-commands/scripts/bounded_run.py diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py old mode 100644 new mode 100755 index 75c9d0b..2cf89e6 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -403,3 +403,176 @@ def finish(self) -> Optional[int]: self.done.set() self.join(timeout=15) return self.peak + + +def exit_code_of(status: int) -> int: + code = os.waitstatus_to_exitcode(status) + if code < 0: + return 128 - code + return code + + +def run_command( + command: Sequence[str], environ: Mapping[str, str], + on_start: Optional[Callable[[int], None]] = None, +) -> Tuple[int, int]: + """Runs the command in its own process group. Returns the exit code and ru_maxrss.""" + received: List[int] = [] + started: List[int] = [] + + def forward(signum: int, frame: object) -> None: + received.append(signum) + if started: + try: + os.killpg(started[0], signum if len(received) == 1 else signal.SIGKILL) + except ProcessLookupError: + pass + + previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGINT, signal.SIGTERM)} + try: + try: + process = subprocess.Popen(list(command), env=dict(environ), start_new_session=True) + except OSError as error: + raise WrapperError("cannot start '%s': %s" % (command[0], error)) + started.append(process.pid) + if received: + os.killpg(process.pid, received[0]) + if on_start is not None: + on_start(process.pid) + _, status, usage = os.wait4(process.pid, 0) + process.returncode = exit_code_of(status) + finally: + for signum, handler in previous.items(): + signal.signal(signum, handler) + if received: + return 128 + received[0], usage.ru_maxrss + return process.returncode, usage.ru_maxrss + + +def inside_cap( + peak_file: str, unit: str, command: Sequence[str], + proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup", +) -> int: + """Runs the command as a child in the cgroup of the cap, then writes the peak of that cgroup. + + The cgroup exists for as long as this process is in it. Thus the peak is readable after the + command stops, which is not possible from outside the cgroup. + """ + def keep_running(signum: int, frame: object) -> None: + pass + + previous = {signum: signal.signal(signum, keep_running) for signum in (signal.SIGINT, signal.SIGTERM)} + try: + try: + process = subprocess.Popen(list(command)) + except OSError as error: + log("cannot start '%s': %s" % (command[0], error)) + return EXIT_WRAPPER + _, status = os.waitpid(process.pid, 0) + process.returncode = exit_code_of(status) + finally: + for signum, handler in previous.items(): + signal.signal(signum, handler) + directory = cgroup_directory(os.getpid(), unit, proc_root, cgroup_root) + peak = cgroup_peak_mib(directory, names=("memory.peak",)) if directory is not None else None + if peak is not None: + try: + with open(peak_file, "w") as handle: + handle.write("%d\n" % peak) + except OSError: + pass + return process.returncode + + +def read_peak_file(path: str) -> Optional[int]: + try: + with open(path) as handle: + text = handle.read().strip() + os.unlink(path) + except OSError: + return None + return int(text) if text.isdigit() else None + + +class Options: + def __init__(self) -> None: + self.memory: Optional[str] = None + self.cpus: Optional[int] = None + self.exclusive: List[str] = [] + self.measure = False + self.command: List[str] = [] + + +def parse_arguments(argv: Sequence[str]) -> Options: + options = Options() + arguments = list(argv) + if "--" not in arguments: + raise WrapperError("the '--' before the command is missing\n" + USAGE) + split = arguments.index("--") + options.command = arguments[split + 1:] + if not options.command: + raise WrapperError("the command is missing\n" + USAGE) + flags = arguments[:split] + while flags: + flag = flags.pop(0) + if flag == "--measure": + options.measure = True + continue + if flag not in ("--memory", "--cpus", "--exclusive"): + raise WrapperError("cannot read the option '%s'\n%s" % (flag, USAGE)) + if not flags: + raise WrapperError("the option '%s' needs a value\n%s" % (flag, USAGE)) + value = flags.pop(0) + if flag == "--memory": + options.memory = value + elif flag == "--exclusive": + if value not in options.exclusive: + options.exclusive.append(value) + else: + if not value.isdigit() or int(value) < 1: + raise WrapperError("cannot read --cpus '%s'; use a whole number of 1 or more" % value) + options.cpus = int(value) + return options + + +def bounded(options: Options, environ: Mapping[str, str]) -> int: + settings = Settings(environ) + if options.memory is not None: + budget = parse_size_mib(options.memory) + else: + budget = default_budget_mib(settings.total_mib, settings.slot_mib) + command = list(options.command) + if shutil.which(command[0]) is None: + raise WrapperError("cannot start '%s': the command does not exist" % command[0]) + + child_environ: Dict[str, str] = dict(environ) + child_environ[ACTIVE_VARIABLE] = "1" + child_environ["BOUNDED_RUN_MEMORY_MIB"] = str(budget) + child_environ["BOUNDED_RUN_CPUS"] = str(options.cpus if options.cpus is not None else (os.cpu_count() or 1)) + + code, maxrss = run_command(command, child_environ) + log("budget %d MiB, exit %d" % (budget, code)) + return code + + +def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, str]] = None) -> int: + arguments = list(sys.argv[1:] if argv is None else argv) + variables = os.environ if environ is None else environ + try: + if len(arguments) > 4 and arguments[0] == "--inside-cap" and arguments[3] == "--": + return inside_cap(arguments[1], arguments[2], arguments[4:]) + options = parse_arguments(arguments) + if variables.get(ACTIVE_VARIABLE): + log("nested call; running the command directly") + try: + os.execvpe(options.command[0], options.command, dict(variables)) + except OSError as error: + raise WrapperError("cannot start '%s': %s" % (options.command[0], error)) + return bounded(options, variables) + except WrapperError as error: + log(str(error)) + return EXIT_WRAPPER + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index d84997b..12f0830 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -520,5 +520,255 @@ def read(): self.assertIsNone(tracker.finish()) +class ArgumentTest(unittest.TestCase): + def test_reads_all_options(self): + options = bounded_run.parse_arguments( + ["--memory", "6G", "--cpus", "4", "--exclusive", "a", "--exclusive", "b", "--measure", "--", "tool", "--memory", "x"] + ) + self.assertEqual( + (options.memory, options.cpus, options.exclusive, options.measure, options.command), + ("6G", 4, ["a", "b"], True, ["tool", "--memory", "x"]), + ) + + def test_rejects_bad_arguments(self): + for arguments in (["tool"], ["--memory", "6G", "--"], ["--fast", "--", "tool"], ["--memory", "--", "tool"], ["--cpus", "0", "--", "tool"], ["--cpus", "two", "--", "tool"]): + with self.subTest(arguments=arguments): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.parse_arguments(arguments) + + def test_a_repeated_exclusive_name_is_kept_one_time(self): + options = bounded_run.parse_arguments( + ["--exclusive", "port", "--exclusive", "cache", "--exclusive", "port", "--", "tool"] + ) + self.assertEqual(options.exclusive, ["port", "cache"]) + + +class InsideCapTest(unittest.TestCase): + def setUp(self): + patcher = mock.patch.object(bounded_run, "log") + patcher.start() + self.addCleanup(patcher.stop) + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.proc = os.path.join(self.base.name, "proc") + self.cgroups = os.path.join(self.base.name, "cgroups") + self.peak_file = os.path.join(self.base.name, "peak") + os.makedirs(os.path.join(self.proc, str(os.getpid()))) + Path(self.proc, str(os.getpid()), "cgroup").write_text("0::/user.slice/unit-1.scope\n") + self.cgroup = os.path.join(self.cgroups, "user.slice", "unit-1.scope") + os.makedirs(self.cgroup) + + def inside(self, command, unit="unit-1"): + return bounded_run.inside_cap(self.peak_file, unit, command, proc_root=self.proc, cgroup_root=self.cgroups) + + def test_writes_the_peak_after_the_command_stops(self): + Path(self.cgroup, "memory.peak").write_text("%d\n" % (300 * 1024 * 1024)) + self.assertEqual(self.inside([sys.executable, "-c", "import sys; sys.exit(6)"]), 6) + self.assertEqual(bounded_run.read_peak_file(self.peak_file), 300) + self.assertFalse(os.path.exists(self.peak_file)) + + def test_writes_nothing_without_the_peak_file_of_the_kernel(self): + Path(self.cgroup, "memory.current").write_text("%d\n" % (100 * 1024 * 1024)) + self.assertEqual(self.inside([sys.executable, "-c", "pass"]), 0) + self.assertIsNone(bounded_run.read_peak_file(self.peak_file)) + + def test_writes_nothing_outside_the_cgroup_of_the_unit(self): + Path(self.cgroup, "memory.peak").write_text("%d\n" % (300 * 1024 * 1024)) + self.assertEqual(self.inside([sys.executable, "-c", "pass"], unit="unit-2"), 0) + self.assertIsNone(bounded_run.read_peak_file(self.peak_file)) + + def test_a_command_that_a_signal_stopped_gives_128_plus_the_signal(self): + script = "import os, signal; os.kill(os.getpid(), signal.SIGKILL)" + self.assertEqual(self.inside([sys.executable, "-c", script]), 137) + + def test_a_command_that_does_not_exist_gives_125(self): + self.assertEqual(self.inside(["/nonexistent/tool-for-the-test"]), 125) + + def test_puts_the_signal_handlers_back(self): + before = signal.getsignal(signal.SIGTERM) + self.inside([sys.executable, "-c", "pass"]) + self.assertIs(signal.getsignal(signal.SIGTERM), before) + + def test_a_peak_file_with_other_text_gives_nothing(self): + Path(self.peak_file).write_text("not a number\n") + self.assertIsNone(bounded_run.read_peak_file(self.peak_file)) + + +class WrapperProcessCase(unittest.TestCase): + """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" + + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.events = os.path.join(self.base.name, "events") + self.environ = dict(os.environ) + self.environ.pop("BOUNDED_RUN_ACTIVE", None) + self.environ.update({ + "BOUNDED_RUN_LOCK_DIR": os.path.join(self.base.name, "locks"), + "BOUNDED_RUN_TOTAL_MIB": "6144", + "BOUNDED_RUN_RESERVE_MIB": "2048", + "BOUNDED_RUN_SLOT_MIB": "2048", + "BOUNDED_RUN_POLL_SECONDS": "0.05", + "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", + "BOUNDED_RUN_SAMPLE_SECONDS": "0.1", + "BOUNDED_RUN_NO_CAP": "1", + "EVENTS": self.events, + }) + self.processes = [] + + def tearDown(self): + for process in self.processes: + if process.poll() is None: + process.kill() + process.wait() + for stream in (process.stdout, process.stderr): + if stream is not None: + stream.close() + for line in self.read_events(): + try: + os.kill(int(line.split()[2]), signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + + def wrapper(self, options, command, **environ): + variables = dict(self.environ) + variables.update(environ) + process = subprocess.Popen( + [sys.executable, WRAPPER] + options + ["--"] + command, + env=variables, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + self.processes.append(process) + return process + + def worker(self, name, memory, hold="0.3", options=(), release=""): + command = [sys.executable, "-c", WORKER, name] + return self.wrapper(["--memory", memory] + list(options), command, HOLD=hold, RELEASE=release) + + def read_events(self): + try: + with open(self.events) as handle: + return handle.read().splitlines() + except OSError: + return [] + + def wait_for_event(self, kind, name, seconds=30.0): + deadline = time.time() + seconds + while time.time() < deadline: + for line in self.read_events(): + if line.split()[:2] == [kind, name]: + return line + time.sleep(0.02) + self.fail("no '%s %s' event after %s seconds; events: %s" % (kind, name, seconds, self.read_events())) + + def peak_concurrency(self): + running = 0 + peak = 0 + for line in self.read_events(): + running += 1 if line.startswith("start ") else -1 + peak = max(peak, running) + return peak + + +class WrapperProcessTest(WrapperProcessCase): + def test_passes_the_exit_code(self): + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "import sys; sys.exit(7)"]) + self.assertEqual(process.wait(timeout=60), 7) + + def test_passes_the_output(self): + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "print('from the command')"]) + output, errors = process.communicate(timeout=60) + self.assertEqual(output, "from the command\n") + self.assertIn("bounded-run: budget 2048 MiB", errors) + + def test_a_command_that_a_signal_stopped_gives_128_plus_the_signal(self): + script = "import os, signal; os.kill(os.getpid(), signal.SIGKILL)" + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", script]) + self.assertEqual(process.wait(timeout=60), 137) + + def test_a_failure_of_the_wrapper_gives_125(self): + process = subprocess.Popen( + [sys.executable, WRAPPER, "--memory", "2G", "tool"], env=self.environ, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + self.processes.append(process) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 125) + self.assertTrue(errors.startswith("bounded-run: "), errors) + + def test_a_command_that_does_not_exist_gives_125(self): + process = self.wrapper(["--memory", "2G"], ["/nonexistent/tool-for-the-test"]) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 125) + self.assertIn("cannot start", errors) + follower = self.worker("after", "4G", hold="0") + self.assertEqual(follower.wait(timeout=60), 0) + + def test_the_command_gets_the_budget_and_the_marker(self): + script = "import os; print(os.environ['BOUNDED_RUN_ACTIVE'], os.environ['BOUNDED_RUN_MEMORY_MIB'], os.environ['BOUNDED_RUN_CPUS'])" + process = self.wrapper(["--memory", "2G", "--cpus", "3"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual(output, "1 2048 3\n") + + def test_the_command_reads_the_input_of_the_wrapper(self): + variables = dict(self.environ) + process = subprocess.Popen( + [sys.executable, WRAPPER, "--memory", "2G", "--", sys.executable, "-c", "import sys; print(sys.stdin.read().upper())"], + env=variables, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + self.processes.append(process) + output, errors = process.communicate("text for the command", timeout=60) + process.stdin = None + self.assertEqual((process.returncode, output), (0, "TEXT FOR THE COMMAND\n"), errors) + + def test_a_nested_call_does_not_wait_for_its_own_slots(self): + inner = [sys.executable, WRAPPER, "--memory", "4G", "--", sys.executable, "-c", "import sys; print('inner'); sys.exit(3)"] + process = self.wrapper(["--memory", "4G"], inner) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, output), (3, "inner\n"), errors) + self.assertIn("nested call", errors) + + def test_a_nested_call_of_a_command_that_does_not_exist_gives_125(self): + process = self.wrapper(["--memory", "2G"], ["/nonexistent/tool-for-the-test"], BOUNDED_RUN_ACTIVE="1") + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 125, errors) + self.assertNotIn("Traceback", errors) + + def test_a_stop_signal_stops_the_command(self): + for signum, code in ((signal.SIGTERM, 143), (signal.SIGINT, 130)): + with self.subTest(signal=signum): + name = "stopped-%d" % code + process = self.worker(name, "2G", hold="30") + line = self.wait_for_event("start", name) + process.send_signal(signum) + self.assertEqual(process.wait(timeout=60), code) + child = int(line.split()[2]) + deadline = time.time() + 5 + alive = True + while alive and time.time() < deadline: + try: + os.kill(child, 0) + time.sleep(0.05) + except ProcessLookupError: + alive = False + self.assertFalse(alive, "the command still runs") + + def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self): + script = ( + "import os, signal, sys, time\n" + "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" + "descriptor = os.open(os.environ['EVENTS'], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)\n" + "os.write(descriptor, ('start stubborn %d\\n' % os.getpid()).encode())\n" + "os.close(descriptor)\n" + "time.sleep(30)\n" + ) + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", script]) + self.wait_for_event("start", "stubborn") + process.send_signal(signal.SIGTERM) + time.sleep(0.3) + self.assertIsNone(process.poll()) + process.send_signal(signal.SIGTERM) + self.assertEqual(process.wait(timeout=60), 143) + + if __name__ == "__main__": unittest.main() From 119471b8181b61cadcc6c5c5fdff090b70bab265 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:39:29 +0100 Subject: [PATCH 13/65] fix(skills/bounding-heavy-commands): stop the command when the wrapper fails after the start (#45) An exception between Popen and wait4 (a broken on_start hook, a future caller's error) left the command running with no parent: neither killpg call guarded PermissionError, which macOS raises for a group that holds only zombies, and nothing reaped the command on a failure. run_command now guards both killpg calls and wraps the run from the start to the end of the wait so any exception kills the command's process group and reaps it before the exception propagates. Also check the command against the PATH of the environment it will run in, not the wrapper's own PATH; they can differ. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 28 ++++++++++++++----- .../scripts/tests/test_bounded_run.py | 23 +++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 2cf89e6..17e0fbf 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -425,7 +425,7 @@ def forward(signum: int, frame: object) -> None: if started: try: os.killpg(started[0], signum if len(received) == 1 else signal.SIGKILL) - except ProcessLookupError: + except (ProcessLookupError, PermissionError): pass previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGINT, signal.SIGTERM)} @@ -435,11 +435,25 @@ def forward(signum: int, frame: object) -> None: except OSError as error: raise WrapperError("cannot start '%s': %s" % (command[0], error)) started.append(process.pid) - if received: - os.killpg(process.pid, received[0]) - if on_start is not None: - on_start(process.pid) - _, status, usage = os.wait4(process.pid, 0) + try: + if received: + try: + os.killpg(process.pid, received[0]) + except (ProcessLookupError, PermissionError): + pass + if on_start is not None: + on_start(process.pid) + _, status, usage = os.wait4(process.pid, 0) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + try: + os.waitpid(process.pid, 0) + except ChildProcessError: + pass + raise process.returncode = exit_code_of(status) finally: for signum, handler in previous.items(): @@ -542,7 +556,7 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: else: budget = default_budget_mib(settings.total_mib, settings.slot_mib) command = list(options.command) - if shutil.which(command[0]) is None: + if shutil.which(command[0], path=environ.get("PATH")) is None: raise WrapperError("cannot start '%s': the command does not exist" % command[0]) child_environ: Dict[str, str] = dict(environ) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 12f0830..7c08912 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -594,6 +594,29 @@ def test_a_peak_file_with_other_text_gives_nothing(self): self.assertIsNone(bounded_run.read_peak_file(self.peak_file)) +class RunCommandTest(unittest.TestCase): + def test_an_error_after_the_start_stops_the_command(self): + pids = [] + + def on_start(pid): + pids.append(pid) + raise RuntimeError("boom") + + command = [sys.executable, "-c", "import time; time.sleep(300)"] + with self.assertRaises(RuntimeError): + bounded_run.run_command(command, dict(os.environ), on_start=on_start) + self.assertEqual(len(pids), 1) + deadline = time.time() + 10 + alive = True + while alive and time.time() < deadline: + try: + os.kill(pids[0], 0) + time.sleep(0.05) + except ProcessLookupError: + alive = False + self.assertFalse(alive, "the command still runs") + + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" From f910b1d4479f9e3de7fa00e14e157ec66bc534e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:40:13 +0100 Subject: [PATCH 14/65] fix(skills/bounding-heavy-commands): stop the command on a hangup (#45) The command runs in a new session, so a SIGHUP of the wrapper's terminal never reaches it. A closed agent shell is a normal way for this to happen. The wrapper took the default action and died, leaving the command running with nothing to stop it. run_command and inside_cap now handle SIGHUP the same way as SIGTERM: the first hangup goes to the command's process group, a second signal kills the group, and the wrapper stops with status 129. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 4 ++-- .../scripts/tests/test_bounded_run.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 17e0fbf..2950864 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -428,7 +428,7 @@ def forward(signum: int, frame: object) -> None: except (ProcessLookupError, PermissionError): pass - previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGINT, signal.SIGTERM)} + previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)} try: try: process = subprocess.Popen(list(command), env=dict(environ), start_new_session=True) @@ -475,7 +475,7 @@ def inside_cap( def keep_running(signum: int, frame: object) -> None: pass - previous = {signum: signal.signal(signum, keep_running) for signum in (signal.SIGINT, signal.SIGTERM)} + previous = {signum: signal.signal(signum, keep_running) for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)} try: try: process = subprocess.Popen(list(command)) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 7c08912..acc53d7 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -775,6 +775,23 @@ def test_a_stop_signal_stops_the_command(self): alive = False self.assertFalse(alive, "the command still runs") + def test_a_hangup_stops_the_command_and_gives_129(self): + name = "hangup-129" + process = self.worker(name, "2G", hold="300") + line = self.wait_for_event("start", name) + process.send_signal(signal.SIGHUP) + self.assertEqual(process.wait(timeout=60), 129) + child = int(line.split()[2]) + deadline = time.time() + 5 + alive = True + while alive and time.time() < deadline: + try: + os.kill(child, 0) + time.sleep(0.05) + except ProcessLookupError: + alive = False + self.assertFalse(alive, "the command still runs") + def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self): script = ( "import os, signal, sys, time\n" From 93d8a8d2fdb63886b849d933a4f70fc2bf0a98b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:41:53 +0100 Subject: [PATCH 15/65] test(skills/bounding-heavy-commands): make the signal tests fail on a signal that is not forwarded (#45) The command in the two stop-signal tests held for 30 seconds while the wait had a timeout of 60 seconds. A wrapper that never forwards the signal still lets the command end by itself inside that window, so the test passes even though the property it checks is broken. Both tests now hold for 300 seconds, so a broken forward times out the wait and fails the test instead. Also drop a line that sets process.stdin to None after communicate() already closed it; it has no effect. Co-Authored-By: Claude Fable 5.1 --- .../scripts/tests/test_bounded_run.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index acc53d7..19a5ada 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -740,7 +740,6 @@ def test_the_command_reads_the_input_of_the_wrapper(self): ) self.processes.append(process) output, errors = process.communicate("text for the command", timeout=60) - process.stdin = None self.assertEqual((process.returncode, output), (0, "TEXT FOR THE COMMAND\n"), errors) def test_a_nested_call_does_not_wait_for_its_own_slots(self): @@ -760,7 +759,7 @@ def test_a_stop_signal_stops_the_command(self): for signum, code in ((signal.SIGTERM, 143), (signal.SIGINT, 130)): with self.subTest(signal=signum): name = "stopped-%d" % code - process = self.worker(name, "2G", hold="30") + process = self.worker(name, "2G", hold="300") line = self.wait_for_event("start", name) process.send_signal(signum) self.assertEqual(process.wait(timeout=60), code) @@ -799,7 +798,7 @@ def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self): "descriptor = os.open(os.environ['EVENTS'], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)\n" "os.write(descriptor, ('start stubborn %d\\n' % os.getpid()).encode())\n" "os.close(descriptor)\n" - "time.sleep(30)\n" + "time.sleep(300)\n" ) process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", script]) self.wait_for_event("start", "stubborn") From cc802d419a5813b8e73a403df6b1e8c092de3484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:51:14 +0100 Subject: [PATCH 16/65] test(skills/bounding-heavy-commands): stop the command of a test that fails (#45) test_an_error_after_the_start_stops_the_command started a command that holds for 300 seconds and relied on run_command's own guard to stop it. When the assertion failed, or if that guard ever regresses, the command kept running with no cleanup. The test now registers an addCleanup, before the call to run_command, that sends SIGKILL to the command's process group and reaps it; addCleanup callbacks run on every path, including a failing assertion. Also gave the command's argument list a marker unique to this test, for a pgrep check. Checked every other test class that starts a process: ExclusiveNameTest and MeasurementTest only use synchronous subprocess.run calls that finish before returning. InsideCapTest's inside_cap already waits for its child before returning. WrapperProcessCase (and its subclass WrapperProcessTest) already kill every process they start, and every pid recorded in the events file, from their own tearDown. None of those needed a change. Co-Authored-By: Claude Fable 5.1 --- .../scripts/tests/test_bounded_run.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 19a5ada..a0b439d 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -598,11 +598,24 @@ class RunCommandTest(unittest.TestCase): def test_an_error_after_the_start_stops_the_command(self): pids = [] + def cleanup(): + for pid in pids: + try: + os.killpg(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + try: + os.waitpid(pid, 0) + except ChildProcessError: + pass + + self.addCleanup(cleanup) + def on_start(pid): pids.append(pid) raise RuntimeError("boom") - command = [sys.executable, "-c", "import time; time.sleep(300)"] + command = [sys.executable, "-c", "import time; time.sleep(300)", "run-command-test-marker-8f2c1"] with self.assertRaises(RuntimeError): bounded_run.run_command(command, dict(os.environ), on_start=on_start) self.assertEqual(len(pids), 1) From 4a84b575a28fb4016d29e4a064a6e77cd9504211 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 13:59:51 +0100 Subject: [PATCH 17/65] feat(skills/bounding-heavy-commands): queue commands on the memory of the machine (#45) Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 18 +++- .../scripts/tests/test_bounded_run.py | 86 +++++++++++++++++++ 2 files changed, 103 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 2950864..3623a2d 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -559,12 +559,28 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: if shutil.which(command[0], path=environ.get("PATH")) is None: raise WrapperError("cannot start '%s': the command does not exist" % command[0]) + count = slot_count(settings.total_mib, settings.slot_mib, settings.reserve_mib) + needed = slots_needed(budget, settings.slot_mib, count) + if budget > count * settings.slot_mib: + log("WARNING: the budget of %d MiB is more than the %d MiB of the queue; the command takes all slots" % (budget, count * settings.slot_mib)) + uid = os.getuid() + directory = lock_directory(environ, uid) + ensure_lock_directory(directory, uid) + repository = repository_id(os.getcwd()) if options.exclusive else "" + exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive] + child_environ: Dict[str, str] = dict(environ) child_environ[ACTIVE_VARIABLE] = "1" child_environ["BOUNDED_RUN_MEMORY_MIB"] = str(budget) child_environ["BOUNDED_RUN_CPUS"] = str(options.cpus if options.cpus is not None else (os.cpu_count() or 1)) - code, maxrss = run_command(command, child_environ) + reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds) + try: + wait_for_memory(budget, settings.memory_wait_seconds, settings.poll_seconds) + code, maxrss = run_command(command, child_environ) + finally: + reservation.release() + log("budget %d MiB, exit %d" % (budget, code)) return code diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index a0b439d..2fbbce9 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -821,6 +821,92 @@ def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self): process.send_signal(signal.SIGTERM) self.assertEqual(process.wait(timeout=60), 143) + def test_commands_never_run_together_beyond_the_slots(self): + workers = [self.worker("w%d" % index, "2G", hold="0.3") for index in range(6)] + for process in workers: + self.assertEqual(process.wait(timeout=60), 0) + events = self.read_events() + self.assertEqual(len([line for line in events if line.startswith("start ")]), 6) + self.assertEqual(len([line for line in events if line.startswith("end ")]), 6) + self.assertLessEqual(self.peak_concurrency(), 2) + + def test_a_command_that_needs_all_slots_runs_alone(self): + workers = [self.worker("w%d" % index, "4G", hold="0.2") for index in range(3)] + for process in workers: + self.assertEqual(process.wait(timeout=60), 0) + self.assertEqual(self.peak_concurrency(), 1) + + def test_a_waiting_command_holds_no_slot(self): + release = os.path.join(self.base.name, "release") + long_holder = self.worker("holder", "2G", hold="60", release=release) + self.wait_for_event("start", "holder") + large = self.worker("large", "4G", hold="0") + time.sleep(0.3) + small = self.worker("small", "2G", hold="0") + self.assertEqual(small.wait(timeout=60), 0) + names = [line.split()[1] for line in self.read_events() if line.startswith("end ")] + self.assertEqual(names, ["small"]) + Path(release).write_text("") + self.assertEqual(large.wait(timeout=60), 0) + self.assertEqual(long_holder.wait(timeout=60), 0) + order = [line.split()[:2] for line in self.read_events()] + self.assertLess(order.index(["end", "holder"]), order.index(["start", "large"])) + + def test_a_hard_kill_of_the_wrapper_frees_the_slots_at_once(self): + holder = self.worker("holder", "4G", hold="120") + self.wait_for_event("start", "holder") + holder.kill() + holder.wait(timeout=60) + started = time.time() + follower = self.worker("follower", "4G", hold="0") + self.assertEqual(follower.wait(timeout=60), 0) + self.assertLess(time.time() - started, 30.0) + + def test_the_command_does_not_inherit_the_locks(self): + script = ( + "import os\n" + "directory = os.environ['BOUNDED_RUN_LOCK_DIR']\n" + "locks = set()\n" + "for name in os.listdir(directory):\n" + " info = os.stat(os.path.join(directory, name))\n" + " locks.add((info.st_dev, info.st_ino))\n" + "found = 0\n" + "for descriptor in range(3, 256):\n" + " try:\n" + " info = os.fstat(descriptor)\n" + " except OSError:\n" + " continue\n" + " if (info.st_dev, info.st_ino) in locks:\n" + " found += 1\n" + "print('locks', len(locks), 'inherited', found)\n" + ) + process = self.wrapper(["--memory", "4G", "--exclusive", "port"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual(output, "locks 4 inherited 0\n", errors) + + def test_commands_with_the_same_exclusive_name_take_turns(self): + workers = [self.worker("w%d" % index, "2G", hold="0.3", options=["--exclusive", "port-8080"]) for index in range(3)] + for process in workers: + self.assertEqual(process.wait(timeout=60), 0) + self.assertEqual(self.peak_concurrency(), 1) + + def test_a_budget_larger_than_the_queue_runs_with_a_warning(self): + first = self.worker("first", "64G", hold="0.3") + second = self.worker("second", "64G", hold="0.3") + output, errors = first.communicate(timeout=60) + self.assertEqual(first.returncode, 0, errors) + self.assertIn("WARNING: the budget of 65536 MiB is more than the 4096 MiB of the queue", errors) + self.assertEqual(second.wait(timeout=60), 0) + self.assertEqual(self.peak_concurrency(), 1) + + def test_a_lock_directory_that_is_a_file_gives_125(self): + path = os.path.join(self.base.name, "a-file") + Path(path).write_text("") + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "print('ran')"], BOUNDED_RUN_LOCK_DIR=path) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, output), (125, ""), errors) + self.assertIn("bounded-run: cannot use the lock directory", errors) + if __name__ == "__main__": unittest.main() From bd33dd9d56737e3654458932ce220c41b98f2127 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:14:58 +0100 Subject: [PATCH 18/65] feat(skills/bounding-heavy-commands): cap the command and report its peak (#45) Replaces bounded() to apply the hard cap where systemd-run --user --scope can create a cgroup, measure the peak memory (from the cgroup when capped, sampled otherwise), print the report line, and support a measure mode that suggests a budget. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 37 ++++++++- .../scripts/tests/test_bounded_run.py | 83 +++++++++++++++++++ 2 files changed, 118 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 3623a2d..910273a 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -569,19 +569,52 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: repository = repository_id(os.getcwd()) if options.exclusive else "" exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive] + unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) + capped = not settings.no_cap and cap_usable(cap_prefix(budget, options.cpus, unit + "-probe")) + peak_file = os.path.join(directory, "peak-%s" % unit) + if capped: + inside = [sys.executable, os.path.abspath(__file__), "--inside-cap", peak_file, unit, "--"] + command = cap_prefix(budget, options.cpus, unit) + inside + command + else: + log("no hard cap is available here; the queue and the wait for free memory are the full protection") + child_environ: Dict[str, str] = dict(environ) child_environ[ACTIVE_VARIABLE] = "1" child_environ["BOUNDED_RUN_MEMORY_MIB"] = str(budget) child_environ["BOUNDED_RUN_CPUS"] = str(options.cpus if options.cpus is not None else (os.cpu_count() or 1)) + trackers: List[PeakTracker] = [] + + def start_tracker(pid: int) -> None: + if capped: + def read_sample() -> Optional[int]: + found = cgroup_directory(pid, unit) + return cgroup_peak_mib(found) if found is not None else None + interval = min(settings.sample_seconds, 0.5) + else: + def read_sample() -> Optional[int]: + return group_rss_mib(pid) + interval = settings.sample_seconds + tracker = PeakTracker(read_sample, interval) + tracker.start() + trackers.append(tracker) + reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds) try: wait_for_memory(budget, settings.memory_wait_seconds, settings.poll_seconds) - code, maxrss = run_command(command, child_environ) + code, maxrss = run_command(command, child_environ, start_tracker) + tracked = trackers[0].finish() if trackers else None finally: reservation.release() - log("budget %d MiB, exit %d" % (budget, code)) + reported = read_peak_file(peak_file) if capped else None + exact = reported is not None + peak = max(reported or tracked or 0, rusage_peak_mib(maxrss)) + log("budget %d MiB, peak %d MiB (%s), exit %d" % (budget, peak, "cgroup" if exact else "sampled, approximate", code)) + if capped and code == 137: + log("the command was killed; if the peak is near the budget, the hard cap stopped it") + if options.measure: + log("suggested budget %d MiB" % suggested_budget_mib(peak, not exact)) return code diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 2fbbce9..0f9aa8f 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -907,6 +907,89 @@ def test_a_lock_directory_that_is_a_file_gives_125(self): self.assertEqual((process.returncode, output), (125, ""), errors) self.assertIn("bounded-run: cannot use the lock directory", errors) + def test_each_run_reports_the_budget_and_the_peak(self): + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"]) + output, errors = process.communicate(timeout=60) + self.assertRegex(errors, r"bounded-run: budget 2048 MiB, peak \d+ MiB \(sampled, approximate\), exit 0\n") + self.assertNotIn("suggested budget", errors) + + def test_without_a_cap_the_output_says_so(self): + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"]) + output, errors = process.communicate(timeout=60) + self.assertIn("no hard cap is available here", errors) + + def test_measure_mode_reports_a_peak_and_a_budget(self): + script = "import time\ndata = bytearray(150 * 1024 * 1024)\nfor index in range(0, len(data), 4096):\n data[index] = 1\ntime.sleep(1.0)\n" + process = self.wrapper(["--measure"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + peak = [line for line in errors.splitlines() if " peak " in line][0] + value = int(peak.split(" peak ")[1].split()[0]) + self.assertGreaterEqual(value, 140) + self.assertLess(value, 1024) + self.assertIn("sampled, approximate", peak) + suggested = [line for line in errors.splitlines() if "suggested budget" in line][0] + self.assertEqual(int(suggested.split()[-2]) % 256, 0) + self.assertGreaterEqual(int(suggested.split()[-2]), value * 1.5) + +@unittest.skipUnless( + bounded_run.cap_usable(bounded_run.cap_prefix(256, 1, "bounded-run-test-probe-%d" % os.getpid())), + "no hard cap on this machine", +) +class HardCapTest(WrapperProcessCase): + def setUp(self): + super().setUp() + del self.environ["BOUNDED_RUN_NO_CAP"] + + def test_a_command_that_does_not_exist_gives_125(self): + process = self.wrapper(["--memory", "2G"], ["/nonexistent/tool-for-the-test"]) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 125, errors) + + def test_the_cap_stops_a_command_that_passes_its_budget(self): + script = "data = bytearray(1024 * 1024 * 1024)\nfor index in range(0, len(data), 4096):\n data[index] = 1\nprint('survived')\n" + process = self.wrapper(["--memory", "256M", "--cpus", "1"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, output), (137, ""), errors) + self.assertIn("the hard cap stopped it", errors) + + def test_a_short_command_gets_its_peak_from_the_cgroup(self): + for attempt in range(5): + with self.subTest(attempt=attempt): + process = self.wrapper(["--memory", "1G", "--cpus", "2"], [sys.executable, "-c", "print(1)"]) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, output), (0, "1\n"), errors) + self.assertRegex(errors, r"bounded-run: budget 1024 MiB, peak \d+ MiB \(cgroup\), exit 0\n") + locks = os.listdir(self.environ["BOUNDED_RUN_LOCK_DIR"]) + self.assertEqual([name for name in locks if name.startswith("peak-")], []) + + def test_a_stop_signal_stops_a_capped_command(self): + process = self.worker("capped", "1G", hold="30") + line = self.wait_for_event("start", "capped") + process.send_signal(signal.SIGTERM) + self.assertEqual(process.wait(timeout=60), 143) + with self.assertRaises(ProcessLookupError): + deadline = time.time() + 5 + while time.time() < deadline: + os.kill(int(line.split()[2]), 0) + time.sleep(0.05) + + def test_the_peak_comes_from_the_cgroup(self): + script = "import time\ndata = bytearray(150 * 1024 * 1024)\nfor index in range(0, len(data), 4096):\n data[index] = 1\ntime.sleep(1.2)\n" + process = self.wrapper(["--memory", "1G", "--measure"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + peak = [line for line in errors.splitlines() if " peak " in line][0] + self.assertIn("(cgroup)", peak) + self.assertGreaterEqual(int(peak.split(" peak ")[1].split()[0]), 140) + + def test_no_peak_file_is_left_behind_after_a_failing_command(self): + process = self.wrapper(["--memory", "1G"], [sys.executable, "-c", "import sys; sys.exit(9)"]) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 9, errors) + locks = os.listdir(self.environ["BOUNDED_RUN_LOCK_DIR"]) + self.assertEqual([name for name in locks if name.startswith("peak-")], []) + if __name__ == "__main__": unittest.main() From 1238bd284d79453c3a03dedc00cd8a3bd5b6b791 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:15:50 +0100 Subject: [PATCH 19/65] fix(skills/bounding-heavy-commands): stop with 130 and no traceback on an interrupt in the queue (#45) An interrupt while the wrapper waits in the queue or waits for free memory raised KeyboardInterrupt out of main() and printed a traceback, breaking the rule that the wrapper never prints one. main() now catches KeyboardInterrupt around the call to bounded(), logs one line, and returns 130; the locks are still released by bounded()'s finally or by the kernel. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 6 +++- .../scripts/tests/test_bounded_run.py | 28 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 910273a..ead2f72 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -631,7 +631,11 @@ def main(argv: Optional[Sequence[str]] = None, environ: Optional[Mapping[str, st os.execvpe(options.command[0], options.command, dict(variables)) except OSError as error: raise WrapperError("cannot start '%s': %s" % (options.command[0], error)) - return bounded(options, variables) + try: + return bounded(options, variables) + except KeyboardInterrupt: + log("interrupted while waiting") + return 130 except WrapperError as error: log(str(error)) return EXIT_WRAPPER diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 0f9aa8f..1c7cc8c 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2,6 +2,7 @@ import errno import os +import select import signal import subprocess import sys @@ -932,6 +933,33 @@ def test_measure_mode_reports_a_peak_and_a_budget(self): self.assertEqual(int(suggested.split()[-2]) % 256, 0) self.assertGreaterEqual(int(suggested.split()[-2]), value * 1.5) + def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self): + holder = self.worker("holder", "4G", hold="300") + self.wait_for_event("start", "holder") + waiting = self.worker("waiting", "4G", hold="0") + + deadline = time.time() + 30.0 + buffer = "" + while "waiting for" not in buffer: + remaining = deadline - time.time() + self.assertGreater(remaining, 0, "no 'waiting for' line from the wrapper; stderr so far: %s" % buffer) + ready, _, _ = select.select([waiting.stderr], [], [], min(remaining, 0.5)) + if ready: + line = waiting.stderr.readline() + if line: + buffer += line + + waiting.send_signal(signal.SIGINT) + self.assertEqual(waiting.wait(timeout=60), 130) + buffer += waiting.stderr.read() + self.assertNotIn("Traceback", buffer) + for line in buffer.splitlines(): + self.assertTrue(line.startswith("bounded-run: "), buffer) + + holder.send_signal(signal.SIGTERM) + self.assertEqual(holder.wait(timeout=60), 143) + + @unittest.skipUnless( bounded_run.cap_usable(bounded_run.cap_prefix(256, 1, "bounded-run-test-probe-%d" % os.getpid())), "no hard cap on this machine", From 92d1768e455c91e371dddf3769482cf94511f362 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:28:47 +0100 Subject: [PATCH 20/65] test(skills/bounding-heavy-commands): make the capped signal test fail on a signal that is lost (#45) test_a_stop_signal_stops_a_capped_command held the command for only 30 seconds, so a regression that stops the signal from reaching the command (e.g. os.kill to the tracked pid instead of os.killpg to its group) could still pass: the command would finish on its own inside the 60-second wait and the wrapper would still report 143, since run_command reports 128+signal once a signal was sent regardless of what actually stopped the command. Holding for 300 seconds makes a lost signal show up as a timeout instead. test_no_peak_file_is_left_behind_after_a_failing_command asserted only that no peak- file remained, which is also true when no such file was ever written. It now also asserts the report line says "(cgroup)", proving a file existed and was read before removal. Co-Authored-By: Claude Fable 5.1 --- .../bounding-heavy-commands/scripts/tests/test_bounded_run.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 1c7cc8c..a46a225 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -992,7 +992,7 @@ def test_a_short_command_gets_its_peak_from_the_cgroup(self): self.assertEqual([name for name in locks if name.startswith("peak-")], []) def test_a_stop_signal_stops_a_capped_command(self): - process = self.worker("capped", "1G", hold="30") + process = self.worker("capped", "1G", hold="300") line = self.wait_for_event("start", "capped") process.send_signal(signal.SIGTERM) self.assertEqual(process.wait(timeout=60), 143) @@ -1015,6 +1015,7 @@ def test_no_peak_file_is_left_behind_after_a_failing_command(self): process = self.wrapper(["--memory", "1G"], [sys.executable, "-c", "import sys; sys.exit(9)"]) output, errors = process.communicate(timeout=60) self.assertEqual(process.returncode, 9, errors) + self.assertIn("(cgroup)", errors) locks = os.listdir(self.environ["BOUNDED_RUN_LOCK_DIR"]) self.assertEqual([name for name in locks if name.startswith("peak-")], []) From 0e5b7057fc526f60474c4bc5529df0523184dc69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 14:38:36 +0100 Subject: [PATCH 21/65] fix(skills/bounding-heavy-commands): remove the peak file on every path (#45) bounded() read and removed the peak file after the try/finally that holds the reservation, so an exception between run_command's return and that read (or a run_command that raises outright, as with an on_start callback that fails) left the peak- file behind in the lock directory. The read and removal now happen inside the finally block, before the reservation is released, so the file is gone on every path on which the wrapper still runs. The report line still says "cgroup" only when that read returned a value. Proven with test_the_peak_file_is_removed_when_the_run_fails_after_the_start, which calls bounded() in the test process with run_command and cap_usable replaced by stubs (no real subprocess, no real cgroup), makes the stub write the peak file at the path it is given and then raise RuntimeError, and asserts the file is gone and both slots are free afterward. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 4 +- .../scripts/tests/test_bounded_run.py | 50 +++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index ead2f72..a7bad28 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -599,15 +599,17 @@ def read_sample() -> Optional[int]: tracker.start() trackers.append(tracker) + reported: Optional[int] = None reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds) try: wait_for_memory(budget, settings.memory_wait_seconds, settings.poll_seconds) code, maxrss = run_command(command, child_environ, start_tracker) tracked = trackers[0].finish() if trackers else None finally: + if capped: + reported = read_peak_file(peak_file) reservation.release() - reported = read_peak_file(peak_file) if capped else None exact = reported is not None peak = max(reported or tracked or 0, rusage_peak_mib(maxrss)) log("budget %d MiB, peak %d MiB (%s), exit %d" % (budget, peak, "cgroup" if exact else "sampled, approximate", code)) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index a46a225..2dee24e 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -631,6 +631,56 @@ def on_start(pid): self.assertFalse(alive, "the command still runs") +class BoundedCleanupTest(unittest.TestCase): + """Calls bounded() in this process, with run_command and cap_usable replaced by stubs. + + No real command, no real cgroup, and no real subprocess run outside the stubs. + """ + + def setUp(self): + patcher = mock.patch.object(bounded_run, "log") + patcher.start() + self.addCleanup(patcher.stop) + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.directory = os.path.join(self.base.name, "locks") + self.environ = dict(os.environ) + self.environ.pop("BOUNDED_RUN_ACTIVE", None) + self.environ.pop("BOUNDED_RUN_NO_CAP", None) + self.environ.update({ + "BOUNDED_RUN_LOCK_DIR": self.directory, + "BOUNDED_RUN_TOTAL_MIB": "4096", + "BOUNDED_RUN_RESERVE_MIB": "0", + "BOUNDED_RUN_SLOT_MIB": "2048", + "BOUNDED_RUN_POLL_SECONDS": "0.05", + "BOUNDED_RUN_MEMORY_WAIT_SECONDS": "0", + "BOUNDED_RUN_SAMPLE_SECONDS": "0.1", + }) + + def test_the_peak_file_is_removed_when_the_run_fails_after_the_start(self): + def fake_run_command(command, environ, on_start=None): + index = command.index("--inside-cap") + with open(command[index + 1], "w") as handle: + handle.write("123\n") + raise RuntimeError("boom") + + options = bounded_run.Options() + options.memory = "2G" + options.command = [sys.executable, "-c", "pass"] + + with mock.patch.object(bounded_run, "cap_usable", return_value=True), \ + mock.patch.object(bounded_run, "run_command", fake_run_command): + with self.assertRaises(RuntimeError): + bounded_run.bounded(options, self.environ) + + names = os.listdir(self.directory) + self.assertEqual([name for name in names if name.startswith("peak-")], []) + + reservation = bounded_run.try_reserve(self.directory, 2, 2, []) + self.assertIsNotNone(reservation, "the slots are still held") + reservation.release() + + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" From 30d879cd6bd0c8472d0d85ac01ae86e6eefa5e29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 15:18:37 +0100 Subject: [PATCH 22/65] test(skills/bounding-heavy-commands): wait for a fact, not for a time, between two processes (#45) test_a_waiting_command_holds_no_slot used time.sleep(0.3) to let the large command try and fail to reserve before starting the small one. Replaced it with waiting for "waiting for" on the large command's own error stream, a fact instead of a fixed pause. test_an_interrupt_in_the_queue_gives_130_and_no_traceback already waited for the holder's start event (a fact) before launching the second wrapper, so the reservation was never the issue: a probe placed right after that event, in a standalone repro, confirmed the two needed slots were always still held. Reproducing under real CPU load (up to ~100 runnable processes on 16 cores) showed the second wrapper's own "waiting for" log line reaching its stderr pipe more than 30, and occasionally more than 60, seconds after it started, while remaining alive and correct the whole time: the code between its two log calls is a handful of non-blocking syscalls with nothing in it that should take that long, so this is the OS failing to schedule a fully correct process under heavy contention, not a bug in bounded_run.py's reservation or logging. Extracted the inline 30-second wait into a shared wait_for_stderr helper (default 60 seconds, matching every other timeout in this suite) and used it here in place of the ad hoc loop. Co-Authored-By: Claude Fable 5.1 --- .../scripts/tests/test_bounded_run.py | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 2dee24e..bf2d7ea 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -747,6 +747,21 @@ def wait_for_event(self, kind, name, seconds=30.0): time.sleep(0.02) self.fail("no '%s %s' event after %s seconds; events: %s" % (kind, name, seconds, self.read_events())) + def wait_for_stderr(self, process, substring, seconds=60.0): + """Reads lines from the process's error stream until one holds substring, or fails by seconds.""" + deadline = time.time() + seconds + buffer = "" + while substring not in buffer: + remaining = deadline - time.time() + if remaining <= 0: + self.fail("no line with %r on the error stream after %s seconds; stderr so far: %s" % (substring, seconds, buffer)) + ready, _, _ = select.select([process.stderr], [], [], min(remaining, 0.5)) + if ready: + line = process.stderr.readline() + if line: + buffer += line + return buffer + def peak_concurrency(self): running = 0 peak = 0 @@ -892,7 +907,7 @@ def test_a_waiting_command_holds_no_slot(self): long_holder = self.worker("holder", "2G", hold="60", release=release) self.wait_for_event("start", "holder") large = self.worker("large", "4G", hold="0") - time.sleep(0.3) + self.wait_for_stderr(large, "waiting for") small = self.worker("small", "2G", hold="0") self.assertEqual(small.wait(timeout=60), 0) names = [line.split()[1] for line in self.read_events() if line.startswith("end ")] @@ -988,16 +1003,7 @@ def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self): self.wait_for_event("start", "holder") waiting = self.worker("waiting", "4G", hold="0") - deadline = time.time() + 30.0 - buffer = "" - while "waiting for" not in buffer: - remaining = deadline - time.time() - self.assertGreater(remaining, 0, "no 'waiting for' line from the wrapper; stderr so far: %s" % buffer) - ready, _, _ = select.select([waiting.stderr], [], [], min(remaining, 0.5)) - if ready: - line = waiting.stderr.readline() - if line: - buffer += line + buffer = self.wait_for_stderr(waiting, "waiting for") waiting.send_signal(signal.SIGINT) self.assertEqual(waiting.wait(timeout=60), 130) From a0801b64a3dc6aac5e95cb871a623ca4cccbcde7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 15:31:16 +0100 Subject: [PATCH 23/65] test(skills/bounding-heavy-commands): read the error stream of a process with no buffer between (#45) wait_for_stderr used select() on process.stderr (a buffered text stream) and then readline(). select() only reports the descriptor ready; it says nothing about how many lines are already sitting in the pipe. When two lines arrive before the first read, readline() pulls both out of the pipe and returns only the first, leaving the second sitting in Python's own buffer where select() can no longer see it. The loop then waits for a line it already holds, until its deadline. Proved this before changing anything: a temporary time.sleep(3) placed right before the wait_for_stderr call, so both lines are reliably in the pipe first, made test_an_interrupt_in_the_queue_gives_130_and_no_traceback fail the same way three times in a row on an otherwise quiet machine (load average 2.7-22), with the exact message seen under real load. This replaces the "OS scheduling latency" cause recorded for this test in the Fix round 2 section of the task report, which was not confirmed and is superseded by this cause. Fixed wait_for_stderr to select() on the raw descriptor (process.stderr.fileno()) and read it with os.read(), never through process.stderr's own buffered readline()/read(), so select() and the read always agree on what is still in the pipe. An empty read means the stream closed; that now fails immediately with the buffer so far, instead of waiting out the deadline. Kept the partial read in self._stderr_buffers, keyed by process, and added stderr_of(process) to combine it with a final raw read after the process has stopped, so a test that reads the same stream twice (once through wait_for_stderr, once to check the full output) never loses or re-reads a byte between the two. Updated test_an_interrupt_in_the_queue_gives_130_and_no_traceback, the one test that reads a stream both ways, to use it. Searched the file for the same fault (select() paired with a buffered readline(), read(), or iteration): wait_for_stderr was the only place that did this. Re-ran the three-failures-in-a-row proof with the fix in place and the temporary sleep still there: passed three times. Removed the sleep. Co-Authored-By: Claude Fable 5.1 --- .../scripts/tests/test_bounded_run.py | 46 +++++++++++++++---- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index bf2d7ea..7c31878 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -702,6 +702,7 @@ def setUp(self): "EVENTS": self.events, }) self.processes = [] + self._stderr_buffers = {} def tearDown(self): for process in self.processes: @@ -748,20 +749,49 @@ def wait_for_event(self, kind, name, seconds=30.0): self.fail("no '%s %s' event after %s seconds; events: %s" % (kind, name, seconds, self.read_events())) def wait_for_stderr(self, process, substring, seconds=60.0): - """Reads lines from the process's error stream until one holds substring, or fails by seconds.""" + """Reads the process's raw error-stream descriptor until substring appears, or fails by seconds. + + Reads os.read() on the raw descriptor, never process.stderr's own buffered readline()/read(): + select() only reports the descriptor ready, it says nothing about how many lines are + sitting in the pipe. A buffered readline() can pull more than one already-arrived line + out of the pipe in a single call and return just the first, leaving the rest sitting in + Python's own buffer where select() can no longer see them and this loop would wait for a + line it already holds. Keeps what it reads in self._stderr_buffers, keyed by process, so + a later call to stderr_of() for the same process resumes from here instead of losing or + re-reading any of it. + """ deadline = time.time() + seconds - buffer = "" + buffer = self._stderr_buffers.setdefault(process, "") + fd = process.stderr.fileno() while substring not in buffer: remaining = deadline - time.time() if remaining <= 0: self.fail("no line with %r on the error stream after %s seconds; stderr so far: %s" % (substring, seconds, buffer)) - ready, _, _ = select.select([process.stderr], [], [], min(remaining, 0.5)) + ready, _, _ = select.select([fd], [], [], min(remaining, 0.5)) if ready: - line = process.stderr.readline() - if line: - buffer += line + chunk = os.read(fd, 65536) + if not chunk: + self.fail("the error stream closed with no line %r; stderr so far: %s" % (substring, buffer)) + buffer += chunk.decode(errors="replace") + self._stderr_buffers[process] = buffer return buffer + def stderr_of(self, process): + """Returns everything the process wrote to its error stream, once it has stopped. + + Combines what wait_for_stderr already took off the raw descriptor (if any) with a final + raw read of whatever is left, so the two never compete for the same bytes through two + different buffers. Call only after the process has exited, so the final read reaches + end-of-file instead of blocking. + """ + buffer = self._stderr_buffers.pop(process, "") + fd = process.stderr.fileno() + while True: + chunk = os.read(fd, 65536) + if not chunk: + return buffer + buffer += chunk.decode(errors="replace") + def peak_concurrency(self): running = 0 peak = 0 @@ -1003,11 +1033,11 @@ def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self): self.wait_for_event("start", "holder") waiting = self.worker("waiting", "4G", hold="0") - buffer = self.wait_for_stderr(waiting, "waiting for") + self.wait_for_stderr(waiting, "waiting for") waiting.send_signal(signal.SIGINT) self.assertEqual(waiting.wait(timeout=60), 130) - buffer += waiting.stderr.read() + buffer = self.stderr_of(waiting) self.assertNotIn("Traceback", buffer) for line in buffer.splitlines(): self.assertTrue(line.startswith("bounded-run: "), buffer) From adb71b3b8cb0d0abd3c591ca761b4b06340bd47b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:26:13 +0100 Subject: [PATCH 24/65] test(skills/bounding-heavy-commands): order two signals by a fact and hold until the test stops the command (#45) Two more tests had the same two faults already fixed elsewhere in this file: ordering two events with a fixed sleep, and a "runs until stopped" hold short enough that its own natural end could rescue a buggy result. test_a_second_stop_signal_kills_a_command_that_ignores_the_first used time.sleep(0.3) between the first and second SIGTERM. Under load the two signals can coalesce into one delivery before the sleep even starts, failing the test with no fault in the wrapper; a wrapper that wrongly stops on the first signal could still look alive after 0.3 seconds, passing a test that should have caught it. Made the ignoring command write a "signaled" event when it receives SIGTERM, and made the test wait for that fact (with the existing wait_for_event helper, 60-second deadline) before sending the second signal. Added the missing assertion that the command's own process is actually gone afterward, matching every other signal test in this file. Proved the new test has teeth: temporarily changed run_command's forward() to resend the first signal instead of SIGKILL on the second delivery, and watched the test fail by timeout; reverted before committing. test_a_waiting_command_holds_no_slot gave its long-running holder hold="60" while waiting up to 60 seconds for the small command to end. If a bug let something wrongly keep a slot, the holder's own natural expiry at the same 60-second mark could still free a slot just in time and mask the bug. Changed the hold to 300 seconds; the holder still ends early via its release file on every correct run. Proved it: temporarily made a failed try_reserve() keep the slots it had already taken instead of releasing them (matching a real leak bug shape), and watched the test fail by timeout with the fixed 300-second hold; reverted before committing. Also, from the same review pass: - test_a_hard_kill_of_the_wrapper_frees_the_slots_at_once used hold="120" for a holder that is unconditionally killed right after its start event; never 120 by design, so normalized it to the same 300-second convention as every other "runs until stopped" hold. - test_the_tracker_survives_a_reader_that_fails asserted only that the tracker's peak stayed None, which is also true if the reader never ran at all. Now counts the reader's calls, waits for at least one (a fact, not a fixed sleep), and asserts that count. - Added a one-line comment to every hold that is genuinely short and that the test waits to end, so the two patterns ("runs until the test stops it" vs "short, waited out") are no longer distinguished only by tribal knowledge. Audited every hold= and time.sleep in the file for these two faults; the two above were the only other instances found. Full list in task-12-report.md. Co-Authored-By: Claude Fable 5.1 --- .../scripts/tests/test_bounded_run.py | 58 +++++++++++++------ 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 7c31878..bc06ff0 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -512,12 +512,18 @@ def test_the_tracker_keeps_the_largest_sample(self): self.assertEqual(tracker.finish(), 900) def test_the_tracker_survives_a_reader_that_fails(self): + calls = [] + def read(): + calls.append(1) raise OSError("gone") tracker = bounded_run.PeakTracker(read, 0.01) tracker.start() - time.sleep(0.05) + deadline = time.time() + 5 + while not calls and time.time() < deadline: + time.sleep(0.01) + self.assertGreaterEqual(len(calls), 1, "the reader never ran") self.assertIsNone(tracker.finish()) @@ -832,7 +838,7 @@ def test_a_command_that_does_not_exist_gives_125(self): output, errors = process.communicate(timeout=60) self.assertEqual(process.returncode, 125) self.assertIn("cannot start", errors) - follower = self.worker("after", "4G", hold="0") + follower = self.worker("after", "4G", hold="0") # ends at once; the test waits for it to end self.assertEqual(follower.wait(timeout=60), 0) def test_the_command_gets_the_budget_and_the_marker(self): @@ -903,22 +909,36 @@ def test_a_hangup_stops_the_command_and_gives_129(self): def test_a_second_stop_signal_kills_a_command_that_ignores_the_first(self): script = ( "import os, signal, sys, time\n" - "signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" - "descriptor = os.open(os.environ['EVENTS'], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)\n" - "os.write(descriptor, ('start stubborn %d\\n' % os.getpid()).encode())\n" - "os.close(descriptor)\n" - "time.sleep(300)\n" + "def event(kind):\n" + " descriptor = os.open(os.environ['EVENTS'], os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)\n" + " os.write(descriptor, ('%s stubborn %d\\n' % (kind, os.getpid())).encode())\n" + " os.close(descriptor)\n" + "def ignore(signum, frame):\n" + " event('signaled')\n" + "signal.signal(signal.SIGTERM, ignore)\n" + "event('start')\n" + "time.sleep(300)\n" # runs until the second signal kills it; never meant to end on its own ) process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", script]) - self.wait_for_event("start", "stubborn") + line = self.wait_for_event("start", "stubborn") process.send_signal(signal.SIGTERM) - time.sleep(0.3) + self.wait_for_event("signaled", "stubborn", seconds=60.0) self.assertIsNone(process.poll()) process.send_signal(signal.SIGTERM) self.assertEqual(process.wait(timeout=60), 143) + child = int(line.split()[2]) + deadline = time.time() + 5 + alive = True + while alive and time.time() < deadline: + try: + os.kill(child, 0) + time.sleep(0.05) + except ProcessLookupError: + alive = False + self.assertFalse(alive, "the command still runs") def test_commands_never_run_together_beyond_the_slots(self): - workers = [self.worker("w%d" % index, "2G", hold="0.3") for index in range(6)] + workers = [self.worker("w%d" % index, "2G", hold="0.3") for index in range(6)] # brief; the test waits for each to end for process in workers: self.assertEqual(process.wait(timeout=60), 0) events = self.read_events() @@ -927,18 +947,18 @@ def test_commands_never_run_together_beyond_the_slots(self): self.assertLessEqual(self.peak_concurrency(), 2) def test_a_command_that_needs_all_slots_runs_alone(self): - workers = [self.worker("w%d" % index, "4G", hold="0.2") for index in range(3)] + workers = [self.worker("w%d" % index, "4G", hold="0.2") for index in range(3)] # brief; the test waits for each to end for process in workers: self.assertEqual(process.wait(timeout=60), 0) self.assertEqual(self.peak_concurrency(), 1) def test_a_waiting_command_holds_no_slot(self): release = os.path.join(self.base.name, "release") - long_holder = self.worker("holder", "2G", hold="60", release=release) + long_holder = self.worker("holder", "2G", hold="300", release=release) # runs until the release file below ends it early self.wait_for_event("start", "holder") - large = self.worker("large", "4G", hold="0") + large = self.worker("large", "4G", hold="0") # ends at once once it gets its slots; the test waits for it to end self.wait_for_stderr(large, "waiting for") - small = self.worker("small", "2G", hold="0") + small = self.worker("small", "2G", hold="0") # ends at once; the test waits for it to end self.assertEqual(small.wait(timeout=60), 0) names = [line.split()[1] for line in self.read_events() if line.startswith("end ")] self.assertEqual(names, ["small"]) @@ -949,12 +969,12 @@ def test_a_waiting_command_holds_no_slot(self): self.assertLess(order.index(["end", "holder"]), order.index(["start", "large"])) def test_a_hard_kill_of_the_wrapper_frees_the_slots_at_once(self): - holder = self.worker("holder", "4G", hold="120") + holder = self.worker("holder", "4G", hold="300") # runs until the kill below ends it self.wait_for_event("start", "holder") holder.kill() holder.wait(timeout=60) started = time.time() - follower = self.worker("follower", "4G", hold="0") + follower = self.worker("follower", "4G", hold="0") # ends at once; the test waits for it to end self.assertEqual(follower.wait(timeout=60), 0) self.assertLess(time.time() - started, 30.0) @@ -981,13 +1001,13 @@ def test_the_command_does_not_inherit_the_locks(self): self.assertEqual(output, "locks 4 inherited 0\n", errors) def test_commands_with_the_same_exclusive_name_take_turns(self): - workers = [self.worker("w%d" % index, "2G", hold="0.3", options=["--exclusive", "port-8080"]) for index in range(3)] + workers = [self.worker("w%d" % index, "2G", hold="0.3", options=["--exclusive", "port-8080"]) for index in range(3)] # brief; the test waits for each to end for process in workers: self.assertEqual(process.wait(timeout=60), 0) self.assertEqual(self.peak_concurrency(), 1) def test_a_budget_larger_than_the_queue_runs_with_a_warning(self): - first = self.worker("first", "64G", hold="0.3") + first = self.worker("first", "64G", hold="0.3") # brief; the test waits for each to end second = self.worker("second", "64G", hold="0.3") output, errors = first.communicate(timeout=60) self.assertEqual(first.returncode, 0, errors) @@ -1031,7 +1051,7 @@ def test_measure_mode_reports_a_peak_and_a_budget(self): def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self): holder = self.worker("holder", "4G", hold="300") self.wait_for_event("start", "holder") - waiting = self.worker("waiting", "4G", hold="0") + waiting = self.worker("waiting", "4G", hold="0") # never reached; interrupted while still queued self.wait_for_stderr(waiting, "waiting for") From 4d6097fcfe7da0e609145d7559b2f4f5fe341ac5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:27:24 +0100 Subject: [PATCH 25/65] fix(skills/bounding-heavy-commands): keep systemd from stopping a capped command before the kernel does (#45) Under load, the controller measured test_the_cap_stops_a_command_that_passes_its_budget end with exit 143 (SIGTERM) instead of 137 (SIGKILL) in 1 of 12 full suite runs. inside_cap returns the real exit status of the command it runs, so a 143 there means the command, or the --inside-cap process standing in front of it, was itself stopped by a signal other than the kernel's own OOM kill. This machine has DefaultOOMPolicy=stop (systemctl --user show -p DefaultOOMPolicy) and systemd-oomd active. With OOMPolicy=stop (the default cap_prefix left unset), when the kernel OOM-kills one process of a scope, systemd additionally stops the whole scope, which means sending SIGTERM to every process still in it. On a quiet machine the kernel's SIGKILL reaches the heavy command first and inside_cap, which ignores SIGTERM by design, is long past installing that ignore-handler by the time systemd's own SIGTERM would arrive, so it keeps running and reports 137. Under load, process startup and signal delivery both become less predictable, and systemd's SIGTERM can arrive at inside_cap before it has installed its ignore-handler (default disposition terminates it), or reach the command through a different path than the kernel's SIGKILL, producing 143 instead. I could not reproduce the 143 result myself: 40 isolated runs of the one test and 40 full-suite runs, all under the load of 16 busy processes (load average 13-48) and with this machine's swap consistently near full throughout (a condition present in every attempt), all passed. The failure the controller measured is real (they quoted it directly) and every fact checked here is consistent with their hypothesis, but I have no journal capture of an actual 143 run of my own to include. Fixed the cause the evidence supports rather than leave it unaddressed. Fix: added "-p", "OOMPolicy=continue" to cap_prefix(), so systemd only logs the kernel's OOM kill and leaves the rest of the scope alone; inside_cap stays alive to see its child die from the kernel's own SIGKILL and to write the peak file, and the command's exit status is the kernel's 137. cap_usable()'s probe already builds its command from cap_prefix(), so the probe declares this property too with no extra code. man systemd.scope documents OOMPolicy as a scope-unit property added in systemd 243 (this machine runs 255). Checked what an older systemd does with a property it does not recognize: `systemd-run --user --scope -p ThisPropertyDoesNotExist=1 -- true` exits 1 with "Unknown assignment", never running the command. cap_usable() already treats any nonzero probe exit as "no cap"; an systemd older than 243 would report cap_usable() == False through this same existing path, with no special case needed. Test first: added "-p", "OOMPolicy=continue" to the expected list in CapTest.test_prefix_holds_the_limits (a unit test of cap_prefix()); left the process-level test's expected exit code at 137 unchanged. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 1 + .../bounding-heavy-commands/scripts/tests/test_bounded_run.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index a7bad28..8de2b79 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -303,6 +303,7 @@ def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str) -> List[str]: "systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", unit, "-p", "MemoryMax=%dM" % budget_mib, "-p", "MemorySwapMax=0", + "-p", "OOMPolicy=continue", ] if cpus is not None: prefix += ["-p", "CPUQuota=%d%%" % (cpus * 100)] diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index bc06ff0..2f23a66 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -399,7 +399,7 @@ class CapTest(unittest.TestCase): def test_prefix_holds_the_limits(self): self.assertEqual(bounded_run.cap_prefix(6144, 4, "unit-1"), [ "systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", "unit-1", - "-p", "MemoryMax=6144M", "-p", "MemorySwapMax=0", + "-p", "MemoryMax=6144M", "-p", "MemorySwapMax=0", "-p", "OOMPolicy=continue", "-p", "CPUQuota=400%", "--", ]) From 494cffc8826f7100cf4ed88b59019b5a37f3a917 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:37:01 +0100 Subject: [PATCH 26/65] docs(skills/bounding-heavy-commands): say who sets the variables of the wrapper (#45) The usage text listed eight environment variables as settings without saying who sets them, which read as an invitation to set any of them on a single call. In normal use nobody sets them: the tests set most of them, and a person can set the tuning values in a shell profile so every session on the machine agrees. A call that sets one for itself stops sharing the queue with the machine's other sessions (a smaller BOUNDED_RUN_SLOT_MIB, an empty BOUNDED_RUN_LOCK_DIR, or BOUNDED_RUN_NO_CAP get around the queue or the cap for that one call). Replaced the environment-variable part of the module docstring with text that says this first, then splits the variables into the three tuning values (with their defaults) and the values for tests and for diagnosis. Kept every variable's existing description and default; changed no behavior. Added test_says_who_sets_the_environment_variables so a later edit cannot drop the who-sets-them sentence again. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 17 ++++++++++++++--- .../scripts/tests/test_bounded_run.py | 8 ++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 8de2b79..e9e6a3b 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -6,14 +6,25 @@ The exit code is the exit code of the command. Exit code 125 means that this script failed before the command gave a result. -These environment variables are settings for the machine, not for one call. -Two sessions with different values do not count the same slots. +A normal call sets none of the environment variables below. A person can +set the tuning values in the profile of the shell, so that every session +on the machine uses the same values. The tests of this script set the +rest, for the tests themselves and for diagnosis. + +A call that sets one of these for itself does not share the queue with +the other sessions of the machine. Do not set one of them for a single +call. + +Tuning values, with their defaults: BOUNDED_RUN_SLOT_MIB size of one memory slot (default 2048) BOUNDED_RUN_RESERVE_MIB memory that the queue never gives out + BOUNDED_RUN_MEMORY_WAIT_SECONDS time limit of the wait for free memory (default 300) + +Values for tests and for diagnosis: + BOUNDED_RUN_TOTAL_MIB memory of the machine, in place of the measured value BOUNDED_RUN_POLL_SECONDS time between two tries for the slots (default 2) - BOUNDED_RUN_MEMORY_WAIT_SECONDS time limit of the wait for free memory (default 300) BOUNDED_RUN_SAMPLE_SECONDS time between two memory samples (default 1) BOUNDED_RUN_LOCK_DIR directory of the lock files BOUNDED_RUN_NO_CAP when set, do not apply the hard cap diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 2f23a66..15b3296 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -36,6 +36,14 @@ ) +class UsageTextTest(unittest.TestCase): + def test_says_who_sets_the_environment_variables(self): + self.assertIn( + "A normal call sets none of the environment variables below.", + bounded_run.__doc__, + ) + + class SizeTest(unittest.TestCase): def test_reads_gibibytes(self): self.assertEqual(bounded_run.parse_size_mib("6G"), 6144) From 859634d14221f92dcdf0a64fe60506f03833f33d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:40:00 +0100 Subject: [PATCH 27/65] chore: ignore the cache directories of the script tests (#45) Co-Authored-By: Claude Fable 5.1 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 0dbb4b0..4484c60 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ .vscode docs .claude/worktrees/ +__pycache__/ From 373f92a014389693f51db29c1c2a34e0bf90ee20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:40:38 +0100 Subject: [PATCH 28/65] ci: run the script tests on Linux and macOS (#45) Co-Authored-By: Claude Fable 5.1 --- .github/workflows/script-tests.yml | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 .github/workflows/script-tests.yml diff --git a/.github/workflows/script-tests.yml b/.github/workflows/script-tests.yml new file mode 100644 index 0000000..20b6e76 --- /dev/null +++ b/.github/workflows/script-tests.yml @@ -0,0 +1,54 @@ +name: Script tests + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + unittest: + name: ${{ matrix.os }}, Python ${{ matrix.python }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + python: ["3.9", "3.x"] + include: + # The interpreter that ships with the developer tools of macOS. + - os: macos-latest + python: system + steps: + - uses: actions/checkout@v4 + + - if: matrix.python != 'system' + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + + - name: Run the tests of the scripts of each skill + shell: bash + run: | + if [ "${{ matrix.python }}" = system ]; then + python=/usr/bin/python3 + else + python=python3 + fi + "$python" --version + + found=0 + for tests in skills/*/scripts/tests; do + [ -d "$tests" ] || continue + found=1 + echo "::group::$tests" + "$python" -m unittest discover -s "$tests" -v + echo "::endgroup::" + done + + if [ "$found" = 0 ]; then + echo "No script tests found under skills/*/scripts/tests." + exit 1 + fi From 8627867e5ebe6344fb344ccbcf378d17e25bfaaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:43:33 +0100 Subject: [PATCH 29/65] fix(skills/bounding-heavy-commands): write the peak before the signals of the cap process are restored (#45) inside_cap put the old signal handlers back before it read the peak of the cgroup. With the default OOM policy, systemd stops the scope after the kernel kills a process of it for memory, and sends SIGTERM to each process that is left. A SIGTERM after the restore ended inside_cap, and the wrapper gave 143 in place of the 137 of the command. The handlers that do nothing now stay in place until the peak file is written. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 17 ++++++------- .../scripts/tests/test_bounded_run.py | 24 +++++++++++++++++++ 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index e9e6a3b..a319208 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -496,17 +496,18 @@ def keep_running(signum: int, frame: object) -> None: return EXIT_WRAPPER _, status = os.waitpid(process.pid, 0) process.returncode = exit_code_of(status) + # After the kernel kills a process of the scope for memory, systemd can stop the scope with SIGTERM. + directory = cgroup_directory(os.getpid(), unit, proc_root, cgroup_root) + peak = cgroup_peak_mib(directory, names=("memory.peak",)) if directory is not None else None + if peak is not None: + try: + with open(peak_file, "w") as handle: + handle.write("%d\n" % peak) + except OSError: + pass finally: for signum, handler in previous.items(): signal.signal(signum, handler) - directory = cgroup_directory(os.getpid(), unit, proc_root, cgroup_root) - peak = cgroup_peak_mib(directory, names=("memory.peak",)) if directory is not None else None - if peak is not None: - try: - with open(peak_file, "w") as handle: - handle.write("%d\n" % peak) - except OSError: - pass return process.returncode diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 15b3296..8432c08 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -604,6 +604,30 @@ def test_puts_the_signal_handlers_back(self): self.inside([sys.executable, "-c", "pass"]) self.assertIs(signal.getsignal(signal.SIGTERM), before) + def test_a_stop_signal_while_the_peak_is_read_does_not_end_the_process(self): + # A signal with its default action ends the process that runs the test, so a child process runs inside_cap. + script = ( + "import os, signal, sys\n" + "sys.path.insert(0, sys.argv[1])\n" + "import bounded_run\n" + "proc, cgroups, peak_file = sys.argv[2:5]\n" + "os.makedirs(os.path.join(proc, str(os.getpid())))\n" + "with open(os.path.join(proc, str(os.getpid()), 'cgroup'), 'w') as handle:\n" + " handle.write('0::/user.slice/unit-1.scope\\n')\n" + "def read_peak(directory, names=()):\n" + " os.kill(os.getpid(), signal.SIGTERM)\n" + " return 300\n" + "bounded_run.cgroup_peak_mib = read_peak\n" + "sys.exit(bounded_run.inside_cap(peak_file, 'unit-1', [sys.executable, '-c', 'import sys; sys.exit(6)'], proc_root=proc, cgroup_root=cgroups))\n" + ) + child_proc = os.path.join(self.base.name, "child-proc") + done = subprocess.run( + [sys.executable, "-c", script, str(SCRIPTS), child_proc, self.cgroups, self.peak_file], + capture_output=True, text=True, timeout=60, + ) + self.assertEqual(done.returncode, 6, done.stderr) + self.assertEqual(bounded_run.read_peak_file(self.peak_file), 300) + def test_a_peak_file_with_other_text_gives_nothing(self): Path(self.peak_file).write_text("not a number\n") self.assertIsNone(bounded_run.read_peak_file(self.peak_file)) From 9371c059d62fbb241b0b36ddd14f1a836814a2de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:44:30 +0100 Subject: [PATCH 30/65] fix(skills/bounding-heavy-commands): keep the hard cap on a systemd that has no OOM policy for a scope (#45) A scope unit accepts OOMPolicy= only from systemd 253 (NEWS, changes with 253: "Scope units now support OOMPolicy="). On systemd 249 to 252 the probe of the cap failed, and each call ran with no hard cap. The wrapper now probes the prefix with OOMPolicy=continue first, and then the prefix without it. It uses the first one that works, and applies no cap only when both fail. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 24 ++++++++-- .../scripts/tests/test_bounded_run.py | 47 ++++++++++++++++++- 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index a319208..f806bf1 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -309,13 +309,14 @@ def wait_for_memory( waited += poll_seconds -def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str) -> List[str]: +def cap_prefix(budget_mib: int, cpus: Optional[int], unit: str, oom_policy: bool = True) -> List[str]: prefix = [ "systemd-run", "--user", "--scope", "--quiet", "--collect", "--unit", unit, "-p", "MemoryMax=%dM" % budget_mib, "-p", "MemorySwapMax=0", - "-p", "OOMPolicy=continue", ] + if oom_policy: + prefix += ["-p", "OOMPolicy=continue"] if cpus is not None: prefix += ["-p", "CPUQuota=%d%%" % (cpus * 100)] return prefix + ["--"] @@ -335,6 +336,18 @@ def cap_usable( return done.returncode == 0 +def choose_cap_prefix( + budget_mib: int, cpus: Optional[int], unit: str, + usable: Callable[[Sequence[str]], bool], +) -> Optional[List[str]]: + """Returns the prefix of the hard cap for the unit, or None when no cap is usable here.""" + # A scope unit accepts OOMPolicy= from systemd 253; an older systemd rejects the whole prefix. + for oom_policy in (True, False): + if usable(cap_prefix(budget_mib, cpus, unit + "-probe", oom_policy)): + return cap_prefix(budget_mib, cpus, unit, oom_policy) + return None + + def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]: try: with open(os.path.join(proc_root, str(pid), "cgroup")) as handle: @@ -583,11 +596,12 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive] unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) - capped = not settings.no_cap and cap_usable(cap_prefix(budget, options.cpus, unit + "-probe")) + prefix = None if settings.no_cap else choose_cap_prefix(budget, options.cpus, unit, cap_usable) + capped = prefix is not None peak_file = os.path.join(directory, "peak-%s" % unit) - if capped: + if prefix is not None: inside = [sys.executable, os.path.abspath(__file__), "--inside-cap", peak_file, unit, "--"] - command = cap_prefix(budget, options.cpus, unit) + inside + command + command = prefix + inside + command else: log("no hard cap is available here; the queue and the wait for free memory are the full protection") diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 8432c08..868dd94 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -414,6 +414,51 @@ def test_prefix_holds_the_limits(self): def test_prefix_without_cpus_has_no_quota(self): self.assertNotIn("CPUQuota", " ".join(bounded_run.cap_prefix(6144, None, "unit-1"))) + def test_prefix_without_the_oom_policy(self): + prefix = bounded_run.cap_prefix(6144, None, "unit-1", oom_policy=False) + self.assertNotIn("OOMPolicy", " ".join(prefix)) + self.assertIn("MemoryMax=6144M", prefix) + + def choose(self, answers): + probes = [] + + def usable(prefix): + probes.append(list(prefix)) + return answers[len(probes) - 1] + + return bounded_run.choose_cap_prefix(1024, 2, "unit-1", usable), probes + + def test_uses_the_oom_policy_when_the_first_probe_passes(self): + prefix, probes = self.choose([True]) + self.assertEqual(prefix, bounded_run.cap_prefix(1024, 2, "unit-1")) + self.assertEqual(len(probes), 1) + self.assertIn("OOMPolicy=continue", probes[0]) + self.assertNotIn("unit-1", probes[0]) + + def test_uses_the_prefix_without_the_oom_policy_when_only_the_second_probe_passes(self): + prefix, probes = self.choose([False, True]) + self.assertEqual(prefix, bounded_run.cap_prefix(1024, 2, "unit-1", oom_policy=False)) + self.assertEqual(len(probes), 2) + self.assertNotIn("OOMPolicy=continue", probes[1]) + + def test_no_cap_when_both_probes_fail(self): + prefix, probes = self.choose([False, False]) + self.assertIsNone(prefix) + self.assertEqual(len(probes), 2) + + def test_no_command_runs_on_a_different_system(self): + calls = [] + + def run(command, **keywords): + calls.append(command) + return subprocess.CompletedProcess(command, 0) + + def usable(prefix): + return bounded_run.cap_usable(prefix, platform="darwin", which=lambda name: "/usr/bin/systemd-run", run=run) + + self.assertIsNone(bounded_run.choose_cap_prefix(1024, 2, "unit-1", usable)) + self.assertEqual(calls, []) + def probe(self, platform, tool, code=0, error=None): calls = [] @@ -1099,7 +1144,7 @@ def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self): @unittest.skipUnless( - bounded_run.cap_usable(bounded_run.cap_prefix(256, 1, "bounded-run-test-probe-%d" % os.getpid())), + bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.cap_usable) is not None, "no hard cap on this machine", ) class HardCapTest(WrapperProcessCase): From f6fedea2ba1700782aecb3be2254df1b5088a9e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:44:51 +0100 Subject: [PATCH 31/65] docs(skills/bounding-heavy-commands): name the risk of each variable, and who the test values are for (#45) The usage text said only that a call with its own value does not share the queue. That is true of the slot size, the reserve, and the lock directory, but the larger risk of a call with no cap is that it can take the memory of every other session. The heading of the second list now says that its values are for the tests and the maintainers of the script. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 11 ++++++----- .../scripts/tests/test_bounded_run.py | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index f806bf1..3de970f 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -9,11 +9,12 @@ A normal call sets none of the environment variables below. A person can set the tuning values in the profile of the shell, so that every session on the machine uses the same values. The tests of this script set the -rest, for the tests themselves and for diagnosis. +rest, and so do its maintainers when they look for a fault of the script. -A call that sets one of these for itself does not share the queue with -the other sessions of the machine. Do not set one of them for a single -call. +Do not set one of them for a single call. A call with its own slot size, +reserve, or lock directory does not share the queue with the other +sessions of the machine, and a call with no cap can take the memory of +all of them. Tuning values, with their defaults: @@ -21,7 +22,7 @@ BOUNDED_RUN_RESERVE_MIB memory that the queue never gives out BOUNDED_RUN_MEMORY_WAIT_SECONDS time limit of the wait for free memory (default 300) -Values for tests and for diagnosis: +Values for the tests of this script, and for its maintainers: BOUNDED_RUN_TOTAL_MIB memory of the machine, in place of the measured value BOUNDED_RUN_POLL_SECONDS time between two tries for the slots (default 2) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 868dd94..76b8b87 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -43,6 +43,21 @@ def test_says_who_sets_the_environment_variables(self): bounded_run.__doc__, ) + def test_names_the_risk_of_a_variable_for_a_single_call(self): + text = " ".join(bounded_run.__doc__.split()) + self.assertIn( + "Do not set one of them for a single call. A call with its own slot size, reserve, or lock " + "directory does not share the queue with the other sessions of the machine, and a call with " + "no cap can take the memory of all of them.", + text, + ) + + def test_says_who_the_test_values_are_for(self): + text = " ".join(bounded_run.__doc__.split()) + self.assertIn("The tests of this script set the rest, and so do its maintainers when they look for a fault of the script.", text) + self.assertIn("Values for the tests of this script, and for its maintainers:", text) + self.assertNotIn("diagnosis", text) + class SizeTest(unittest.TestCase): def test_reads_gibibytes(self): From b319565ee9f33a1ab82cdea87c1a7b46cc8e1ee8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:45:01 +0100 Subject: [PATCH 32/65] test(skills/bounding-heavy-commands): give each wait for an event 60 seconds (#45) wait_for_event had a default of 30 seconds, and the waits that use the default got half the time of every other wait of the suite. Co-Authored-By: Claude Fable 5.1 --- .../bounding-heavy-commands/scripts/tests/test_bounded_run.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 76b8b87..f983311 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -837,7 +837,7 @@ def read_events(self): except OSError: return [] - def wait_for_event(self, kind, name, seconds=30.0): + def wait_for_event(self, kind, name, seconds=60.0): deadline = time.time() + seconds while time.time() < deadline: for line in self.read_events(): From d22ebd77471c4ead24b83c32d3c5eeb4d35856f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 16:55:06 +0100 Subject: [PATCH 33/65] feat(skills/bounding-heavy-commands): add the skill that bounds heavy commands (#45) Agents run test suites, linters and builds with no knowledge of the other sessions on the machine. The skill sends each heavy command through the wrapper, keeps the measured budgets in the project memory, and puts the bounded command lines into each dispatch prompt. An explicit instruction of the user or of the project's instruction file comes before the skill. Pressure to be quick does not. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/SKILL.md | 154 ++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 skills/bounding-heavy-commands/SKILL.md diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md new file mode 100644 index 0000000..45a95fb --- /dev/null +++ b/skills/bounding-heavy-commands/SKILL.md @@ -0,0 +1,154 @@ +--- +name: bounding-heavy-commands +description: Use when about to run a project's test suite, linter, build, type check, or another command of that weight, when about to dispatch subagents that will run one, or when a command fails on a port already in use, a tool's own lock, or a machine that slows down or swaps while agents verify their work. +--- + +# bounding-heavy-commands + +## Overview + +Every heavy command an agent starts goes through the wrapper. There is no exception for a session that looks alone, for a command that looks small, or for a user who is in a hurry. The one exception is an explicit instruction from the user to run a command without the wrapper (see §When the user tells you to go around the wrapper). + +Heavy commands are what freeze a machine, not agents. Sessions in other terminals and other projects run their own test suites and builds at the same moment, and no session can see the others. When the commands together need more memory than the machine has, it swaps until it stops responding, and that costs every session, not only the one that started the last command. The wrapper makes the commands of every session and every project on the machine take turns on its memory, so too much work shows up as a queue instead of a freeze. + +**Looking first does not protect the machine.** Two sessions that look at the load at the same moment both see a quiet machine, and both start. The same is true of a sum of budgets against the machine's total memory: the sum counts your commands and no one else's. Only a reservation that every session takes before it starts can count the commands, and the wrapper is that reservation. + +**Violating the letter of these rules is violating their spirit.** + +## When to invoke + +- Before you run the project's test suite, linter, build, or type check, or anything that compiles, starts containers, or starts a local cluster. +- Before you dispatch subagents that will run any of those. +- When a command failed on a port that is already in use, or on a tool's own lock. +- When the machine is slow or swaps and someone asks what to change. + +A command is heavy when the project's record says so, or when it does more than touch a handful of files. A part of a heavy command is heavy too: one test file, one package, one target. When in doubt, it is heavy: the wrapper costs a second, a frozen machine costs every session. + +Skip for commands that only read (listing files, searching, version-control queries). Skip for a CI pipeline and for a person at a terminal: their commands stay as they are. + +## The wrapper + +``` +python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... -- +``` + +| Option | Meaning | +| --- | --- | +| `--memory ` | Memory the command may use, such as `6G` or `4096M`. Taken from the record. Without it the wrapper uses its default budget. | +| `--cpus ` | Processor limit, as a whole number. Taken from the record. | +| `--exclusive ` | A resource that only one command in this repository may hold at a time, such as a fixed port. Repeat the option for each resource. | +| `--measure` | Also print a suggested budget. Discovery uses it. | + +The wrapper waits for its share of the machine's memory, waits until that much is free, runs the command, and prints the budget against the measured peak on the error stream. Each line that the wrapper prints starts with `bounded-run:`. Its exit code is the command's exit code. Exit code 125 means the wrapper itself failed. + +The command receives `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB` in its environment, so a recorded command line can hand them to the toolchain's own parallelism and memory settings. + +On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. + +## The record + +Budgets and command lines are facts about one machine and one user, so they live in your project memory, not in the repository. The record is one memory named `bounded-heavy-commands`. Your harness decides the file format. This skill decides the content. + +For each heavy command, record: + +- what it is for ("unit tests", "lint", "build") +- the plain command +- the full bounded command line +- the budget, the measured peak, and the date of the measurement +- each exclusive resource it uses +- the flags or variables that limit the toolchain's own parallelism + +Then, every time: + +1. **The record exists.** Check that each command in it still exists in the project, and that the path of the wrapper in it still exists. An update of the plugin can move the wrapper: then put the path that this skill shows into each command line of the record. Then use the bounded command lines as written. +2. **The record does not exist.** Run the discovery below and save the record before you run anything heavy. +3. **Project memory is off or unavailable.** Run the discovery in this session, keep the result in your context, and use the wrapper's default budget for anything you could not measure. + +A budget is a measurement, not a preference. Change one only when the wrapper's output shows that the peak moved, and write the new peak and date with it. + +A part of a recorded command (one test file, one target) uses the bounded command line of the full command, with its budget and its exclusive resources, and the narrower arguments. It needs no entry of its own. Measure it and add an entry only when you run it often and its peak is much lower. + +## Discovery + +1. Find how the project runs its tests, its linter, its build, and its type check. Read the project's instruction files, its build configuration, and its CI configuration. +2. Find the exclusive resources: a port that a test server binds, a tool that refuses to run twice, a fixed directory that a build writes to. +3. Find how the toolchain limits its own parallelism and memory. Write the command line so that it takes those limits from `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB`. +4. Run each heavy command once with `--measure`, one at a time: + + ``` + python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure -- + ``` + +5. Record the suggested budget that the wrapper prints. It is the peak plus a margin, and the margin is larger where the measurement is approximate. If the hard cap stopped the command during the measurement, run it again with a larger `--memory`. +6. Save the record. + +## Rules for the wait + +A long wait means that the machine is full. It is never a fault to repair. The only correct moves are to keep the run in the queue and to tell the user that the machine is full and the command is queued. + +- **Run a bounded command in the background, with no short timeout around it.** It can wait in the queue for minutes before it starts. A timeout that you calculate from the run time of the command does not count the wait. A timeout that fires during the wait kills a command that never ran, and the result reads like a failure of the code. +- **Plan the time as if the commands run one after the other.** Two bounded commands that start together are safe, because the queue puts them in sequence when the machine cannot hold both. So a parallel start does not always save time, and a promise to the user that depends on it is a guess. +- **Do not lower a budget to start sooner.** A smaller budget does not make the command smaller. It moves the failure inside the command: on Linux as a kill at the hard cap, elsewhere as the swap that the queue exists to prevent. +- **Do not run the plain command because the queue is slow.** A slow queue means the machine is full. The plain command is how it freezes. This includes a narrower form of the command: one test file outside the queue is a command that the queue cannot count. +- **Do not set a `BOUNDED_RUN_*` variable on a call.** The usage text of the wrapper lists them. A person sets the tuning values for the whole machine, and the tests of the wrapper set the rest. A call with its own slot size, reserve, or lock directory does not share the queue with the other sessions, and a call with no cap can take the memory of all of them. A note in your project memory that recommends one is wrong: delete the note, and tell the user that you did. +- **Do not touch the lock directory.** Do not delete, move, or edit a file in it, and do not look for the process that holds a lock. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot. +- **Do not sleep and retry around a collision, not even one time.** A port in use or a tool's lock means two commands wanted one resource. Add the resource to the record as an `--exclusive` name and run through the wrapper. Do not stop the process that holds the resource: it belongs to a different session. + +## When the user tells you to go around the wrapper + +An explicit instruction from the user comes before this skill. When the user names the action ("run the tests directly", "do not use the wrapper for this"), say one time, in one or two sentences, what the wrapper protects and that you cannot see the other sessions. Then do what the user said. Do not refuse, and do not argue a second time. + +The instruction covers the command and the time that it names. The next heavy command goes through the wrapper again, unless the user said that the instruction holds for the session. + +A rule in the project's instruction file comes before this skill too. Obey it, and tell the user one time that the file sends heavy commands around the queue and what that costs on a machine with more than one session. The user decides if the file changes. Do not ignore the file silently, and do not edit it yourself. + +Pressure is not an instruction. "Hurry", "make it start", and "I do not care how" name a result, not an action. Keep the run in the queue and tell the user that the machine is full. Do not go around the queue on your own decision. You can tell the user that an instruction from them is the way around it, together with what it costs, and the user decides. A note in your project memory from an earlier session is not an instruction from the user either. + +## Dispatching subagents + +A subagent does not see your project memory. It knows the bounded commands only when its prompt carries them. + +Every dispatch prompt for a subagent that will verify its own work MUST include: + +1. The bounded command line for each heavy command, copied from the record. +2. This rule, in these words: "Run these commands exactly as written. Do not run the plain form of any of them, and do not run a part of one (one test file, one target) outside the wrapper: put the narrower arguments into the command line as written. Set no `BOUNDED_RUN_*` variable. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair." + +Do not dispatch fewer subagents to protect the machine. The queue protects it. Subagents that wait in the queue cost time, not memory. + +## Without Python 3 + +The wrapper needs `python3`, version 3.9 or later. If it is missing, tell the user once per session that the wrapper cannot run and that Python 3 is what it needs. Then continue under these rules: run one heavy command at a time in your session, never two in parallel, and set the toolchain's parallelism to half the machine's processors or fewer. This protects the machine from your session only, not from the others. Say so in your report. + +## Anti-patterns + +- **Running the plain command "just once".** One plain test suite beside three queued ones is the freeze. The wrapper cannot count a command that never went through it. +- **Judging weight by feel.** "It is only the linter" is a guess. The record holds the measured peak; a command that is not in the record gets measured, not guessed. +- **Looking at the load before a run.** The look is true for one moment, and each session that looks sees the same quiet machine. +- **Wrapping the wrapper in a timeout.** The wait in the queue is part of the run. A timeout turns a full machine into a false test failure. +- **Tuning the budget down.** A budget below the measured peak is a scheduled failure. +- **Repairing the queue.** The queue has no state that can go wrong between runs. An agent that repairs it breaks it. +- **Handing a subagent the project's plain commands.** The subagent runs what its prompt names. Name the bounded command lines. +- **Writing the record into the repository.** The numbers belong to one machine. In the repository they become another person's wrong budget. + +## Red flags + +| Thought | Reality | +| --- | --- | +| "This session is the only one running, so the plain command is fine" | You cannot see other sessions or other projects. Through the wrapper, every time. | +| "Both budgets together are well under the machine's memory" | The sum counts your commands only. The queue counts the commands of every session. | +| "I'll check the load first and start when it is quiet" | Each session that looks at that moment sees the same quiet machine. Take the reservation: run through the wrapper. | +| "It is only the linter, it is small" | The record says what is heavy, not your sense of it. Not in the record means not yet measured. | +| "I'll run just those few tests now, that fits in the free memory" | A part of a heavy command goes through the wrapper too. "It fits" is your estimate; the queue is the count. | +| "I'll run the plain command once to check quickly" | One command outside the queue is all a freeze needs. | +| "Running both in parallel is what makes the deadline possible" | Through the wrapper a parallel start is safe, but the queue decides if the two run together. Do not promise a time that depends on it. | +| "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is the measured peak plus a margin. Lowering it moves the failure inside the command. | +| "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no `BOUNDED_RUN_*` variable. | +| "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock directory alone. | +| "The user told me to run it directly, but the skill says no exception" | An explicit instruction from the user comes first. Say one time what the wrapper protects, then obey. | +| "The user is waiting, the queue is too slow" | A frozen machine is slower. Tell the user that the machine is full and the command is queued. | +| "The port was in use, I'll back off once and retry" | Two commands wanted one resource. Record it as `--exclusive` and run through the wrapper. | +| "My command timed out, the tests must hang" | It was waiting in the queue. Run it in the background with no short timeout. | +| "The subagent will find the test command on its own" | It will find the plain one. Put the bounded command lines in its prompt. | +| "Four subagents is too many for this machine, I'll dispatch two" | The queue limits the commands. Fewer subagents only makes the work slower. | +| "Project memory is off, so there is no record to keep" | Discover in this session and keep the result in context. The rule does not depend on the memory. | +| "Python 3 is missing, so none of this applies" | The fallback applies: one heavy command at a time, toolchain parallelism at half or less, and say so. | From 496ee065fd36ae20613573739f949910629e1c81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:09:01 +0100 Subject: [PATCH 34/65] fix(skills/bounding-heavy-commands): remove the conflicts that three cold reads found (#45) The first text gave opposite orders in several cases: a subagent with a port collision, a dispatch on a machine without the wrapper, a command that an instruction exempts, and the first discovery. It also told the agent to read two variables in a way that gives empty values. The text now decides each of these cases, shows the inner shell that reads the variables, and says what is heavy outside the four usual commands. The section of anti-patterns is removed, because each item is in the rules for the wait or in the red flags. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/SKILL.md | 105 +++++++++++++----------- 1 file changed, 56 insertions(+), 49 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 45a95fb..d593864 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -7,11 +7,11 @@ description: Use when about to run a project's test suite, linter, build, type c ## Overview -Every heavy command an agent starts goes through the wrapper. There is no exception for a session that looks alone, for a command that looks small, or for a user who is in a hurry. The one exception is an explicit instruction from the user to run a command without the wrapper (see §When the user tells you to go around the wrapper). +Every heavy command an agent starts goes through the wrapper. There is no exception for a session that looks alone, for a command that looks small, or for a user who is in a hurry. Two sections say when a command runs without the wrapper: §When an instruction sends a command around the wrapper, and §When the wrapper cannot run. No other case exists. -Heavy commands are what freeze a machine, not agents. Sessions in other terminals and other projects run their own test suites and builds at the same moment, and no session can see the others. When the commands together need more memory than the machine has, it swaps until it stops responding, and that costs every session, not only the one that started the last command. The wrapper makes the commands of every session and every project on the machine take turns on its memory, so too much work shows up as a queue instead of a freeze. +A machine freezes because of the heavy commands that run on it, not because of the number of agents. Sessions in other terminals and other projects run their own test suites and builds at the same moment, and no session can see the others. When the commands together need more memory than the machine has, it swaps until it stops responding, and that costs every session, not only the one that started the last command. The wrapper makes the commands of every session and every project on the machine take turns on its memory, so too much work shows up as a queue instead of a freeze. -**Looking first does not protect the machine.** Two sessions that look at the load at the same moment both see a quiet machine, and both start. The same is true of a sum of budgets against the machine's total memory: the sum counts your commands and no one else's. Only a reservation that every session takes before it starts can count the commands, and the wrapper is that reservation. +**Looking first does not protect the machine.** Two sessions that look at the load at the same moment both see a quiet machine, and both start. A sum of budgets against the machine's total memory does not protect it either: the sum counts your commands and no one else's. Only a reservation that every session takes before it starts can count the commands, and the wrapper is that reservation. **Violating the letter of these rules is violating their spirit.** @@ -22,32 +22,34 @@ Heavy commands are what freeze a machine, not agents. Sessions in other terminal - When a command failed on a port that is already in use, or on a tool's own lock. - When the machine is slow or swaps and someone asks what to change. -A command is heavy when the project's record says so, or when it does more than touch a handful of files. A part of a heavy command is heavy too: one test file, one package, one target. When in doubt, it is heavy: the wrapper costs a second, a frozen machine costs every session. +A command is heavy when the project's record says so, or when it compiles, tests, checks, generates, or installs over more than a handful of files. An install of the dependencies, a code generator, and a formatter over the whole tree are heavy. So is a commit or a push in a project whose hooks run the tests or the linter. A part of a heavy command is heavy too: one test file, one package, one target. When in doubt, it is heavy: the wrapper costs a second, a frozen machine costs every session. -Skip for commands that only read (listing files, searching, version-control queries). Skip for a CI pipeline and for a person at a terminal: their commands stay as they are. +Skip for commands that only read (listing files, searching, version-control queries). Do not add the wrapper to the project's scripts, to its CI configuration, or to the commands that a person types: this skill is for the commands that an agent starts on a machine that it shares. + +A command that does not end, such as a server or a watch mode, holds its memory in the queue until it stops. Start it through the wrapper, and stop it when your work with it is done. ## The wrapper ``` -python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... -- +python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --memory [--cpus ] [--exclusive ]... [--measure] -- ``` | Option | Meaning | | --- | --- | -| `--memory ` | Memory the command may use, such as `6G` or `4096M`. Taken from the record. Without it the wrapper uses its default budget. | +| `--memory ` | Memory the command may use, such as `6G` or `4096M`. Taken from the record. Without it the wrapper uses its default budget, a quarter of the machine's memory. | | `--cpus ` | Processor limit, as a whole number. Taken from the record. | -| `--exclusive ` | A resource that only one command in this repository may hold at a time, such as a fixed port. Repeat the option for each resource. | +| `--exclusive ` | A resource that only one command may hold at a time, such as a fixed port. You choose the name. The wrapper keeps the names of each repository apart, and all worktrees of one repository share them. Repeat the option for each resource. | | `--measure` | Also print a suggested budget. Discovery uses it. | -The wrapper waits for its share of the machine's memory, waits until that much is free, runs the command, and prints the budget against the measured peak on the error stream. Each line that the wrapper prints starts with `bounded-run:`. Its exit code is the command's exit code. Exit code 125 means the wrapper itself failed. +The wrapper does four things in sequence. It waits for its turn in the queue. It waits until the memory of its budget is free. It runs the command. It prints the budget and the measured peak on the error stream. Each line that the wrapper prints starts with `bounded-run:`. Its exit code is the command's exit code. Exit code 125, with a `bounded-run:` line that names a fault and with no line for the budget and the peak, means that the wrapper itself failed (see §When the wrapper cannot run). -The command receives `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB` in its environment, so a recorded command line can hand them to the toolchain's own parallelism and memory settings. +The wrapper sets `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB` in the environment of the command, from `--cpus` and `--memory`. A recorded command line can read them and hand them to the toolchain's own parallelism and memory settings. You do not set them: you change them with the two options. -On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. +On Linux the wrapper also puts a hard cap on the command where the system allows it: a command that passes its budget is stopped with exit code 137, and the machine does not swap. Elsewhere there is no hard cap, the wrapper says so in its output, and the queue and the wait are the whole protection. When a recorded command ends with exit code 137 and the wrapper reports a peak near the budget, the cap stopped it: the command grew. Measure it again with `--measure` and `--memory` at two times the budget, and correct the record. ## The record -Budgets and command lines are facts about one machine and one user, so they live in your project memory, not in the repository. The record is one memory named `bounded-heavy-commands`. Your harness decides the file format. This skill decides the content. +Budgets and command lines are facts about one machine and one user, so they live in your project memory (the notes that your harness keeps for this project between sessions), not in the repository. The record is one memory named `bounded-heavy-commands`. Your harness decides the file format. This skill decides the content. For each heavy command, record: @@ -58,92 +60,97 @@ For each heavy command, record: - each exclusive resource it uses - the flags or variables that limit the toolchain's own parallelism -Then, every time: +Then, before each heavy command, use the first case that applies: -1. **The record exists.** Check that each command in it still exists in the project, and that the path of the wrapper in it still exists. An update of the plugin can move the wrapper: then put the path that this skill shows into each command line of the record. Then use the bounded command lines as written. -2. **The record does not exist.** Run the discovery below and save the record before you run anything heavy. -3. **Project memory is off or unavailable.** Run the discovery in this session, keep the result in your context, and use the wrapper's default budget for anything you could not measure. +1. **Your prompt carries bounded command lines.** You are a subagent. Use them under the rule that your prompt gives with them, and run no discovery. For a heavy command that your prompt does not carry, use the wrapper with no `--memory` option. +2. **The record exists and has the command.** Check that the plain command still exists in the project, and that the file of the wrapper in the command line still exists. When the file of the wrapper is not there, an update of the plugin moved it: put the path that the command line in §The wrapper shows into each command line of the record. Then use the bounded command line as written. +3. **The record exists, and the command is not in it or is no longer correct.** Run the discovery for that command and correct the record. Remove an entry whose command the project no longer has. +4. **The record does not exist.** Run the discovery for the commands that you are about to run. The measured runs of the discovery are your first heavy runs. Save the record before you run a heavy command that is not a part of the discovery. The other commands get their entry when an agent first needs them. +5. **Project memory is off or unavailable.** Run the discovery in this session, keep the result in your context, and use the wrapper's default budget for anything you could not measure. A budget is a measurement, not a preference. Change one only when the wrapper's output shows that the peak moved, and write the new peak and date with it. -A part of a recorded command (one test file, one target) uses the bounded command line of the full command, with its budget and its exclusive resources, and the narrower arguments. It needs no entry of its own. Measure it and add an entry only when you run it often and its peak is much lower. +A part of a recorded command (one test file, one target) uses the bounded command line of the full command, with its budget and its exclusive resources, and the narrower arguments. It needs no entry of its own and no measurement, because the budget of the full command is sufficient for each part of it. ## Discovery 1. Find how the project runs its tests, its linter, its build, and its type check. Read the project's instruction files, its build configuration, and its CI configuration. 2. Find the exclusive resources: a port that a test server binds, a tool that refuses to run twice, a fixed directory that a build writes to. -3. Find how the toolchain limits its own parallelism and memory. Write the command line so that it takes those limits from `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB`. -4. Run each heavy command once with `--measure`, one at a time: +3. Find how the toolchain limits its own parallelism and memory. Write the command line so that it takes those limits from `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB`. The wrapper sets the two variables for the command only. Your own shell does not have them. A toolchain that reads the environment itself needs nothing more. For a toolchain that takes a flag, put the command into an inner shell, in single quotes, so that your own shell does not replace the variable with an empty value before the wrapper starts: + + ``` + ... --cpus 4 -- sh -c ' "$BOUNDED_RUN_CPUS"' + ``` + +4. Run each heavy command once with `--measure`, one at a time. Measure the full command, not a part of it: the peak of one test file is not the budget of the suite. Add `--exclusive ` for each resource that step 2 found for it: ``` python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure -- ``` -5. Record the suggested budget that the wrapper prints. It is the peak plus a margin, and the margin is larger where the measurement is approximate. If the hard cap stopped the command during the measurement, run it again with a larger `--memory`. +5. Record the suggested budget that the wrapper prints. It is the peak plus a margin, and the margin is larger where the measurement is approximate. The measurement runs under the default budget. If the hard cap stopped the command during the measurement, run it again with `--memory` at two times the default budget that the wrapper printed. 6. Save the record. +The measured run is a real run of the command. Its result counts, so do not run the command a second time to get the result. + ## Rules for the wait -A long wait means that the machine is full. It is never a fault to repair. The only correct moves are to keep the run in the queue and to tell the user that the machine is full and the command is queued. +A long wait means that the machine is full. It is never a fault to repair: the queue has no state that can go wrong between runs, and an agent that repairs it breaks it. Unless an instruction says otherwise (see the next section), the only correct moves are to keep the run in the queue and to tell the user that the machine is full and the command is queued. A subagent tells its dispatcher in its report. -- **Run a bounded command in the background, with no short timeout around it.** It can wait in the queue for minutes before it starts. A timeout that you calculate from the run time of the command does not count the wait. A timeout that fires during the wait kills a command that never ran, and the result reads like a failure of the code. +- **Run a bounded command in the background, with no short timeout around it.** It can wait in the queue for minutes before it starts. Where the harness requires a timeout, use the longest one that it permits. When that timeout ends a run, start the run again through the wrapper, and say in your report that the timeout ended the run and that the code did not fail. A timeout that you calculate from the run time of the command does not count the wait. A timeout that fires during the wait kills a command that never ran, and the result reads like a failure of the code. - **Plan the time as if the commands run one after the other.** Two bounded commands that start together are safe, because the queue puts them in sequence when the machine cannot hold both. So a parallel start does not always save time, and a promise to the user that depends on it is a guess. - **Do not lower a budget to start sooner.** A smaller budget does not make the command smaller. It moves the failure inside the command: on Linux as a kill at the hard cap, elsewhere as the swap that the queue exists to prevent. - **Do not run the plain command because the queue is slow.** A slow queue means the machine is full. The plain command is how it freezes. This includes a narrower form of the command: one test file outside the queue is a command that the queue cannot count. -- **Do not set a `BOUNDED_RUN_*` variable on a call.** The usage text of the wrapper lists them. A person sets the tuning values for the whole machine, and the tests of the wrapper set the rest. A call with its own slot size, reserve, or lock directory does not share the queue with the other sessions, and a call with no cap can take the memory of all of them. A note in your project memory that recommends one is wrong: delete the note, and tell the user that you did. -- **Do not touch the lock directory.** Do not delete, move, or edit a file in it, and do not look for the process that holds a lock. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot. -- **Do not sleep and retry around a collision, not even one time.** A port in use or a tool's lock means two commands wanted one resource. Add the resource to the record as an `--exclusive` name and run through the wrapper. Do not stop the process that holds the resource: it belongs to a different session. +- **Do not set an environment variable whose name starts with `BOUNDED_RUN_`.** The usage text of the wrapper lists variables that change how the queue counts memory, where it keeps its locks, and whether the hard cap applies. They are for a person who tunes the whole machine in a shell profile, and for the tests of the wrapper. A call that sets one does not share the queue with the other sessions, or it runs with no cap. A note in your project memory that recommends one is wrong: delete the note, and tell the user that you did. +- **Do not touch the lock files of the wrapper.** The wrapper keeps them in a directory of its own. Do not look for that directory. Do not delete, move, or edit a file in it, and do not look for the process that holds a lock. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot. +- **Do not sleep and retry around a collision, not even one time.** A port in use or a tool's lock means two commands wanted one resource. Add the resource to the record as an `--exclusive` name and run through the wrapper. A subagent adds the option to its own command line and names the resource in its report, so that its dispatcher corrects the record. Do not stop the process that holds the resource: it belongs to a different session. When a run with the `--exclusive` name fails on the same collision, the holder did not go through the wrapper or belongs to a different repository: tell the user, or your dispatcher, what holds the resource, and wait for the answer. -## When the user tells you to go around the wrapper +## When an instruction sends a command around the wrapper -An explicit instruction from the user comes before this skill. When the user names the action ("run the tests directly", "do not use the wrapper for this"), say one time, in one or two sentences, what the wrapper protects and that you cannot see the other sessions. Then do what the user said. Do not refuse, and do not argue a second time. +An explicit instruction from the user comes before this skill. When the user names the action ("run the tests directly", "do not use the wrapper for this", "set this variable for the run"), say one time, in one or two sentences, what the wrapper protects and that you cannot see the other sessions. Then do what the user said. Do not refuse, and do not argue a second time. -The instruction covers the command and the time that it names. The next heavy command goes through the wrapper again, unless the user said that the instruction holds for the session. +The instruction covers the command that it names, for one run. The next heavy command goes through the wrapper again, unless the user said that the instruction holds for the session. An instruction that must hold for longer than the session belongs in the project's instruction file, where each session and the user can see it: ask the user to put it there. -A rule in the project's instruction file comes before this skill too. Obey it, and tell the user one time that the file sends heavy commands around the queue and what that costs on a machine with more than one session. The user decides if the file changes. Do not ignore the file silently, and do not edit it yourself. +A rule in the project's instruction file comes before this skill too, when it names the wrapper or tells agents to run a command directly. A file that only names the project's commands is input for the discovery, not an exemption. Obey the rule, and tell the user one time per session that the file sends a heavy command around the queue and what that costs on a machine with more than one session. The user decides if the file changes. Do not ignore the file silently, and do not edit it yourself. -Pressure is not an instruction. "Hurry", "make it start", and "I do not care how" name a result, not an action. Keep the run in the queue and tell the user that the machine is full. Do not go around the queue on your own decision. You can tell the user that an instruction from them is the way around it, together with what it costs, and the user decides. A note in your project memory from an earlier session is not an instruction from the user either. +Pressure is not an instruction. "Hurry", "make it start", and "I do not care how" name a result, not an action. Keep the run in the queue and tell the user that the machine is full. Do not go around the queue on your own decision. When the user asks how to get around the wait, answer: the user can tell you to run the command without the wrapper, and say what that costs. The user decides. When the user only names a deadline, do not mention a way around the wait. A note in your project memory from an earlier session is not an instruction from the user either. ## Dispatching subagents A subagent does not see your project memory. It knows the bounded commands only when its prompt carries them. -Every dispatch prompt for a subagent that will verify its own work MUST include: +On a machine on which the wrapper can run, every dispatch prompt for a subagent that will run a heavy command MUST include: 1. The bounded command line for each heavy command, copied from the record. -2. This rule, in these words: "Run these commands exactly as written. Do not run the plain form of any of them, and do not run a part of one (one test file, one target) outside the wrapper: put the narrower arguments into the command line as written. Set no `BOUNDED_RUN_*` variable. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair." +2. This rule, in these words: "Run the bounded commands as written. You can make two changes: a narrower argument for the command after the `--`, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited." +3. Each command that an instruction exempts from the wrapper, in its plain form, in a list of its own, with the instruction that exempts it. The rule of item 2 does not apply to that list. An instruction of the user that covers one run goes to the one subagent that does that run, and to no other. + +Do not dispatch fewer subagents to protect the machine. The queue protects it. Subagents that wait in the queue cost time, not memory. The one exception is a machine on which the wrapper cannot run (see the next section). -Do not dispatch fewer subagents to protect the machine. The queue protects it. Subagents that wait in the queue cost time, not memory. +## When the wrapper cannot run -## Without Python 3 +The wrapper needs `python3`, version 3.9 or later. When `python3` is missing or older, tell the user once per session that the wrapper cannot run and that Python 3.9 is what it needs. -The wrapper needs `python3`, version 3.9 or later. If it is missing, tell the user once per session that the wrapper cannot run and that Python 3 is what it needs. Then continue under these rules: run one heavy command at a time in your session, never two in parallel, and set the toolchain's parallelism to half the machine's processors or fewer. This protects the machine from your session only, not from the others. Say so in your report. +When `python3` reports that it cannot open the file of the wrapper, the path in the command line is old. That is a fault of the record, not of the machine: correct the path (§The record, case 2). A subagent stops and reports it. -## Anti-patterns +When the wrapper ends with exit code 125, read its `bounded-run:` message. A fault of your call (an option, a name, a command that does not exist) is yours to correct. A fault of the machine (the wrapper cannot make or lock its files) means that the wrapper cannot run here: tell the user once per session, with the message. -- **Running the plain command "just once".** One plain test suite beside three queued ones is the freeze. The wrapper cannot count a command that never went through it. -- **Judging weight by feel.** "It is only the linter" is a guess. The record holds the measured peak; a command that is not in the record gets measured, not guessed. -- **Looking at the load before a run.** The look is true for one moment, and each session that looks sees the same quiet machine. -- **Wrapping the wrapper in a timeout.** The wait in the queue is part of the run. A timeout turns a full machine into a false test failure. -- **Tuning the budget down.** A budget below the measured peak is a scheduled failure. -- **Repairing the queue.** The queue has no state that can go wrong between runs. An agent that repairs it breaks it. -- **Handing a subagent the project's plain commands.** The subagent runs what its prompt names. Name the bounded command lines. -- **Writing the record into the repository.** The numbers belong to one machine. In the repository they become another person's wrong budget. +In both cases, a missing Python and a fault of the machine, continue under these fallback rules. Run one heavy command at a time, never two in parallel, and set the toolchain's parallelism to half the machine's processors or fewer. Your subagents count as your session: no queue protects the machine now, so dispatch them so that only one of them runs a heavy command at a time. Their prompts carry the plain commands and these fallback rules, in place of the three items of §Dispatching subagents. The fallback protects the machine from your session only, not from the other sessions. Tell the user that in your report. ## Red flags | Thought | Reality | | --- | --- | -| "This session is the only one running, so the plain command is fine" | You cannot see other sessions or other projects. Through the wrapper, every time. | +| "This session is the only one running, so the plain command is fine" | You cannot see other sessions or other projects. Each heavy command goes through the wrapper, unless an instruction names the plain command. | | "Both budgets together are well under the machine's memory" | The sum counts your commands only. The queue counts the commands of every session. | | "I'll check the load first and start when it is quiet" | Each session that looks at that moment sees the same quiet machine. Take the reservation: run through the wrapper. | -| "It is only the linter, it is small" | The record says what is heavy, not your sense of it. Not in the record means not yet measured. | +| "It is only the linter, it is small" | The record says what is heavy, not your sense of it. Not in the record, and not a part of a recorded command, means not yet measured. | | "I'll run just those few tests now, that fits in the free memory" | A part of a heavy command goes through the wrapper too. "It fits" is your estimate; the queue is the count. | | "I'll run the plain command once to check quickly" | One command outside the queue is all a freeze needs. | | "Running both in parallel is what makes the deadline possible" | Through the wrapper a parallel start is safe, but the queue decides if the two run together. Do not promise a time that depends on it. | | "The queue has waited five minutes, I'll lower `--memory` to get a slot" | The budget is the measured peak plus a margin. Lowering it moves the failure inside the command. | -| "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no `BOUNDED_RUN_*` variable. | -| "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock directory alone. | +| "A smaller slot size made it start at once last time" | The variable changes what the queue counts, not what the command uses. Set no variable whose name starts with `BOUNDED_RUN_`. | +| "A crashed job left a stale lock, I'll remove only that file" | A stale lock cannot exist: the kernel releases a lock when its holder stops. The slots are held by commands that run. Leave the lock files alone. | | "The user told me to run it directly, but the skill says no exception" | An explicit instruction from the user comes first. Say one time what the wrapper protects, then obey. | | "The user is waiting, the queue is too slow" | A frozen machine is slower. Tell the user that the machine is full and the command is queued. | | "The port was in use, I'll back off once and retry" | Two commands wanted one resource. Record it as `--exclusive` and run through the wrapper. | @@ -151,4 +158,4 @@ The wrapper needs `python3`, version 3.9 or later. If it is missing, tell the us | "The subagent will find the test command on its own" | It will find the plain one. Put the bounded command lines in its prompt. | | "Four subagents is too many for this machine, I'll dispatch two" | The queue limits the commands. Fewer subagents only makes the work slower. | | "Project memory is off, so there is no record to keep" | Discover in this session and keep the result in context. The rule does not depend on the memory. | -| "Python 3 is missing, so none of this applies" | The fallback applies: one heavy command at a time, toolchain parallelism at half or less, and say so. | +| "The wrapper cannot run here, so none of this applies" | The fallback applies: one heavy command at a time, toolchain parallelism at half or less, and say so. | From 1ec8cfe98f044dae03d108deedb197ade4cf1aab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:09:45 +0100 Subject: [PATCH 35/65] feat(skills): send every heavy command through bounding-heavy-commands (#45) Co-Authored-By: Claude Fable 5.1 --- README.md | 5 +++-- skills/developing-a-feature/SKILL.md | 3 +++ skills/fanning-out-with-worktrees/SKILL.md | 2 ++ skills/reviewing-feature-progress/SKILL.md | 2 ++ templates/project-CLAUDE.md | 5 +++-- 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9c0999e..b33aad9 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ It is also the faster path. Breaking the feature into independent PRs lets the m | `fanning-out-with-worktrees` | An orchestrator dispatching parallel subagents into per-PR worktrees off a feature branch. | | `stacking-dependent-prs` | A PR's branch is based on another open PR's branch (a linear stack). Creates, adopts, propagates through, syncs, and merges the stack with `gh stack`, in one dedicated worktree per stack. | | `reviewing-feature-progress` | Orchestration checkpoints: between fan-out waves, and before the integration PR. | +| `bounding-heavy-commands` | About to run a test suite, linter, build, or type check, or to dispatch subagents that will. Runs every heavy command through a memory queue that all sessions and projects on the machine share, so parallel work queues instead of freezing the machine. | | `testing-a-feature` | Writing tests for any non-trivial change. Decides the assertion shape (black-box against the contract). | | `testing-end-to-end` | A structurally-complete feature introduces a new user- or consumer-visible flow. Decides which flows earn an end-to-end test and what each asserts (golden path, not edge cases). | | `writing-code-comments` | About to write, edit, or delete a comment in source code. Decides whether the comment exists and what it holds: the contract for a doc comment, and the fact that the code cannot show for an inline comment. | @@ -56,7 +57,7 @@ flowchart TD Shape -->|single PR| IssueOne[File one issue
feature or bug] IssueOne --> PlanS[Write the plan
ordered tasks · dependencies] PlanS --> Build[Implement directly
test-first · one commit per task] - Build --> VerifyS[Verify green
tests · lint · typecheck] + Build --> VerifyS[Verify green
tests · lint · typecheck
each through the memory queue] VerifyS --> PR1[Open PR → main
Fixes / Closes the issue] Shape -->|many PRs| Epic[File an epic
+ one sub-issue per PR, linked] @@ -66,7 +67,7 @@ flowchart TD Wave --> Merge[Orchestrator reviews each sub-PR,
merges it, closes its sub-issue] Merge --> Done{All sub-PRs
merged?} Done -->|next wave| Wave - Done -->|yes| VerifyM[Verify the integrated branch
green end to end] + Done -->|yes| VerifyM[Verify the integrated branch
green end to end, through the memory queue] VerifyM --> PR2[Open the integration PR
feature → main · Closes the epic] PR1 --> Ship([External review → merge
plan + state torn down in the same diff]) diff --git a/skills/developing-a-feature/SKILL.md b/skills/developing-a-feature/SKILL.md index df42f2c..6aa86cb 100644 --- a/skills/developing-a-feature/SKILL.md +++ b/skills/developing-a-feature/SKILL.md @@ -94,6 +94,7 @@ Record the choice as `sub_pr_target: feature-branch` or `sub_pr_target: main`. T - **2+ independent tasks → drive the build task-by-task with review between tasks.** **REQUIRED SUB-SKILL:** `superpowers:subagent-driven-development`. The orchestrator (this session — the main loop, which *can* dispatch subagents) runs that skill's loop engine: a fresh implementer subagent per task with full task text handed in, then review, fix-loop, and continuous execution across all tasks. Two adaptations keep it consistent with the rest of this plugin: - **Per-task review is the `review` skill** (the same mechanism `feature-dev-workflow:fanning-out-with-worktrees` uses for sub-PRs), run by the orchestrator — not the implementer subagent that wrote the task. Run it as two scoped passes, spec-compliance first as a gate, then code quality; route findings back to the implementer and re-run until clean. - Each implementer subagent uses **`superpowers:test-driven-development`** + **`feature-dev-workflow:testing-a-feature`** for its task, and `feature-dev-workflow:writing-code-comments` for every comment the change adds, edits, or deletes, exactly as the direct path below. + - Each implementer subagent's prompt carries the bounded command line for every heavy command it will run, and the rule to use no other form. A subagent does not see the orchestrator's project memory. **REQUIRED SUB-SKILL:** `feature-dev-workflow:bounding-heavy-commands` (§Dispatching subagents). Why conditional: SDD's premise is independent tasks. Below that threshold the dispatch overhead and context hand-off cost more than they return, so the direct path is correct. This is the in-session analogue of the multi-PR fan-out — same "author and reviewer are different contexts" discipline, one PR instead of many. @@ -103,6 +104,8 @@ Record the choice as `sub_pr_target: feature-branch` or `sub_pr_target: main`. T Either way: commits follow CLAUDE.md conventions (`(): (#)`), and you run the project's test and lint commands (and typecheck, if it has one) before claiming work is done. Discover them from the project's CLAUDE.md / AGENTS.md or its build config (Makefile, package.json, etc.). + **REQUIRED SUB-SKILL:** `feature-dev-workflow:bounding-heavy-commands` before you run any of them. Every test, lint, build, and typecheck command goes through its wrapper, whether or not this session looks alone: other sessions and other projects share the machine, and none of them can see the others. + **REQUIRED SUB-SKILL:** `feature-dev-workflow:writing-code-comments` for every comment the change adds, edits, or deletes, on both single-PR build modes. It decides whether the comment exists and what it holds. **OPTIONAL SUB-SKILL:** `simple-english:simple-english` for the prose of every commit body and every code or doc comment you write, here and in the Step 7 teardown commit. If it is available, load it before you draft and write the sentences under it. Where its formatting rules (headings, bold, lists, or its register for chat replies) differ from the host skill or its template, the host skill and its template win. It sets sentence style only: the subject line keeps the project's commit convention (format, prefix, length), the body still carries the why and what the diff cannot show, and the project's comment rules still decide whether a comment exists and what it may say (no narration of the code, no change history). Identifiers, strings, and log messages are code and keep the project's rules. If the skill is not available, do not stop or wait for it. If you have not already done so in this session, tell the user once that it can be installed with `/plugin marketplace add AminBlg/SimpleEnglish` and then `/plugin install simple-english@simple-english`. Then write short, plain, active sentences without it. diff --git a/skills/fanning-out-with-worktrees/SKILL.md b/skills/fanning-out-with-worktrees/SKILL.md index 9a4db17..cfef8a9 100644 --- a/skills/fanning-out-with-worktrees/SKILL.md +++ b/skills/fanning-out-with-worktrees/SKILL.md @@ -60,6 +60,7 @@ Each dispatch prompt MUST include: 2. **Context handoff.** State file path, plan path, spec path, the issue number it's working, the relevant contract row(s) (Name + Producer + Consumer + Shape + Realization), **and the plan's `## Conventions` block**. The subagent implements **against the contract and the conventions** — it does not re-discover or re-design either, and it does not invent its own directory layout or naming scheme. A subagent handed contracts but not conventions will name and structure locally, and the merged feature reads as written by a committee (see `feature-dev-workflow:maintaining-architectural-coherence`). 3. **Implementation skills.** `superpowers:test-driven-development` + `feature-dev-workflow:testing-a-feature` for every change, and `feature-dev-workflow:writing-code-comments` for every comment the change adds, edits, or deletes. 4. **PR completion.** A stack layer's subagent skips this item and reports to the orchestrator, which opens the stack's PRs (see the stack paragraph above). A sequential layer's subagent reports its finished branch and head commit without pushing, because the orchestrator pushes the stack's worktree with `gh stack push`. A parallel layer's subagent pushes its branch from its temporary worktree first, then reports. Every other subagent, when the implementation is done and verified, invokes `feature-dev-workflow:opening-a-pull-request`. The base and body keyword depend on `sub_pr_target` in the state file: when `feature-branch`, use `--base /` and `Towards #` in the body (`Fixes`/`Closes` don't fire on non-default-branch merges; `Towards` keeps the issue open until the orchestrator closes it manually after the merge); when `main`, use `--base main` and the type-appropriate closing keyword in the body — `Fixes #` for a bug sub-issue, `Closes #` otherwise; either fires automatically on merge to the default branch (see `feature-dev-workflow:opening-a-pull-request` for the distinction). No sub-PR keyword closes the epic, and in main mode the epic stays open for the user (see Step 7). The subagent reports the PR URL back to the orchestrator. +5. **Bounded commands.** The bounded command line for every heavy command the subagent will run (tests, lint, build, typecheck), copied from the orchestrator's record, and the rule to use no other form. A subagent does not see the orchestrator's project memory, so a prompt without them sends it to the plain commands, and a wave of plain test runs is what freezes the machine. **REQUIRED SUB-SKILL:** `feature-dev-workflow:bounding-heavy-commands` (§Dispatching subagents) before writing the first dispatch prompt of a wave. Each dispatch prompt also carries this instruction for the subagent: **OPTIONAL SUB-SKILL:** `simple-english:simple-english` for the prose of your commit bodies, code and doc comments, and PR body. If it is available, load it before you draft and write the sentences under it. Where its formatting rules (headings, bold, lists, or its register for chat replies) differ from the host skill or its template, the host skill and its template win. It sets sentence style only: the commit subject keeps the project's commit convention, and the project's comment rules still decide whether a comment exists and what it may say. If it is not available, do not stop or wait for it: write short, plain, active sentences and say in your report that it was missing. The orchestrator, not the subagent, gives the user the install hint (`/plugin marketplace add AminBlg/SimpleEnglish`, then `/plugin install simple-english@simple-english`), at most once per session. @@ -143,6 +144,7 @@ When every wave is complete (every sub-issue closed, every row `self-merged`, ev - **Orchestrator fixing review findings in place.** The worktree subagent wrote the code and holds the context; it fixes, then the orchestrator re-reviews. A silent orchestrator fix skips the author and erodes the shared understanding the parallel agents run on. - **Letting the worktree subagent review its own PR.** A subagent reviewing the code it just wrote has the same blind spots in review that it had in implementation. The orchestrator owns sub-PR review precisely because it didn't write the code. - **Letting a bubble-up concern die in one subagent.** Propagation is the whole point of the watch loop. +- **Shrinking the wave to spare the machine.** The number of subagents does not decide the load; the commands they run do. Dispatch the wave the plan calls for and hand every subagent the bounded commands (dispatch item 5). Subagents that wait in the queue cost time, not memory. - **Forgetting to manually close the sub-issue when `sub_pr_target: feature-branch`.** The keyword doesn't fire on non-default-branch merges; the issue page silently shows "open" even though the work shipped. - **Using `Towards #` when `sub_pr_target: main`.** `Closes` fires on merge to the default branch; `Towards` intentionally blocks auto-close. Using the wrong keyword silently leaves sub-issues open after they merge to main and forces a manual cleanup pass. - **Letting the state file go stale.** A resumed session reads it as ground truth. Update every row as reality moves; commit **and push** the state-file diff per phase transition — an unpushed local commit diverges the feature branch the moment the next sub-PR squash-merges on GitHub (see Step 5.4). diff --git a/skills/reviewing-feature-progress/SKILL.md b/skills/reviewing-feature-progress/SKILL.md index 8244879..bf2880a 100644 --- a/skills/reviewing-feature-progress/SKILL.md +++ b/skills/reviewing-feature-progress/SKILL.md @@ -87,6 +87,8 @@ What this step writes depends on whether a later wave in the plan is still to be At the same checkpoint, with the feature whole and its behavior settled, write or update the public-facing docs the feature touches before the integration PR opens or flips ready (or before the fan-out hands back when `sub_pr_target: main`) — the integration PR is the external-review surface, and its docs are part of the first impression. **REQUIRED SUB-SKILL:** `feature-dev-workflow:writing-docs` for what earns a doc and how to verify a reader can actually use it. +**REQUIRED SUB-SKILL:** `feature-dev-workflow:bounding-heavy-commands` for how to run the checks below. The project-wide suite is the heaviest command of the feature, and a checkpoint often runs while other sessions verify their own work. Run it through the wrapper. + **REQUIRED SUB-SKILL:** `superpowers:verification-before-completion`. Run the project-wide checks where the integrated code lives, which depends on the state file's `sub_pr_target`: - **`feature-branch`**: the main feature worktree, which holds the integration state (sub-worktrees only hold their own sub-branch): diff --git a/templates/project-CLAUDE.md b/templates/project-CLAUDE.md index 4f15f1d..ae1ede7 100644 --- a/templates/project-CLAUDE.md +++ b/templates/project-CLAUDE.md @@ -17,7 +17,7 @@ flowchart TD Shape -->|single PR| IssueOne[File one issue
feature or bug] IssueOne --> PlanS[Write the plan
ordered tasks · dependencies] PlanS --> Build[Implement directly
test-first · one commit per task] - Build --> VerifyS[Verify green
tests · lint · typecheck] + Build --> VerifyS[Verify green
tests · lint · typecheck
each through the memory queue] VerifyS --> PR1[Open PR → main
Fixes / Closes the issue] Shape -->|many PRs| Epic[File an epic
+ one sub-issue per PR, linked] @@ -27,7 +27,7 @@ flowchart TD Wave --> Merge[Orchestrator reviews each sub-PR,
merges it, closes its sub-issue] Merge --> Done{All sub-PRs
merged?} Done -->|next wave| Wave - Done -->|yes| VerifyM[Verify the integrated branch
green end to end] + Done -->|yes| VerifyM[Verify the integrated branch
green end to end, through the memory queue] VerifyM --> PR2[Open the integration PR
feature → main · Closes the epic] PR1 --> Ship([External review → merge
plan + state torn down in the same diff]) @@ -48,6 +48,7 @@ Invoke `feature-dev-workflow:planning-a-feature` at conception. It and the `**RE | Code comments and doc comments (whether one exists, and what it holds) | `feature-dev-workflow:writing-code-comments` | | Public-facing docs for what the feature changed (once structurally complete) | `feature-dev-workflow:writing-docs` | | Verify-before-done | `superpowers:verification-before-completion` | +| Run tests, lint, builds, and other heavy commands without exhausting the machine | `feature-dev-workflow:bounding-heavy-commands` | | Open / flip pull requests | `feature-dev-workflow:opening-a-pull-request` | | Loop a PR through automated (Copilot) review until clean (opt-in) | `feature-dev-workflow:copilot-review-loop` | From 4ebf0dd30b58ba1c18fe3b74961545244b4152d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:11:05 +0100 Subject: [PATCH 36/65] fix(skills/bounding-heavy-commands): refuse a setting that is not a finite number (#45) A value of nan or inf in a BOUNDED_RUN_ variable ended the wrapper with a traceback, and nan as the poll time was accepted. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 2 ++ .../scripts/tests/test_bounded_run.py | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 3de970f..63b5b91 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -128,6 +128,8 @@ def _number(environ: Mapping[str, str], name: str, fallback: float) -> float: value = float(text) except ValueError: raise WrapperError("cannot read %s='%s'; use a number" % (name, text)) + if not math.isfinite(value): + raise WrapperError("cannot read %s='%s'; use a number" % (name, text)) if value < 0: raise WrapperError("%s must not be less than zero" % name) return value diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index f983311..20fcc5c 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -130,6 +130,13 @@ def test_rejects_a_value_that_is_not_a_number(self): with self.assertRaises(bounded_run.WrapperError): bounded_run.Settings({"BOUNDED_RUN_POLL_SECONDS": "fast"}, read_total=lambda: 1) + def test_rejects_a_value_that_is_not_finite(self): + for name in ("BOUNDED_RUN_SLOT_MIB", "BOUNDED_RUN_TOTAL_MIB", "BOUNDED_RUN_POLL_SECONDS"): + for text in ("nan", "inf", "1e400"): + with self.subTest(name=name, text=text): + with self.assertRaises(bounded_run.WrapperError): + bounded_run.Settings({name: text}, read_total=lambda: 16384) + class LockDirectoryTest(unittest.TestCase): def test_override_wins(self): From f9830444acc7b3536ba98628bb0caccc84e50e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:19:58 +0100 Subject: [PATCH 37/65] fix(skills/bounding-heavy-commands): decide the case of a harness with no project memory (#45) The case for a record that does not exist came first, so an agent with no project memory planned to save a record. The two cases now name the state of the memory, and the one for no memory comes first. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/SKILL.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index d593864..70931f5 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -63,10 +63,10 @@ For each heavy command, record: Then, before each heavy command, use the first case that applies: 1. **Your prompt carries bounded command lines.** You are a subagent. Use them under the rule that your prompt gives with them, and run no discovery. For a heavy command that your prompt does not carry, use the wrapper with no `--memory` option. -2. **The record exists and has the command.** Check that the plain command still exists in the project, and that the file of the wrapper in the command line still exists. When the file of the wrapper is not there, an update of the plugin moved it: put the path that the command line in §The wrapper shows into each command line of the record. Then use the bounded command line as written. +2. **The record exists and has the command.** Check that the plain command still exists in the project, and that the file of the wrapper in the command line still exists. When the file of the wrapper is not there, an update of the plugin moved it. The command line in §The wrapper shows the correct path: put it into each command line of the record. Then use the bounded command line as written. 3. **The record exists, and the command is not in it or is no longer correct.** Run the discovery for that command and correct the record. Remove an entry whose command the project no longer has. -4. **The record does not exist.** Run the discovery for the commands that you are about to run. The measured runs of the discovery are your first heavy runs. Save the record before you run a heavy command that is not a part of the discovery. The other commands get their entry when an agent first needs them. -5. **Project memory is off or unavailable.** Run the discovery in this session, keep the result in your context, and use the wrapper's default budget for anything you could not measure. +4. **Your harness has no project memory, or it is off.** You cannot save a record, so do not try. Run the discovery in this session, keep the result in your context, and use the wrapper's default budget for anything you could not measure. +5. **Project memory is on, and the record does not exist.** Run the discovery for the commands that you are about to run, and save the record. The measured runs of the discovery are your first heavy runs. A heavy command of the project that you do not run now gets its entry when an agent first needs it. A budget is a measurement, not a preference. Change one only when the wrapper's output shows that the peak moved, and write the new peak and date with it. @@ -76,13 +76,13 @@ A part of a recorded command (one test file, one target) uses the bounded comman 1. Find how the project runs its tests, its linter, its build, and its type check. Read the project's instruction files, its build configuration, and its CI configuration. 2. Find the exclusive resources: a port that a test server binds, a tool that refuses to run twice, a fixed directory that a build writes to. -3. Find how the toolchain limits its own parallelism and memory. Write the command line so that it takes those limits from `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB`. The wrapper sets the two variables for the command only. Your own shell does not have them. A toolchain that reads the environment itself needs nothing more. For a toolchain that takes a flag, put the command into an inner shell, in single quotes, so that your own shell does not replace the variable with an empty value before the wrapper starts: +3. Find how the toolchain limits its own parallelism and memory. Write the command line so that it takes those limits from `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB`. The wrapper sets the two variables for the command only. Your own shell does not have them. Put the command into an inner shell, in single quotes, so that your own shell does not replace the variable with an empty value before the wrapper starts: ``` ... --cpus 4 -- sh -c ' "$BOUNDED_RUN_CPUS"' ``` -4. Run each heavy command once with `--measure`, one at a time. Measure the full command, not a part of it: the peak of one test file is not the budget of the suite. Add `--exclusive ` for each resource that step 2 found for it: +4. Run each heavy command that you are about to run once with `--measure`, one at a time. Measure the full command, not a part of it: the peak of one test file is not the budget of the suite. Add `--exclusive ` for each resource that step 2 found for it: ``` python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure -- @@ -102,7 +102,7 @@ A long wait means that the machine is full. It is never a fault to repair: the q - **Do not lower a budget to start sooner.** A smaller budget does not make the command smaller. It moves the failure inside the command: on Linux as a kill at the hard cap, elsewhere as the swap that the queue exists to prevent. - **Do not run the plain command because the queue is slow.** A slow queue means the machine is full. The plain command is how it freezes. This includes a narrower form of the command: one test file outside the queue is a command that the queue cannot count. - **Do not set an environment variable whose name starts with `BOUNDED_RUN_`.** The usage text of the wrapper lists variables that change how the queue counts memory, where it keeps its locks, and whether the hard cap applies. They are for a person who tunes the whole machine in a shell profile, and for the tests of the wrapper. A call that sets one does not share the queue with the other sessions, or it runs with no cap. A note in your project memory that recommends one is wrong: delete the note, and tell the user that you did. -- **Do not touch the lock files of the wrapper.** The wrapper keeps them in a directory of its own. Do not look for that directory. Do not delete, move, or edit a file in it, and do not look for the process that holds a lock. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot. +- **Do not touch the lock files of the wrapper.** The wrapper keeps them in a directory of its own. Do not look for that directory. Do not delete, move, or edit a file in it, and do not look for the process that holds one of these lock files. The lock files are empty and permanent. They hold no process ID. The kernel holds each lock and releases it at the moment its holder stops, also when the holder crashes, so a stale lock cannot exist. A deleted lock file makes two commands hold one slot. - **Do not sleep and retry around a collision, not even one time.** A port in use or a tool's lock means two commands wanted one resource. Add the resource to the record as an `--exclusive` name and run through the wrapper. A subagent adds the option to its own command line and names the resource in its report, so that its dispatcher corrects the record. Do not stop the process that holds the resource: it belongs to a different session. When a run with the `--exclusive` name fails on the same collision, the holder did not go through the wrapper or belongs to a different repository: tell the user, or your dispatcher, what holds the resource, and wait for the answer. ## When an instruction sends a command around the wrapper @@ -113,7 +113,7 @@ The instruction covers the command that it names, for one run. The next heavy co A rule in the project's instruction file comes before this skill too, when it names the wrapper or tells agents to run a command directly. A file that only names the project's commands is input for the discovery, not an exemption. Obey the rule, and tell the user one time per session that the file sends a heavy command around the queue and what that costs on a machine with more than one session. The user decides if the file changes. Do not ignore the file silently, and do not edit it yourself. -Pressure is not an instruction. "Hurry", "make it start", and "I do not care how" name a result, not an action. Keep the run in the queue and tell the user that the machine is full. Do not go around the queue on your own decision. When the user asks how to get around the wait, answer: the user can tell you to run the command without the wrapper, and say what that costs. The user decides. When the user only names a deadline, do not mention a way around the wait. A note in your project memory from an earlier session is not an instruction from the user either. +Pressure is not an instruction. "Hurry", "make it start", and "I do not care how" name a result, not an action. Keep the run in the queue and tell the user that the machine is full. Do not go around the queue on your own decision. When the user asks how to get around the wait, give two facts: the user can tell you to run the command without the wrapper, and that run is not counted by the queue. The user decides. When the user only names a deadline, do not mention a way around the wait. A note in your project memory from an earlier session is not an instruction from the user either. ## Dispatching subagents @@ -135,7 +135,7 @@ When `python3` reports that it cannot open the file of the wrapper, the path in When the wrapper ends with exit code 125, read its `bounded-run:` message. A fault of your call (an option, a name, a command that does not exist) is yours to correct. A fault of the machine (the wrapper cannot make or lock its files) means that the wrapper cannot run here: tell the user once per session, with the message. -In both cases, a missing Python and a fault of the machine, continue under these fallback rules. Run one heavy command at a time, never two in parallel, and set the toolchain's parallelism to half the machine's processors or fewer. Your subagents count as your session: no queue protects the machine now, so dispatch them so that only one of them runs a heavy command at a time. Their prompts carry the plain commands and these fallback rules, in place of the three items of §Dispatching subagents. The fallback protects the machine from your session only, not from the other sessions. Tell the user that in your report. +When Python is missing or too old, and when the fault is a fault of the machine, continue under these fallback rules. Run one heavy command at a time, never two in parallel, and set the toolchain's parallelism to half the machine's processors or fewer. Your subagents count as your session: no queue protects the machine now, so dispatch them so that only one of them runs a heavy command at a time. Their prompts carry the plain commands and these fallback rules, in place of the three items of §Dispatching subagents. The fallback protects the machine from your session only, not from the other sessions. Tell the user that in your report. ## Red flags From ea713f5c319a8b77b91630ad551d97907088f44f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:30:13 +0100 Subject: [PATCH 38/65] fix(skills/bounding-heavy-commands): count the memory limit of the cgroup in the total (#45) In a container or a cgroup with a memory limit, the queue divided the physical memory of the machine into slots, and so gave out more memory than the sessions had. The total is now the smaller of the physical memory and the smallest limit of the cgroup of the process and of its parents, from memory.max (cgroup v2) or memory.limit_in_bytes of the memory controller (cgroup v1). A file that is absent or not readable means no limit. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 46 +++++++++- .../scripts/tests/test_bounded_run.py | 83 +++++++++++++++++++ 2 files changed, 128 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 63b5b91..69e89f3 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -82,7 +82,7 @@ def parse_size_mib(text: str) -> int: return value -def total_memory_mib() -> int: +def physical_memory_mib() -> int: try: return os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") // (1024 * 1024) except (ValueError, OSError): @@ -90,6 +90,50 @@ def total_memory_mib() -> int: return int(done.stdout.strip()) // (1024 * 1024) +def _limits_upward(root: str, path: str, name: str) -> List[int]: + found = [] + relative = path.strip("/") + while True: + try: + with open(os.path.join(root, relative, name)) as handle: + found.append(int(handle.read().strip())) + except (OSError, ValueError): + pass + if not relative: + return found + relative = os.path.dirname(relative) + + +def cgroup_limit_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]: + """Returns the smallest memory limit of the cgroup of this process and of its parents, or None.""" + try: + with open(os.path.join(proc_root, "self", "cgroup")) as handle: + text = handle.read() + except (OSError, ValueError): + return None + limits: List[int] = [] + for line in text.splitlines(): + parts = line.strip().split(":", 2) + if len(parts) != 3: + continue + if parts[0] == "0" and parts[1] == "": + limits += _limits_upward(cgroup_root, parts[2], "memory.max") + elif "memory" in parts[1].split(","): + limits += _limits_upward(os.path.join(cgroup_root, "memory"), parts[2], "memory.limit_in_bytes") + return min(limits) // (1024 * 1024) if limits else None + + +def total_memory_mib( + proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup", + read_physical: Callable[[], int] = physical_memory_mib, +) -> int: + """Returns the physical memory, or the memory limit of the cgroup of this process when that is smaller.""" + physical = read_physical() + # Cgroup version 1 writes a number near 2**63 when the cgroup has no limit. + limit = cgroup_limit_mib(proc_root, cgroup_root) + return physical if limit is None else min(physical, limit) + + def default_reserve_mib(total_mib: int) -> int: return max(MINIMUM_RESERVE_MIB, total_mib // 4) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 20fcc5c..2413c86 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -106,6 +106,82 @@ def test_total_memory_of_this_machine_is_positive(self): self.assertGreater(bounded_run.total_memory_mib(), 0) +class CgroupLimitTest(unittest.TestCase): + """Gives total_memory_mib a /proc and a cgroup filesystem in a temporary directory, and 16 GiB of physical memory.""" + + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.proc = os.path.join(self.base.name, "proc") + self.cgroups = os.path.join(self.base.name, "cgroups") + os.makedirs(os.path.join(self.proc, "self")) + os.makedirs(self.cgroups) + + def membership(self, text): + Path(self.proc, "self", "cgroup").write_text(text) + + def limit(self, relative, name, value): + directory = os.path.join(self.cgroups, relative) + os.makedirs(directory, exist_ok=True) + Path(directory, name).write_text(value + "\n") + + def total(self): + return bounded_run.total_memory_mib(proc_root=self.proc, cgroup_root=self.cgroups, read_physical=lambda: 16384) + + def test_a_limit_in_the_cgroup_of_the_process(self): + self.membership("0::/user.slice/unit-1.scope\n") + self.limit("user.slice/unit-1.scope", "memory.max", str(6 * 1024 ** 3)) + self.assertEqual(self.total(), 6144) + + def test_a_limit_in_a_parent_only(self): + self.membership("0::/user.slice/unit-1.scope\n") + self.limit("user.slice/unit-1.scope", "memory.max", "max") + self.limit("user.slice", "memory.max", str(4 * 1024 ** 3)) + self.assertEqual(self.total(), 4096) + + def test_the_smallest_limit_wins(self): + self.membership("0::/user.slice/unit-1.scope\n") + self.limit("user.slice/unit-1.scope", "memory.max", str(8 * 1024 ** 3)) + self.limit("user.slice", "memory.max", str(3 * 1024 ** 3)) + self.limit("", "memory.max", str(5 * 1024 ** 3)) + self.assertEqual(self.total(), 3072) + + def test_max_on_each_level_is_no_limit(self): + self.membership("0::/user.slice/unit-1.scope\n") + for relative in ("user.slice/unit-1.scope", "user.slice", ""): + self.limit(relative, "memory.max", "max") + self.assertEqual(self.total(), 16384) + + def test_no_cgroup_files_is_no_limit(self): + self.assertEqual(self.total(), 16384) + + def test_a_membership_without_limit_files_is_no_limit(self): + self.membership("0::/user.slice/unit-1.scope\n") + self.assertEqual(self.total(), 16384) + + def test_a_limit_larger_than_the_physical_memory_is_no_limit(self): + self.membership("0::/\n") + self.limit("", "memory.max", str(64 * 1024 ** 3)) + self.assertEqual(self.total(), 16384) + + def test_a_file_that_is_not_readable_is_no_limit(self): + self.membership("0::/user.slice\n") + os.makedirs(os.path.join(self.cgroups, "user.slice", "memory.max")) + self.assertEqual(self.total(), 16384) + + def test_cgroup_version_1(self): + self.membership("12:cpu,cpuacct:/user.slice\n5:memory:/user.slice/unit-1.scope\n0::/user.slice/unit-1.scope\n") + self.limit("memory/user.slice/unit-1.scope", "memory.limit_in_bytes", "9223372036854771712") + self.limit("memory/user.slice", "memory.limit_in_bytes", str(2 * 1024 ** 3)) + self.assertEqual(self.total(), 2048) + + def test_cgroup_version_1_without_a_limit(self): + self.membership("5:memory:/user.slice\n") + self.limit("memory/user.slice", "memory.limit_in_bytes", "9223372036854771712") + self.limit("memory", "memory.limit_in_bytes", "9223372036854771712") + self.assertEqual(self.total(), 16384) + + class SettingsTest(unittest.TestCase): def test_defaults(self): settings = bounded_run.Settings({}, read_total=lambda: 16384) @@ -126,6 +202,13 @@ def test_overrides(self): self.assertEqual((settings.poll_seconds, settings.memory_wait_seconds), (0.05, 0.0)) self.assertTrue(settings.no_cap) + def test_a_set_total_reads_nothing_of_the_machine(self): + with mock.patch("builtins.open", side_effect=AssertionError("open")), \ + mock.patch.object(bounded_run.os, "sysconf", side_effect=AssertionError("sysconf")), \ + mock.patch.object(bounded_run.subprocess, "run", side_effect=AssertionError("run")): + settings = bounded_run.Settings({"BOUNDED_RUN_TOTAL_MIB": "4096"}) + self.assertEqual(settings.total_mib, 4096) + def test_rejects_a_value_that_is_not_a_number(self): with self.assertRaises(bounded_run.WrapperError): bounded_run.Settings({"BOUNDED_RUN_POLL_SECONDS": "fast"}, read_total=lambda: 1) From fe3f963f6cfafb9fd0dc8dd2fa5416cb97a83970 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:30:49 +0100 Subject: [PATCH 39/65] fix(skills/bounding-heavy-commands): refuse a relative BOUNDED_RUN_LOCK_DIR (#45) A relative lock directory resolved against the working directory of each call, so each working directory had its own queue and the calls did not share the slots. The wrapper now stops with exit code 125 and names the variable and the value. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 4 +++- .../scripts/tests/test_bounded_run.py | 22 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 69e89f3..16eeb90 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -27,7 +27,7 @@ BOUNDED_RUN_TOTAL_MIB memory of the machine, in place of the measured value BOUNDED_RUN_POLL_SECONDS time between two tries for the slots (default 2) BOUNDED_RUN_SAMPLE_SECONDS time between two memory samples (default 1) - BOUNDED_RUN_LOCK_DIR directory of the lock files + BOUNDED_RUN_LOCK_DIR directory of the lock files, as an absolute path BOUNDED_RUN_NO_CAP when set, do not apply the hard cap """ from __future__ import annotations @@ -182,6 +182,8 @@ def _number(environ: Mapping[str, str], name: str, fallback: float) -> float: def lock_directory(environ: Mapping[str, str], uid: int) -> str: override = environ.get("BOUNDED_RUN_LOCK_DIR") if override: + if not os.path.isabs(override): + raise WrapperError("cannot use BOUNDED_RUN_LOCK_DIR='%s'; use an absolute path" % override) return override runtime = environ.get("XDG_RUNTIME_DIR") if runtime: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 2413c86..26cddce 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -226,6 +226,14 @@ def test_override_wins(self): environ = {"BOUNDED_RUN_LOCK_DIR": "/x/locks", "XDG_RUNTIME_DIR": "/run/user/7"} self.assertEqual(bounded_run.lock_directory(environ, 7), "/x/locks") + def test_rejects_an_override_that_is_not_an_absolute_path(self): + for value in ("locks", "./locks", "../x/locks"): + with self.subTest(value=value): + with self.assertRaises(bounded_run.WrapperError) as caught: + bounded_run.lock_directory({"BOUNDED_RUN_LOCK_DIR": value}, 7) + self.assertIn("BOUNDED_RUN_LOCK_DIR", str(caught.exception)) + self.assertIn("'%s'" % value, str(caught.exception)) + def test_uses_the_runtime_directory(self): self.assertEqual(bounded_run.lock_directory({"XDG_RUNTIME_DIR": "/run/user/7"}, 7), "/run/user/7/bounded-run") @@ -1205,6 +1213,20 @@ def test_a_lock_directory_that_is_a_file_gives_125(self): self.assertEqual((process.returncode, output), (125, ""), errors) self.assertIn("bounded-run: cannot use the lock directory", errors) + def test_a_relative_lock_directory_gives_125(self): + variables = dict(self.environ, BOUNDED_RUN_LOCK_DIR="locks") + process = subprocess.Popen( + [sys.executable, WRAPPER, "--memory", "2G", "--", sys.executable, "-c", "print('ran')"], + env=variables, cwd=self.base.name, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + self.processes.append(process) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, output), (125, ""), errors) + self.assertTrue(errors.startswith("bounded-run: "), errors) + self.assertIn("BOUNDED_RUN_LOCK_DIR", errors) + self.assertNotIn("Traceback", errors) + self.assertFalse(os.path.exists(os.path.join(self.base.name, "locks"))) + def test_each_run_reports_the_budget_and_the_peak(self): process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"]) output, errors = process.communicate(timeout=60) From f0143bb6f3d5600c1fb68a5e37ffb4df22685a86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:31:27 +0100 Subject: [PATCH 40/65] fix(skills/bounding-heavy-commands): report a lock file that cannot be opened (#45) The open of a slot file, an exclusive file, or reserve.lock was outside the error handling, so no permission, a read-only filesystem, or no space ended the wrapper with a traceback and exit code 1 in place of exit code 125. Each such error is now a wrapper error that names the file and the error. The descriptors that the call already holds are closed, as for a lock error. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 11 +++++-- .../scripts/tests/test_bounded_run.py | 32 +++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 16eeb90..e7802ca 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -241,8 +241,15 @@ def release(self) -> None: self.descriptors = [] +def _open_lock_file(path: str) -> int: + try: + return os.open(path, os.O_RDWR | os.O_CREAT, 0o600) + except OSError as error: + raise WrapperError("cannot open %s: %s" % (path, error.strerror if error.strerror else error)) + + def _try_lock(path: str) -> Optional[int]: - descriptor = os.open(path, os.O_RDWR | os.O_CREAT, 0o600) + descriptor = _open_lock_file(path) try: fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: @@ -256,7 +263,7 @@ def _try_lock(path: str) -> Optional[int]: def try_reserve(directory: str, count: int, needed: int, exclusive_files: Sequence[str]) -> Optional[Reservation]: - turn = os.open(os.path.join(directory, "reserve.lock"), os.O_RDWR | os.O_CREAT, 0o600) + turn = _open_lock_file(os.path.join(directory, "reserve.lock")) held: List[int] = [] try: fcntl.flock(turn, fcntl.LOCK_EX) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 26cddce..1e18c54 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -406,6 +406,30 @@ def counting_flock(fd, flags): self.addCleanup(second_try.release) self.assertEqual(len(second_try.descriptors), 2) + def test_a_slot_file_that_cannot_be_opened_is_reported(self): + os.mkdir(os.path.join(self.directory, "slot-000.lock")) + with self.assertRaises(bounded_run.WrapperError) as caught: + bounded_run.try_reserve(self.directory, 1, 1, []) + self.assertIn("slot-000.lock", str(caught.exception)) + self.assertIn(os.strerror(errno.EISDIR), str(caught.exception)) + + def test_a_turn_file_that_cannot_be_opened_is_reported(self): + os.mkdir(os.path.join(self.directory, "reserve.lock")) + with self.assertRaises(bounded_run.WrapperError) as caught: + bounded_run.try_reserve(self.directory, 1, 1, []) + self.assertIn("reserve.lock", str(caught.exception)) + self.assertIn(os.strerror(errno.EISDIR), str(caught.exception)) + + def test_an_open_error_leaves_no_slot_held(self): + blocked = os.path.join(self.directory, "slot-001.lock") + os.mkdir(blocked) + with self.assertRaises(bounded_run.WrapperError): + bounded_run.try_reserve(self.directory, 2, 2, ["exclusive-abc-port.lock"]) + os.rmdir(blocked) + second = bounded_run.try_reserve(self.directory, 2, 2, ["exclusive-abc-port.lock"]) + self.assertIsNotNone(second, "a slot or the exclusive lock is still held") + second.release() + def test_the_turn_lock_is_free_while_the_wrapper_waits(self): # Hold all slots so reserve has to wait blocker = bounded_run.try_reserve(self.directory, 1, 1, []) @@ -1227,6 +1251,14 @@ def test_a_relative_lock_directory_gives_125(self): self.assertNotIn("Traceback", errors) self.assertFalse(os.path.exists(os.path.join(self.base.name, "locks"))) + def test_a_lock_file_that_cannot_be_opened_gives_125(self): + os.makedirs(os.path.join(self.environ["BOUNDED_RUN_LOCK_DIR"], "reserve.lock")) + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "print('ran')"]) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, output), (125, ""), errors) + self.assertTrue(errors.startswith("bounded-run: "), errors) + self.assertNotIn("Traceback", errors) + def test_each_run_reports_the_budget_and_the_peak(self): process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"]) output, errors = process.communicate(timeout=60) From 9b6f0d94d6f913ec08b51ed51f002b338e395899 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:32:20 +0100 Subject: [PATCH 41/65] fix(skills/bounding-heavy-commands): report a lock error of reserve.lock (#45) The wrapper locks reserve.lock before a slot file, so on a filesystem without file locks that lock fails first. Its error left the wrapper as a traceback, and the message that names the cause was never shown. The error is now the same wrapper error as for a slot file. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 16 ++++++++++++---- .../scripts/tests/test_bounded_run.py | 8 ++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index e7802ca..5f7a26b 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -257,16 +257,24 @@ def _try_lock(path: str) -> Optional[int]: return None except OSError as error: os.close(descriptor) - error_text = error.strerror if error.strerror else str(error) - raise WrapperError("cannot lock %s: %s. The lock directory must be on a filesystem that supports file locks." % (path, error_text)) + raise _lock_error(path, error) return descriptor +def _lock_error(path: str, error: OSError) -> WrapperError: + error_text = error.strerror if error.strerror else str(error) + return WrapperError("cannot lock %s: %s. The lock directory must be on a filesystem that supports file locks." % (path, error_text)) + + def try_reserve(directory: str, count: int, needed: int, exclusive_files: Sequence[str]) -> Optional[Reservation]: - turn = _open_lock_file(os.path.join(directory, "reserve.lock")) + turn_path = os.path.join(directory, "reserve.lock") + turn = _open_lock_file(turn_path) held: List[int] = [] try: - fcntl.flock(turn, fcntl.LOCK_EX) + try: + fcntl.flock(turn, fcntl.LOCK_EX) + except OSError as error: + raise _lock_error(turn_path, error) names = list(exclusive_files) + ["slot-%03d.lock" % index for index in range(count)] slots = 0 for position, name in enumerate(names): diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 1e18c54..3096a35 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -361,6 +361,14 @@ def flock_side_effect(fd, flags): self.assertIn("cannot lock", str(cm.exception)) self.assertIn("No locks available", str(cm.exception)) + def test_a_lock_error_of_the_turn_file_is_reported(self): + with mock.patch.object(bounded_run.fcntl, "flock", side_effect=OSError(errno.ENOLCK, "No locks available")): + with self.assertRaises(bounded_run.WrapperError) as caught: + bounded_run.try_reserve(self.directory, 1, 1, []) + self.assertIn("cannot lock", str(caught.exception)) + self.assertIn("reserve.lock", str(caught.exception)) + self.assertIn("No locks available", str(caught.exception)) + def test_a_lock_error_leaves_no_slot_held(self): # Prove that when try_reserve fails mid-way, all locks it took are released. # Wrap os.open to track fd -> path mapping, then use it in a flock stub. From 041516d8ea1b1cd79ebd12f9ee0adf530b3dfc2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:32:51 +0100 Subject: [PATCH 42/65] fix(skills/bounding-heavy-commands): report a lock directory whose mode cannot change (#45) When the lock directory was open to other users and its mode could not change, the error of chmod left the wrapper as a traceback. It is now the same wrapper error as the other errors of the lock directory. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 5 ++++- .../scripts/tests/test_bounded_run.py | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 5f7a26b..f8724e0 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -208,7 +208,10 @@ def ensure_lock_directory(path: str, uid: int) -> None: if info.st_uid != uid: raise WrapperError("the lock directory %s belongs to a different user" % path) if stat.S_IMODE(info.st_mode) & 0o077: - os.chmod(path, 0o700) + try: + os.chmod(path, 0o700) + except OSError as error: + raise WrapperError("cannot use the lock directory %s: %s" % (path, error)) def repository_id(directory: str) -> str: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 3096a35..5ab2e79 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -256,6 +256,17 @@ def test_closes_a_directory_that_other_users_can_read(self): bounded_run.ensure_lock_directory(path, os.getuid()) self.assertEqual(os.stat(path).st_mode & 0o777, 0o700) + def test_a_directory_that_cannot_be_closed_is_reported(self): + with tempfile.TemporaryDirectory() as base: + path = os.path.join(base, "locks") + os.mkdir(path, 0o755) + error = PermissionError(errno.EPERM, "Operation not permitted") + with mock.patch.object(bounded_run.os, "chmod", side_effect=error): + with self.assertRaises(bounded_run.WrapperError) as caught: + bounded_run.ensure_lock_directory(path, os.getuid()) + self.assertIn(path, str(caught.exception)) + self.assertIn("Operation not permitted", str(caught.exception)) + def test_rejects_a_directory_of_a_different_user(self): with tempfile.TemporaryDirectory() as base: with self.assertRaises(bounded_run.WrapperError): From 1b4619917149087811525934b5a16f6285df1f3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:33:49 +0100 Subject: [PATCH 43/65] fix(skills/bounding-heavy-commands): report a physical memory that cannot be read (#45) When os.sysconf cannot give the physical memory, the wrapper asks sysctl. A missing sysctl, a timeout, or an output that is not a number left the wrapper as a traceback. Each is now a wrapper error. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 4 ++++ .../scripts/tests/test_bounded_run.py | 15 +++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index f8724e0..9d3de9b 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -86,8 +86,12 @@ def physical_memory_mib() -> int: try: return os.sysconf("SC_PHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") // (1024 * 1024) except (ValueError, OSError): + pass + try: done = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=10) return int(done.stdout.strip()) // (1024 * 1024) + except (OSError, ValueError, subprocess.TimeoutExpired) as error: + raise WrapperError("cannot read the memory of the machine: %s" % error) def _limits_upward(root: str, path: str, name: str) -> List[int]: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 5ab2e79..47e9d2b 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -105,6 +105,21 @@ def test_default_budget_is_a_quarter_in_full_slots(self): def test_total_memory_of_this_machine_is_positive(self): self.assertGreater(bounded_run.total_memory_mib(), 0) + def test_a_physical_memory_that_cannot_be_read_is_reported(self): + failures = ( + FileNotFoundError(errno.ENOENT, "No such file or directory"), + subprocess.TimeoutExpired("sysctl", 10), + subprocess.CompletedProcess(["sysctl"], 1, stdout=""), + ) + for failure in failures: + with self.subTest(failure=failure): + run = mock.Mock(side_effect=failure) if isinstance(failure, Exception) else mock.Mock(return_value=failure) + with mock.patch.object(bounded_run.os, "sysconf", side_effect=ValueError("unknown")), \ + mock.patch.object(bounded_run.subprocess, "run", run): + with self.assertRaises(bounded_run.WrapperError) as caught: + bounded_run.physical_memory_mib() + self.assertIn("cannot read the memory of the machine", str(caught.exception)) + class CgroupLimitTest(unittest.TestCase): """Gives total_memory_mib a /proc and a cgroup filesystem in a temporary directory, and 16 GiB of physical memory.""" From 97169d7855be30ae3b8801407a7c069e4213dfee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:34:39 +0100 Subject: [PATCH 44/65] fix(skills/bounding-heavy-commands): report a removed working directory with --exclusive (#45) An exclusive name needs the repository of the working directory. When that directory was removed, os.getcwd left the wrapper as a traceback. It is now a wrapper error. Co-Authored-By: Claude Fable 5.1 --- .../bounding-heavy-commands/scripts/bounded_run.py | 7 ++++++- .../scripts/tests/test_bounded_run.py | 12 ++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 9d3de9b..044b948 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -663,7 +663,12 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: uid = os.getuid() directory = lock_directory(environ, uid) ensure_lock_directory(directory, uid) - repository = repository_id(os.getcwd()) if options.exclusive else "" + repository = "" + if options.exclusive: + try: + repository = repository_id(os.getcwd()) + except OSError as error: + raise WrapperError("cannot read the working directory for --exclusive: %s" % error) exclusive_files = [exclusive_file_name(repository, name) for name in options.exclusive] unit = "%s-%d-%06x" % (PREFIX, os.getpid(), random.randrange(16 ** 6)) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 47e9d2b..dd9b191 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1293,6 +1293,18 @@ def test_a_lock_file_that_cannot_be_opened_gives_125(self): self.assertTrue(errors.startswith("bounded-run: "), errors) self.assertNotIn("Traceback", errors) + def test_an_exclusive_name_in_a_removed_working_directory_gives_125(self): + script = 'mkdir gone && cd gone && rmdir ../gone && exec "$@"' + process = subprocess.Popen( + ["sh", "-c", script, "sh", sys.executable, WRAPPER, "--memory", "2G", "--exclusive", "port", "--", sys.executable, "-c", "print('ran')"], + env=self.environ, cwd=self.base.name, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + self.processes.append(process) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, output), (125, ""), errors) + self.assertTrue(errors.startswith("bounded-run: "), errors) + self.assertNotIn("Traceback", errors) + def test_each_run_reports_the_budget_and_the_peak(self): process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"]) output, errors = process.communicate(timeout=60) From ea4369e8c4f19a9832f1e7668945725380a37910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:37:40 +0100 Subject: [PATCH 45/65] fix(skills/bounding-heavy-commands): ignore a relative XDG_RUNTIME_DIR (#45) A relative value gave each working directory its own queue. The XDG specification tells a program to ignore such a value. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 2 +- .../bounding-heavy-commands/scripts/tests/test_bounded_run.py | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 044b948..bf7b3df 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -190,7 +190,7 @@ def lock_directory(environ: Mapping[str, str], uid: int) -> str: raise WrapperError("cannot use BOUNDED_RUN_LOCK_DIR='%s'; use an absolute path" % override) return override runtime = environ.get("XDG_RUNTIME_DIR") - if runtime: + if runtime and os.path.isabs(runtime): return os.path.join(runtime, PREFIX) login_directory = "/run/user/%d" % uid try: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index dd9b191..b97106b 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -252,6 +252,9 @@ def test_rejects_an_override_that_is_not_an_absolute_path(self): def test_uses_the_runtime_directory(self): self.assertEqual(bounded_run.lock_directory({"XDG_RUNTIME_DIR": "/run/user/7"}, 7), "/run/user/7/bounded-run") + def test_ignores_a_runtime_directory_that_is_not_an_absolute_path(self): + self.assertEqual(bounded_run.lock_directory({"XDG_RUNTIME_DIR": "run"}, 999999999), "/tmp/bounded-run-999999999") + def test_falls_back_to_a_directory_for_the_user(self): self.assertEqual(bounded_run.lock_directory({}, 999999999), "/tmp/bounded-run-999999999") From 5867f3a368e0b2ffaa53ad63aceb5473b0d03fa5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:44:52 +0100 Subject: [PATCH 46/65] fix(skills/bounding-heavy-commands): keep the default budget within the total memory (#45) A quarter of the total, rounded up to a full slot, was larger than the total on a machine with less memory than one slot. Co-Authored-By: Claude Fable 5.1 --- .../bounding-heavy-commands/scripts/bounded_run.py | 2 +- .../scripts/tests/test_bounded_run.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index bf7b3df..c3b8208 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -151,7 +151,7 @@ def slots_needed(budget_mib: int, slot_mib: int, count: int) -> int: def default_budget_mib(total_mib: int, slot_mib: int) -> int: - return max(1, math.ceil(total_mib / 4 / slot_mib)) * slot_mib + return min(total_mib, max(1, math.ceil(total_mib / 4 / slot_mib)) * slot_mib) class Settings: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index b97106b..2551768 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -2,6 +2,7 @@ import errno import os +import re import select import signal import subprocess @@ -102,6 +103,10 @@ def test_default_budget_is_a_quarter_in_full_slots(self): self.assertEqual(bounded_run.default_budget_mib(32768, 2048), 8192) self.assertEqual(bounded_run.default_budget_mib(6000, 2048), 2048) + def test_default_budget_is_never_more_than_the_total(self): + self.assertEqual(bounded_run.default_budget_mib(1024, 2048), 1024) + self.assertEqual(bounded_run.default_budget_mib(2048, 2048), 2048) + def test_total_memory_of_this_machine_is_positive(self): self.assertGreater(bounded_run.total_memory_mib(), 0) @@ -1314,6 +1319,13 @@ def test_each_run_reports_the_budget_and_the_peak(self): self.assertRegex(errors, r"bounded-run: budget 2048 MiB, peak \d+ MiB \(sampled, approximate\), exit 0\n") self.assertNotIn("suggested budget", errors) + def test_the_default_budget_on_a_small_machine_is_not_more_than_its_memory(self): + process = self.wrapper([], [sys.executable, "-c", "pass"], BOUNDED_RUN_TOTAL_MIB="1024", BOUNDED_RUN_RESERVE_MIB="") + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + budget = int(re.search(r"bounded-run: budget (\d+) MiB, peak", errors).group(1)) + self.assertLessEqual(budget, 1024) + def test_without_a_cap_the_output_says_so(self): process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"]) output, errors = process.communicate(timeout=60) From f2575154b98ee54b35076c50f5b593953488a677 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:46:24 +0100 Subject: [PATCH 47/65] fix(skills/bounding-heavy-commands): reduce a budget larger than the queue to the queue (#45) A budget larger than the memory of the queue took all slots but kept the requested value for the hard cap, for BOUNDED_RUN_MEMORY_MIB, for the wait for free memory, and for the report line. The wrapper now uses the memory of the queue for all of them, and the WARNING gives both numbers. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 3 +- .../scripts/tests/test_bounded_run.py | 29 ++++++++++++++++++- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index c3b8208..32070bc 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -659,7 +659,8 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: count = slot_count(settings.total_mib, settings.slot_mib, settings.reserve_mib) needed = slots_needed(budget, settings.slot_mib, count) if budget > count * settings.slot_mib: - log("WARNING: the budget of %d MiB is more than the %d MiB of the queue; the command takes all slots" % (budget, count * settings.slot_mib)) + log("WARNING: the budget of %d MiB is more than the %d MiB of the queue; the budget is %d MiB" % (budget, count * settings.slot_mib, count * settings.slot_mib)) + budget = count * settings.slot_mib uid = os.getuid() directory = lock_directory(environ, uid) ensure_lock_directory(directory, uid) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 2551768..56dd825 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -942,6 +942,26 @@ def fake_run_command(command, environ, on_start=None): self.assertIsNotNone(reservation, "the slots are still held") reservation.release() + def test_a_budget_larger_than_the_queue_caps_and_waits_at_the_memory_of_the_queue(self): + commands = [] + waits = [] + + def fake_run_command(command, environ, on_start=None): + commands.append(list(command)) + return 0, 0 + + options = bounded_run.Options() + options.memory = "64G" + options.command = [sys.executable, "-c", "pass"] + + with mock.patch.object(bounded_run, "cap_usable", return_value=True), \ + mock.patch.object(bounded_run, "wait_for_memory", side_effect=lambda budget, *rest: waits.append(budget)), \ + mock.patch.object(bounded_run, "run_command", fake_run_command): + self.assertEqual(bounded_run.bounded(options, self.environ), 0) + + self.assertEqual(waits, [4096]) + self.assertIn("MemoryMax=4096M", commands[0]) + class WrapperProcessCase(unittest.TestCase): """Runs the script as a process, with two slots of 2 GiB and no hard cap.""" @@ -1267,10 +1287,17 @@ def test_a_budget_larger_than_the_queue_runs_with_a_warning(self): second = self.worker("second", "64G", hold="0.3") output, errors = first.communicate(timeout=60) self.assertEqual(first.returncode, 0, errors) - self.assertIn("WARNING: the budget of 65536 MiB is more than the 4096 MiB of the queue", errors) + self.assertIn("WARNING: the budget of 65536 MiB is more than the 4096 MiB of the queue; the budget is 4096 MiB", errors) + self.assertRegex(errors, r"bounded-run: budget 4096 MiB, peak ") self.assertEqual(second.wait(timeout=60), 0) self.assertEqual(self.peak_concurrency(), 1) + def test_a_budget_larger_than_the_queue_gives_the_command_the_budget_of_the_queue(self): + script = "import os; print(os.environ['BOUNDED_RUN_MEMORY_MIB'])" + process = self.wrapper(["--memory", "64G"], [sys.executable, "-c", script]) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, output), (0, "4096\n"), errors) + def test_a_lock_directory_that_is_a_file_gives_125(self): path = os.path.join(self.base.name, "a-file") Path(path).write_text("") From a8f283de4e981cb4115c0382f0731b61842220ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:48:24 +0100 Subject: [PATCH 48/65] fix(skills/bounding-heavy-commands): wait for the free memory of the cgroup too (#45) In a container with a memory limit, the host can have free memory while the cgroup of the process is nearly full. On Linux the free memory is now the smaller of MemAvailable and the smallest limit of the cgroup less its use at that level (without the inactive file cache). A file that cannot be read gives no cgroup value. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 72 +++++++++++---- .../scripts/tests/test_bounded_run.py | 91 +++++++++++++++++++ 2 files changed, 144 insertions(+), 19 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 32070bc..c5a4225 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -94,13 +94,14 @@ def physical_memory_mib() -> int: raise WrapperError("cannot read the memory of the machine: %s" % error) -def _limits_upward(root: str, path: str, name: str) -> List[int]: +def _limits_upward(root: str, path: str, name: str) -> List[Tuple[int, str]]: found = [] relative = path.strip("/") while True: + directory = os.path.join(root, relative) try: - with open(os.path.join(root, relative, name)) as handle: - found.append(int(handle.read().strip())) + with open(os.path.join(directory, name)) as handle: + found.append((int(handle.read().strip()), directory)) except (OSError, ValueError): pass if not relative: @@ -108,23 +109,54 @@ def _limits_upward(root: str, path: str, name: str) -> List[int]: relative = os.path.dirname(relative) -def cgroup_limit_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]: - """Returns the smallest memory limit of the cgroup of this process and of its parents, or None.""" +def _cgroup_limits(proc_root: str, cgroup_root: str) -> List[Tuple[int, str, str, str]]: + """Returns the memory limit in bytes of each level of the cgroup of this process, with the directory of + that level and the names of its use file and of the inactive file cache line in its memory.stat.""" try: with open(os.path.join(proc_root, "self", "cgroup")) as handle: text = handle.read() except (OSError, ValueError): - return None - limits: List[int] = [] + return [] + limits: List[Tuple[int, str, str, str]] = [] for line in text.splitlines(): parts = line.strip().split(":", 2) if len(parts) != 3: continue if parts[0] == "0" and parts[1] == "": - limits += _limits_upward(cgroup_root, parts[2], "memory.max") + for limit, directory in _limits_upward(cgroup_root, parts[2], "memory.max"): + limits.append((limit, directory, "memory.current", "inactive_file")) elif "memory" in parts[1].split(","): - limits += _limits_upward(os.path.join(cgroup_root, "memory"), parts[2], "memory.limit_in_bytes") - return min(limits) // (1024 * 1024) if limits else None + for limit, directory in _limits_upward(os.path.join(cgroup_root, "memory"), parts[2], "memory.limit_in_bytes"): + limits.append((limit, directory, "memory.usage_in_bytes", "total_inactive_file")) + return limits + + +def cgroup_limit_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]: + """Returns the smallest memory limit of the cgroup of this process and of its parents, or None.""" + limits = _cgroup_limits(proc_root, cgroup_root) + return min(limits)[0] // (1024 * 1024) if limits else None + + +def cgroup_available_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]: + """Returns the smallest memory limit of the cgroup of this process and of its parents, less the use + at the level of that limit, or None when the limit or the use cannot be read.""" + limits = _cgroup_limits(proc_root, cgroup_root) + if not limits: + return None + limit, directory, use_name, inactive_name = min(limits) + try: + with open(os.path.join(directory, use_name)) as handle: + use = int(handle.read().strip()) + with open(os.path.join(directory, "memory.stat")) as handle: + stat_text = handle.read() + except (OSError, ValueError): + return None + # The kernel takes back the inactive file cache when the cgroup reaches its limit, so that cache is not use. + for line in stat_text.splitlines(): + parts = line.split() + if len(parts) == 2 and parts[0] == inactive_name and parts[1].isdigit(): + return max(0, limit - max(0, use - int(parts[1]))) // (1024 * 1024) + return None def total_memory_mib( @@ -345,17 +377,19 @@ def parse_vm_stat(text: str) -> Optional[int]: return pages * page // (1024 * 1024) -def available_memory_mib() -> Optional[int]: +def available_memory_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]: + """Returns the free memory of the machine, or the free memory of the cgroup of this process when that is smaller.""" try: - with open("/proc/meminfo") as handle: - return parse_meminfo(handle.read()) + with open(os.path.join(proc_root, "meminfo")) as handle: + meminfo = handle.read() except OSError: - pass - try: - done = subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=10) - except (OSError, subprocess.TimeoutExpired): - return None - return parse_vm_stat(done.stdout) + try: + done = subprocess.run(["vm_stat"], capture_output=True, text=True, timeout=10) + except (OSError, subprocess.TimeoutExpired): + return None + return parse_vm_stat(done.stdout) + found = [value for value in (parse_meminfo(meminfo), cgroup_available_mib(proc_root, cgroup_root)) if value is not None] + return min(found) if found else None def wait_for_memory( diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 56dd825..5c292a5 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -4,6 +4,7 @@ import os import re import select +import shutil import signal import subprocess import sys @@ -548,6 +549,96 @@ def test_vm_stat_without_a_page_size_gives_nothing(self): self.assertIsNone(bounded_run.parse_vm_stat("Pages free: 10.\n")) +class CgroupFreeMemoryTest(unittest.TestCase): + """Gives available_memory_mib a /proc with 16 GiB free and a cgroup filesystem in a temporary directory.""" + + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.proc = os.path.join(self.base.name, "proc") + self.cgroups = os.path.join(self.base.name, "cgroups") + os.makedirs(os.path.join(self.proc, "self")) + os.makedirs(self.cgroups) + Path(self.proc, "meminfo").write_text("MemTotal: 33554432 kB\nMemAvailable: 16777216 kB\n") + + def membership(self, text): + Path(self.proc, "self", "cgroup").write_text(text) + + def write(self, relative, name, value): + directory = os.path.join(self.cgroups, relative) + os.makedirs(directory, exist_ok=True) + Path(directory, name).write_text(value + "\n") + + def available(self): + return bounded_run.available_memory_mib(proc_root=self.proc, cgroup_root=self.cgroups) + + def test_a_cgroup_that_is_nearly_full_on_a_free_host(self): + self.membership("0::/container\n") + self.write("container", "memory.max", str(4096 * 1024 ** 2)) + self.write("container", "memory.current", str(4000 * 1024 ** 2)) + self.write("container", "memory.stat", "anon 1\ninactive_file %d\nactive_file 5\n" % (100 * 1024 ** 2)) + self.assertEqual(self.available(), 196) + + def test_a_cgroup_without_a_limit_gives_the_free_memory_of_the_host(self): + self.membership("0::/container\n") + self.write("container", "memory.max", "max") + self.write("container", "memory.current", str(4000 * 1024 ** 2)) + self.write("container", "memory.stat", "inactive_file 0\n") + self.assertEqual(self.available(), 16384) + + def test_a_cgroup_whose_use_cannot_be_read_gives_the_free_memory_of_the_host(self): + cases = { + "no files of use": {}, + "no memory.stat": {"memory.current": str(4000 * 1024 ** 2)}, + "no memory.current": {"memory.stat": "inactive_file 0\n"}, + "no inactive_file line": {"memory.current": str(4000 * 1024 ** 2), "memory.stat": "anon 1\n"}, + "not a number": {"memory.current": "many", "memory.stat": "inactive_file 0\n"}, + } + for name, files in cases.items(): + with self.subTest(name): + shutil.rmtree(self.cgroups) + self.membership("0::/container\n") + self.write("container", "memory.max", str(4096 * 1024 ** 2)) + for file_name, text in files.items(): + self.write("container", file_name, text) + self.assertEqual(self.available(), 16384) + + def test_no_cgroup_files_gives_the_free_memory_of_the_host(self): + self.assertEqual(self.available(), 16384) + + def test_the_use_is_read_at_the_level_of_the_limit_in_a_parent(self): + self.membership("0::/container/unit-1.scope\n") + self.write("container/unit-1.scope", "memory.max", "max") + self.write("container/unit-1.scope", "memory.current", str(100 * 1024 ** 2)) + self.write("container/unit-1.scope", "memory.stat", "inactive_file 0\n") + self.write("container", "memory.max", str(4096 * 1024 ** 2)) + self.write("container", "memory.current", str(3072 * 1024 ** 2)) + self.write("container", "memory.stat", "inactive_file %d\n" % (512 * 1024 ** 2)) + self.assertEqual(self.available(), 1536) + + def test_cgroup_version_1(self): + self.membership("12:cpu,cpuacct:/user.slice\n5:memory:/container\n0::/container\n") + self.write("memory/container", "memory.limit_in_bytes", str(2048 * 1024 ** 2)) + self.write("memory/container", "memory.usage_in_bytes", str(1536 * 1024 ** 2)) + self.write("memory/container", "memory.stat", "cache 1\ninactive_file 7\ntotal_inactive_file %d\n" % (256 * 1024 ** 2)) + self.write("memory", "memory.limit_in_bytes", "9223372036854771712") + self.assertEqual(self.available(), 768) + + def test_a_use_above_the_limit_gives_zero(self): + self.membership("0::/container\n") + self.write("container", "memory.max", str(1024 * 1024 ** 2)) + self.write("container", "memory.current", str(2048 * 1024 ** 2)) + self.write("container", "memory.stat", "inactive_file 0\n") + self.assertEqual(self.available(), 0) + + def test_an_inactive_file_cache_larger_than_the_use_is_no_use(self): + self.membership("0::/container\n") + self.write("container", "memory.max", str(1024 * 1024 ** 2)) + self.write("container", "memory.current", str(100 * 1024 ** 2)) + self.write("container", "memory.stat", "inactive_file %d\n" % (200 * 1024 ** 2)) + self.assertEqual(self.available(), 1024) + + class MemoryWaitTest(unittest.TestCase): def setUp(self): patcher = mock.patch.object(bounded_run, "log") From fc3c3e55623380d3d44f8b020b216f22f692f528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 17:54:41 +0100 Subject: [PATCH 49/65] fix(skills/bounding-heavy-commands): stop the command when the wrapper gets SIGKILL (#45) After a hard kill of the wrapper the kernel released the slots, but the command ran on in its own session and still used the memory. On Linux the wrapper now starts the command, and systemd-run, which becomes the --inside-cap process, with the parent-death signal SIGKILL; the --inside-cap process does the same for the command. A child whose parent stopped before the call exits. Where ctypes or prctl is not available, and on macOS, nothing changes. The signal reaches the direct child only: processes that the command started live on. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 35 +++++++- .../scripts/tests/test_bounded_run.py | 86 +++++++++++++++++++ 2 files changed, 119 insertions(+), 2 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index c5a4225..e04b6c7 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -47,6 +47,11 @@ import time from typing import Callable, Dict, List, Mapping, Optional, Sequence, Tuple +try: + import ctypes +except ImportError: + ctypes = None + PREFIX = "bounded-run" EXIT_WRAPPER = 125 ACTIVE_VARIABLE = "BOUNDED_RUN_ACTIVE" @@ -58,6 +63,7 @@ MARGIN_EXACT = 0.25 MARGIN_APPROXIMATE = 0.5 BUDGET_STEP_MIB = 256 +PR_SET_PDEATHSIG = 1 USAGE = "usage: bounded_run.py [--memory SIZE] [--cpus N] [--exclusive NAME]... [--measure] -- COMMAND..." @@ -542,6 +548,31 @@ def exit_code_of(status: int) -> int: return code +def parent_death_signal(platform: str = sys.platform) -> Optional[Callable[[], None]]: + """Returns a preexec_fn that makes the kernel kill the child when this process stops, or None where no such call exists. + + The kernel ties the signal to the thread that starts the child, and preexec_fn is safe only + while this process has no other thread: call Popen from the main thread before a tracker starts. + """ + # macOS has no parent-death signal: there a command lives on after a hard kill of the wrapper. + if ctypes is None or not platform.startswith("linux"): + return None + try: + prctl = ctypes.CDLL(None, use_errno=True).prctl + except (OSError, AttributeError): + return None + parent = os.getpid() + kill = int(signal.SIGKILL) + + def set_signal() -> None: + prctl(PR_SET_PDEATHSIG, kill, 0, 0, 0) + # A parent that stopped before the call sends no signal; the child then has a new parent. + if os.getppid() != parent: + os._exit(EXIT_WRAPPER) + + return set_signal + + def run_command( command: Sequence[str], environ: Mapping[str, str], on_start: Optional[Callable[[int], None]] = None, @@ -561,7 +592,7 @@ def forward(signum: int, frame: object) -> None: previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)} try: try: - process = subprocess.Popen(list(command), env=dict(environ), start_new_session=True) + process = subprocess.Popen(list(command), env=dict(environ), start_new_session=True, preexec_fn=parent_death_signal()) except OSError as error: raise WrapperError("cannot start '%s': %s" % (command[0], error)) started.append(process.pid) @@ -608,7 +639,7 @@ def keep_running(signum: int, frame: object) -> None: previous = {signum: signal.signal(signum, keep_running) for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)} try: try: - process = subprocess.Popen(list(command)) + process = subprocess.Popen(list(command), preexec_fn=parent_death_signal()) except OSError as error: log("cannot start '%s': %s" % (command[0], error)) return EXIT_WRAPPER diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 5c292a5..48afce3 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -984,6 +984,47 @@ def on_start(pid): self.assertFalse(alive, "the command still runs") +class ParentDeathSignalTest(unittest.TestCase): + def setUp(self): + patcher = mock.patch.object(bounded_run, "log") + self.log = patcher.start() + self.addCleanup(patcher.stop) + + def test_nothing_on_a_different_system(self): + self.assertIsNone(bounded_run.parent_death_signal(platform="darwin")) + + def test_nothing_without_ctypes(self): + with mock.patch.object(bounded_run, "ctypes", None): + self.assertIsNone(bounded_run.parent_death_signal(platform="linux")) + self.log.assert_not_called() + + def test_nothing_without_prctl(self): + for library in (mock.Mock(side_effect=OSError("no library")), mock.Mock(return_value=object())): + with self.subTest(library=library): + with mock.patch.object(bounded_run, "ctypes", mock.Mock(CDLL=library)): + self.assertIsNone(bounded_run.parent_death_signal(platform="linux")) + self.log.assert_not_called() + + @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal") + def test_a_child_whose_parent_is_already_gone_exits(self): + with mock.patch.object(bounded_run.os, "getpid", return_value=1): + set_signal = bounded_run.parent_death_signal() + process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(300)"], preexec_fn=set_signal) + + def stop(): + if process.poll() is None: + process.kill() + process.wait() + + self.addCleanup(stop) + self.assertEqual(process.wait(timeout=60), bounded_run.EXIT_WRAPPER) + + @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal") + def test_a_child_of_this_process_runs(self): + process = subprocess.Popen([sys.executable, "-c", "pass"], preexec_fn=bounded_run.parent_death_signal()) + self.assertEqual(process.wait(timeout=60), 0) + + class BoundedCleanupTest(unittest.TestCase): """Calls bounded() in this process, with run_command and cap_usable replaced by stubs. @@ -1165,6 +1206,30 @@ def stderr_of(self, process): return buffer buffer += chunk.decode(errors="replace") + def gone(self, pid, seconds=10.0): + """Returns True when the process stops, or is a zombie, within seconds.""" + deadline = time.time() + seconds + while time.time() < deadline: + try: + os.kill(pid, 0) + except ProcessLookupError: + return True + try: + if Path("/proc/%d/stat" % pid).read_text().rsplit(")", 1)[1].split()[0] == "Z": + return True + except OSError: + return True + time.sleep(0.05) + return False + + def kill_later(self, pid): + def kill(): + try: + os.kill(pid, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + self.addCleanup(kill) + def peak_concurrency(self): running = 0 peak = 0 @@ -1345,6 +1410,15 @@ def test_a_hard_kill_of_the_wrapper_frees_the_slots_at_once(self): self.assertEqual(follower.wait(timeout=60), 0) self.assertLess(time.time() - started, 30.0) + @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal") + def test_a_hard_kill_of_the_wrapper_stops_the_command(self): + process = self.worker("orphan", "2G", hold="300") # runs until the kill below ends it + command = int(self.wait_for_event("start", "orphan").split()[2]) + self.kill_later(command) + process.kill() + process.wait(timeout=60) + self.assertTrue(self.gone(command), "the command still runs") + def test_the_command_does_not_inherit_the_locks(self): script = ( "import os\n" @@ -1523,6 +1597,18 @@ def test_a_stop_signal_stops_a_capped_command(self): os.kill(int(line.split()[2]), 0) time.sleep(0.05) + def test_a_hard_kill_of_the_wrapper_stops_the_inside_process_and_the_command(self): + process = self.worker("capped-orphan", "1G", hold="300") # runs until the kill below ends it + command = int(self.wait_for_event("start", "capped-orphan").split()[2]) + inside = int(Path("/proc/%d/stat" % command).read_text().rsplit(")", 1)[1].split()[1]) + self.kill_later(inside) + self.kill_later(command) + self.assertIn(b"--inside-cap", Path("/proc/%d/cmdline" % inside).read_bytes()) + process.kill() + process.wait(timeout=60) + self.assertTrue(self.gone(inside), "the --inside-cap process still runs") + self.assertTrue(self.gone(command), "the command still runs") + def test_the_peak_comes_from_the_cgroup(self): script = "import time\ndata = bytearray(150 * 1024 * 1024)\nfor index in range(0, len(data), 4096):\n data[index] = 1\ntime.sleep(1.2)\n" process = self.wrapper(["--memory", "1G", "--measure"], [sys.executable, "-c", script]) From 87acd91fe8e89075ded41370f615291e64a274e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:08:45 +0100 Subject: [PATCH 50/65] fix(skills/bounding-heavy-commands): keep the default budget above zero (#45) Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 2 +- .../bounding-heavy-commands/scripts/tests/test_bounded_run.py | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index e04b6c7..da6acbd 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -189,7 +189,7 @@ def slots_needed(budget_mib: int, slot_mib: int, count: int) -> int: def default_budget_mib(total_mib: int, slot_mib: int) -> int: - return min(total_mib, max(1, math.ceil(total_mib / 4 / slot_mib)) * slot_mib) + return max(1, min(total_mib, max(1, math.ceil(total_mib / 4 / slot_mib)) * slot_mib)) class Settings: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 48afce3..4fcc89c 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -104,6 +104,9 @@ def test_default_budget_is_a_quarter_in_full_slots(self): self.assertEqual(bounded_run.default_budget_mib(32768, 2048), 8192) self.assertEqual(bounded_run.default_budget_mib(6000, 2048), 2048) + def test_default_budget_is_never_zero(self): + self.assertEqual(bounded_run.default_budget_mib(0, 2048), 1) + def test_default_budget_is_never_more_than_the_total(self): self.assertEqual(bounded_run.default_budget_mib(1024, 2048), 1024) self.assertEqual(bounded_run.default_budget_mib(2048, 2048), 2048) From 77ab2f993d3f5481f596d6b51b0dd2991a81eb89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:14:44 +0100 Subject: [PATCH 51/65] fix(skills/bounding-heavy-commands): keep a budget within a total smaller than one slot (#45) The queue has one slot or more, so on a machine or a container with less memory than one slot the queue was larger than the memory, and a budget of the size of the slot reached the hard cap. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 7 ++++--- .../scripts/tests/test_bounded_run.py | 7 +++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index da6acbd..066dced 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -723,9 +723,10 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: count = slot_count(settings.total_mib, settings.slot_mib, settings.reserve_mib) needed = slots_needed(budget, settings.slot_mib, count) - if budget > count * settings.slot_mib: - log("WARNING: the budget of %d MiB is more than the %d MiB of the queue; the budget is %d MiB" % (budget, count * settings.slot_mib, count * settings.slot_mib)) - budget = count * settings.slot_mib + queue_mib = max(1, min(settings.total_mib, count * settings.slot_mib)) + if budget > queue_mib: + log("WARNING: the budget of %d MiB is more than the %d MiB of the queue; the budget is %d MiB" % (budget, queue_mib, queue_mib)) + budget = queue_mib uid = os.getuid() directory = lock_directory(environ, uid) ensure_lock_directory(directory, uid) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 4fcc89c..2014e45 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1521,6 +1521,13 @@ def test_the_default_budget_on_a_small_machine_is_not_more_than_its_memory(self) budget = int(re.search(r"bounded-run: budget (\d+) MiB, peak", errors).group(1)) self.assertLessEqual(budget, 1024) + def test_a_budget_on_a_machine_smaller_than_one_slot_is_not_more_than_its_memory(self): + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"], BOUNDED_RUN_TOTAL_MIB="1024", BOUNDED_RUN_RESERVE_MIB="") + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + self.assertIn("WARNING: the budget of 2048 MiB is more than the 1024 MiB of the queue; the budget is 1024 MiB", errors) + self.assertRegex(errors, r"bounded-run: budget 1024 MiB, peak ") + def test_without_a_cap_the_output_says_so(self): process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"]) output, errors = process.communicate(timeout=60) From 04304df19dafe802316ee1cfa63720d6befecc27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:24:51 +0100 Subject: [PATCH 52/65] fix(skills/bounding-heavy-commands): hand a narrower argument through the inner shell (#45) The inner shell that reads the variables of the wrapper dropped each argument that came after it, so a subagent that added one test file ran the full suite. The form in the skill now ends with "$@" and a name for the shell, and the narrower argument goes at the end of the line. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/SKILL.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/skills/bounding-heavy-commands/SKILL.md b/skills/bounding-heavy-commands/SKILL.md index 70931f5..3e9149f 100644 --- a/skills/bounding-heavy-commands/SKILL.md +++ b/skills/bounding-heavy-commands/SKILL.md @@ -70,7 +70,7 @@ Then, before each heavy command, use the first case that applies: A budget is a measurement, not a preference. Change one only when the wrapper's output shows that the peak moved, and write the new peak and date with it. -A part of a recorded command (one test file, one target) uses the bounded command line of the full command, with its budget and its exclusive resources, and the narrower arguments. It needs no entry of its own and no measurement, because the budget of the full command is sufficient for each part of it. +A part of a recorded command (one test file, one target) uses the bounded command line of the full command, with its budget and its exclusive resources, and the narrower arguments at the end of the line. It needs no entry of its own and no measurement, because the budget of the full command is sufficient for each part of it. ## Discovery @@ -79,9 +79,11 @@ A part of a recorded command (one test file, one target) uses the bounded comman 3. Find how the toolchain limits its own parallelism and memory. Write the command line so that it takes those limits from `BOUNDED_RUN_CPUS` and `BOUNDED_RUN_MEMORY_MIB`. The wrapper sets the two variables for the command only. Your own shell does not have them. Put the command into an inner shell, in single quotes, so that your own shell does not replace the variable with an empty value before the wrapper starts: ``` - ... --cpus 4 -- sh -c ' "$BOUNDED_RUN_CPUS"' + ... --cpus 4 -- sh -c ' "$BOUNDED_RUN_CPUS" "$@"' sh ``` + The `"$@"` and the word `sh` at the end hand each argument that comes after them to the command. A narrower argument, such as one test file, goes at the end of the line, after that `sh`. Without the two, the inner shell drops the argument and runs the full command. + 4. Run each heavy command that you are about to run once with `--measure`, one at a time. Measure the full command, not a part of it: the peak of one test file is not the budget of the suite. Add `--exclusive ` for each resource that step 2 found for it: ``` @@ -122,7 +124,7 @@ A subagent does not see your project memory. It knows the bounded commands only On a machine on which the wrapper can run, every dispatch prompt for a subagent that will run a heavy command MUST include: 1. The bounded command line for each heavy command, copied from the record. -2. This rule, in these words: "Run the bounded commands as written. You can make two changes: a narrower argument for the command after the `--`, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited." +2. This rule, in these words: "Run the bounded commands as written. You can make two changes: a narrower argument at the end of the line, such as one test file, and one more `--exclusive ` option after a collision on a port or a lock, which you name in your report. Do not run the plain form of a bounded command or of a part of it. For a heavy command that is not in this prompt, use the same wrapper with no `--memory` option. If the file of the wrapper does not exist, stop and report that. Set no environment variable whose name starts with `BOUNDED_RUN_`. A command can wait in the queue for minutes before it starts, so run it in the background and do not put a short timeout around it. A long wait means that the machine is full; it is not a fault to repair. Say in your report how long you waited." 3. Each command that an instruction exempts from the wrapper, in its plain form, in a list of its own, with the instruction that exempts it. The rule of item 2 does not apply to that list. An instruction of the user that covers one run goes to the one subagent that does that run, and to no other. Do not dispatch fewer subagents to protect the machine. The queue protects it. Subagents that wait in the queue cost time, not memory. The one exception is a machine on which the wrapper cannot run (see the next section). From 6513fb80dd97690f50048ac67c9c94201ed0d141 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:33:33 +0100 Subject: [PATCH 53/65] fix(skills/bounding-heavy-commands): keep one queue when a cleaner deletes a lock file (#45) Without a runtime directory of the user, the lock files are in a temporary directory, and a cleaner of that directory deletes a file by its age. A caller that locked a deleted file held a slot alone, and the next caller took the same slot on a new file. The wrapper now checks after the lock that the path still names the locked file, and tries again when it does not. Each lock also sets the times of the file to now, so a file in use is not old for the cleaner. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 52 ++++++++++++++----- .../scripts/tests/test_bounded_run.py | 50 ++++++++++++++++++ 2 files changed, 88 insertions(+), 14 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 066dced..c2da212 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -293,17 +293,45 @@ def _open_lock_file(path: str) -> int: raise WrapperError("cannot open %s: %s" % (path, error.strerror if error.strerror else error)) -def _try_lock(path: str) -> Optional[int]: - descriptor = _open_lock_file(path) +def _is_the_file_at(path: str, descriptor: int) -> bool: try: - fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - os.close(descriptor) - return None - except OSError as error: + return os.path.samestat(os.stat(path), os.fstat(descriptor)) + except OSError: + return False + + +def _refresh(descriptor: int) -> None: + # A cleaner of a temporary directory deletes a file by its age, also while a lock is held on it. + try: + os.utime(descriptor) + except (OSError, TypeError, NotImplementedError): + pass + + +def _lock(path: str, wait: bool) -> Optional[int]: + """Locks the file that the path names now. Returns None when wait is false and the lock is held.""" + while True: + descriptor = _open_lock_file(path) + try: + fcntl.flock(descriptor, fcntl.LOCK_EX if wait else fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + os.close(descriptor) + return None + except OSError as error: + os.close(descriptor) + raise _lock_error(path, error) + except BaseException: + os.close(descriptor) + raise + # A file that was deleted after the open is locked by this process only: the next caller makes a new one. + if _is_the_file_at(path, descriptor): + _refresh(descriptor) + return descriptor os.close(descriptor) - raise _lock_error(path, error) - return descriptor + + +def _try_lock(path: str) -> Optional[int]: + return _lock(path, wait=False) def _lock_error(path: str, error: OSError) -> WrapperError: @@ -313,13 +341,9 @@ def _lock_error(path: str, error: OSError) -> WrapperError: def try_reserve(directory: str, count: int, needed: int, exclusive_files: Sequence[str]) -> Optional[Reservation]: turn_path = os.path.join(directory, "reserve.lock") - turn = _open_lock_file(turn_path) + turn = _lock(turn_path, wait=True) held: List[int] = [] try: - try: - fcntl.flock(turn, fcntl.LOCK_EX) - except OSError as error: - raise _lock_error(turn_path, error) names = list(exclusive_files) + ["slot-%03d.lock" % index for index in range(count)] slots = 0 for position, name in enumerate(names): diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 2014e45..b899403 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -503,6 +503,56 @@ def sleep_and_check(seconds): self.assertTrue(turn_lock_acquired[0], "turn lock should be free while reserve waits") +class LockFileTest(unittest.TestCase): + def setUp(self): + self.base = tempfile.TemporaryDirectory() + self.addCleanup(self.base.cleanup) + self.path = os.path.join(self.base.name, "slot-000.lock") + + def test_a_file_that_was_deleted_before_the_lock_is_not_the_lock(self): + real_open = bounded_run._open_lock_file + calls = [] + + def open_then_delete(path): + descriptor = real_open(path) + calls.append(descriptor) + if len(calls) == 1: + os.unlink(path) + return descriptor + + with mock.patch.object(bounded_run, "_open_lock_file", open_then_delete): + descriptor = bounded_run._try_lock(self.path) + self.addCleanup(os.close, descriptor) + self.assertEqual(len(calls), 2) + self.assertTrue(os.path.samestat(os.stat(self.path), os.fstat(descriptor))) + + def test_a_lock_makes_the_file_new_for_a_cleaner_of_old_files(self): + Path(self.path).write_text("") + os.utime(self.path, (1000, 1000)) + descriptor = bounded_run._try_lock(self.path) + self.addCleanup(os.close, descriptor) + self.assertGreater(os.stat(self.path).st_mtime, time.time() - 60) + self.assertGreater(os.stat(self.path).st_atime, time.time() - 60) + + def test_the_turn_lock_is_not_a_file_that_was_deleted_before_the_lock(self): + real_open = bounded_run._open_lock_file + turn_path = os.path.join(self.base.name, "reserve.lock") + opened = [] + + def open_then_delete(path): + descriptor = real_open(path) + if path == turn_path: + opened.append(descriptor) + if len(opened) == 1: + os.unlink(path) + return descriptor + + with mock.patch.object(bounded_run, "_open_lock_file", open_then_delete): + reservation = bounded_run.try_reserve(self.base.name, 1, 1, []) + self.addCleanup(reservation.release) + self.assertEqual(len(opened), 2) + + class ExclusiveNameTest(unittest.TestCase): def test_name_holds_the_repository_and_the_resource(self): self.assertEqual(bounded_run.exclusive_file_name("abc123", "port-8080"), "exclusive-abc123-port-8080.lock") From a6cad718b6e5602fc16a16899bf8525e800d93c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:33:33 +0100 Subject: [PATCH 54/65] fix(skills/bounding-heavy-commands): warn when the parent-death signal cannot be set (#45) The result of the call was not read, so a kernel or a sandbox that refuses it left the command with no protection and no message. The command still runs, as it does on a system with no such signal, and the wrapper prints a warning. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 3 ++- .../scripts/tests/test_bounded_run.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index c2da212..dc8bbcc 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -589,7 +589,8 @@ def parent_death_signal(platform: str = sys.platform) -> Optional[Callable[[], N kill = int(signal.SIGKILL) def set_signal() -> None: - prctl(PR_SET_PDEATHSIG, kill, 0, 0, 0) + if prctl(PR_SET_PDEATHSIG, kill, 0, 0, 0) != 0: + os.write(2, ("%s: WARNING: cannot set the parent-death signal; the command lives on after a hard kill of the wrapper\n" % PREFIX).encode()) # A parent that stopped before the call sends no signal; the child then has a new parent. if os.getppid() != parent: os._exit(EXIT_WRAPPER) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index b899403..c2c4e26 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1072,8 +1072,23 @@ def stop(): self.addCleanup(stop) self.assertEqual(process.wait(timeout=60), bounded_run.EXIT_WRAPPER) + def test_a_call_that_the_kernel_refuses_gives_a_warning_and_the_child_runs(self): + library = mock.Mock(return_value=mock.Mock(prctl=mock.Mock(return_value=-1))) + with mock.patch.object(bounded_run, "ctypes", mock.Mock(CDLL=library)): + set_signal = bounded_run.parent_death_signal(platform="linux") + process = subprocess.Popen([sys.executable, "-c", "pass"], preexec_fn=set_signal, stderr=subprocess.PIPE, text=True) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + self.assertIn("bounded-run: WARNING: cannot set the parent-death signal; the command lives on after a hard kill of the wrapper", errors) + @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal") def test_a_child_of_this_process_runs(self): + process = subprocess.Popen([sys.executable, "-c", "pass"], preexec_fn=bounded_run.parent_death_signal(), stderr=subprocess.PIPE, text=True) + output, errors = process.communicate(timeout=60) + self.assertEqual((process.returncode, errors), (0, "")) + + @unittest.skipUnless(sys.platform.startswith("linux"), "only Linux has a parent-death signal") + def test_a_child_of_this_process_runs_with_no_pipe(self): process = subprocess.Popen([sys.executable, "-c", "pass"], preexec_fn=bounded_run.parent_death_signal()) self.assertEqual(process.wait(timeout=60), 0) From 0a7052a090372c976c1c82cf109a1fea50d09aba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:33:33 +0100 Subject: [PATCH 55/65] fix(skills/bounding-heavy-commands): keep the reserve on a machine with less than one slot after it (#45) With less memory after the reserve than one slot, the one slot of the queue gave out a full slot, which is more than the reserve leaves. The queue now gives out what the reserve leaves. When the reserve leaves nothing, the queue gives out the memory of the machine up to one slot and prints a warning, because a budget of zero runs no command. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 20 ++++++++++++---- .../scripts/tests/test_bounded_run.py | 23 +++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index dc8bbcc..c3e2eaa 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -184,6 +184,16 @@ def slot_count(total_mib: int, slot_mib: int, reserve_mib: int) -> int: return max(1, (total_mib - reserve_mib) // slot_mib) +def queue_mib(total_mib: int, slot_mib: int, reserve_mib: int) -> int: + """Returns the most memory that the commands of the queue hold together.""" + after_reserve = total_mib - reserve_mib + if after_reserve >= slot_mib: + return slot_count(total_mib, slot_mib, reserve_mib) * slot_mib + if after_reserve > 0: + return after_reserve + return max(1, min(total_mib, slot_mib)) + + def slots_needed(budget_mib: int, slot_mib: int, count: int) -> int: return min(count, max(1, math.ceil(budget_mib / slot_mib))) @@ -748,10 +758,12 @@ def bounded(options: Options, environ: Mapping[str, str]) -> int: count = slot_count(settings.total_mib, settings.slot_mib, settings.reserve_mib) needed = slots_needed(budget, settings.slot_mib, count) - queue_mib = max(1, min(settings.total_mib, count * settings.slot_mib)) - if budget > queue_mib: - log("WARNING: the budget of %d MiB is more than the %d MiB of the queue; the budget is %d MiB" % (budget, queue_mib, queue_mib)) - budget = queue_mib + if settings.reserve_mib >= settings.total_mib: + log("WARNING: the reserve of %d MiB leaves no memory of the %d MiB of the machine; the queue does not keep the reserve" % (settings.reserve_mib, settings.total_mib)) + most = queue_mib(settings.total_mib, settings.slot_mib, settings.reserve_mib) + if budget > most: + log("WARNING: the budget of %d MiB is more than the %d MiB of the queue; the budget is %d MiB" % (budget, most, most)) + budget = most uid = os.getuid() directory = lock_directory(environ, uid) ensure_lock_directory(directory, uid) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index c2c4e26..02262c3 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -88,6 +88,16 @@ def test_divides_the_memory_after_the_reserve(self): def test_gives_one_slot_on_a_small_machine(self): self.assertEqual(bounded_run.slot_count(2048, 2048, 2048), 1) + def test_the_queue_holds_its_slots_when_the_reserve_leaves_one_or_more(self): + self.assertEqual(bounded_run.queue_mib(32768, 2048, 8192), 24576) + + def test_the_queue_keeps_the_reserve_on_a_machine_with_less_than_one_slot_after_it(self): + self.assertEqual(bounded_run.queue_mib(3072, 2048, 2048), 1024) + + def test_the_queue_has_the_memory_of_the_machine_when_the_reserve_leaves_nothing(self): + self.assertEqual(bounded_run.queue_mib(1024, 2048, 2048), 1024) + self.assertEqual(bounded_run.queue_mib(4096, 2048, 4096), 2048) + def test_default_reserve_is_a_quarter_with_a_minimum(self): self.assertEqual(bounded_run.default_reserve_mib(32768), 8192) self.assertEqual(bounded_run.default_reserve_mib(4096), 2048) @@ -1593,6 +1603,19 @@ def test_a_budget_on_a_machine_smaller_than_one_slot_is_not_more_than_its_memory self.assertIn("WARNING: the budget of 2048 MiB is more than the 1024 MiB of the queue; the budget is 1024 MiB", errors) self.assertRegex(errors, r"bounded-run: budget 1024 MiB, peak ") + def test_a_budget_on_a_machine_with_less_than_one_slot_after_the_reserve_keeps_the_reserve(self): + process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"], BOUNDED_RUN_TOTAL_MIB="3072", BOUNDED_RUN_RESERVE_MIB="") + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + self.assertIn("WARNING: the budget of 2048 MiB is more than the 1024 MiB of the queue; the budget is 1024 MiB", errors) + self.assertNotIn("reserve", errors) + + def test_a_reserve_that_leaves_nothing_gives_a_warning(self): + process = self.wrapper(["--memory", "1G"], [sys.executable, "-c", "pass"], BOUNDED_RUN_TOTAL_MIB="1024", BOUNDED_RUN_RESERVE_MIB="") + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + self.assertIn("WARNING: the reserve of 2048 MiB leaves no memory of the 1024 MiB of the machine; the queue does not keep the reserve", errors) + def test_without_a_cap_the_output_says_so(self): process = self.wrapper(["--memory", "2G"], [sys.executable, "-c", "pass"]) output, errors = process.communicate(timeout=60) From 6e91cb94c9cb89c69c7267228fe0004ce6bde6c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:41:42 +0100 Subject: [PATCH 56/65] fix(skills/bounding-heavy-commands): refuse a poll or sample interval of zero (#45) With an interval of zero, the wait for free memory never reached its time limit, and the loop took a full processor. The same was true for the loop that samples the peak. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 5 +++++ .../scripts/tests/test_bounded_run.py | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index c3e2eaa..6ab52df 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -214,6 +214,11 @@ def __init__(self, environ: Mapping[str, str], read_total: Callable[[], int] = t self.no_cap = bool(environ.get("BOUNDED_RUN_NO_CAP")) if self.slot_mib <= 0: raise WrapperError("BOUNDED_RUN_SLOT_MIB must be more than zero") + # A loop that sleeps for zero seconds never ends its wait and takes a full processor. + if self.poll_seconds <= 0: + raise WrapperError("BOUNDED_RUN_POLL_SECONDS must be more than zero") + if self.sample_seconds <= 0: + raise WrapperError("BOUNDED_RUN_SAMPLE_SECONDS must be more than zero") def _number(environ: Mapping[str, str], name: str, fallback: float) -> float: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 02262c3..9d26b37 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -243,6 +243,12 @@ def test_a_set_total_reads_nothing_of_the_machine(self): settings = bounded_run.Settings({"BOUNDED_RUN_TOTAL_MIB": "4096"}) self.assertEqual(settings.total_mib, 4096) + def test_rejects_an_interval_of_zero(self): + for name in ("BOUNDED_RUN_POLL_SECONDS", "BOUNDED_RUN_SAMPLE_SECONDS"): + with self.subTest(name=name): + with self.assertRaisesRegex(bounded_run.WrapperError, name + " must be more than zero"): + bounded_run.Settings({name: "0"}, read_total=lambda: 1) + def test_rejects_a_value_that_is_not_a_number(self): with self.assertRaises(bounded_run.WrapperError): bounded_run.Settings({"BOUNDED_RUN_POLL_SECONDS": "fast"}, read_total=lambda: 1) From 6bf5ef1e1885b1de5d4c3213e5f1cc4fce8ae6f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:41:42 +0100 Subject: [PATCH 57/65] fix(skills/bounding-heavy-commands): warn when a command leaves a process that still runs (#45) The wrapper waits for the command and not for the processes that it started. A process that stays after the command ends is outside the queue, and no message said so. The wrapper does not wait for such a process: a tool that leaves a helper process would hold its slots with no end. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 12 +++++++++ .../scripts/tests/test_bounded_run.py | 27 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 6ab52df..21f72b6 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -613,6 +613,16 @@ def set_signal() -> None: return set_signal +def _group_runs(group: int) -> bool: + try: + os.killpg(group, 0) + except PermissionError: + return True + except OSError: + return False + return True + + def run_command( command: Sequence[str], environ: Mapping[str, str], on_start: Optional[Callable[[int], None]] = None, @@ -656,6 +666,8 @@ def forward(signum: int, frame: object) -> None: pass raise process.returncode = exit_code_of(status) + if not received and _group_runs(process.pid): + log("WARNING: the command left a process that still runs; the queue does not count its memory") finally: for signum, handler in previous.items(): signal.signal(signum, handler) diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 9d26b37..f2484c7 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1053,6 +1053,33 @@ def on_start(pid): self.assertFalse(alive, "the command still runs") +class LeftProcessTest(unittest.TestCase): + def setUp(self): + patcher = mock.patch.object(bounded_run, "log") + self.log = patcher.start() + self.addCleanup(patcher.stop) + + def test_a_process_that_the_command_leaves_running_gives_a_warning(self): + groups = [] + + def stop(): + for group in groups: + try: + os.killpg(group, signal.SIGKILL) + except (ProcessLookupError, PermissionError): + pass + + self.addCleanup(stop) + code, _ = bounded_run.run_command(["sh", "-c", "sleep 300 >/dev/null 2>&1 &"], os.environ, on_start=groups.append) + self.assertEqual(code, 0) + self.log.assert_called_once_with("WARNING: the command left a process that still runs; the queue does not count its memory") + + def test_a_command_that_leaves_no_process_gives_no_warning(self): + code, _ = bounded_run.run_command(["sh", "-c", "sleep 0.1 & wait"], os.environ) + self.assertEqual(code, 0) + self.log.assert_not_called() + + class ParentDeathSignalTest(unittest.TestCase): def setUp(self): patcher = mock.patch.object(bounded_run, "log") From f981d2f9f72a6c4334ab1411a97c9b2ef1d50b16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:48:10 +0100 Subject: [PATCH 58/65] fix(skills/bounding-heavy-commands): take the smallest free memory of all cgroup levels (#45) The free memory of a cgroup was read only at the level of its smallest limit. A parent with a larger limit and less free memory was not counted, and the wrapper started a command that the parent had no memory for. The wrapper now reads each level and uses the smallest result. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 21 ++++++++++++------- .../scripts/tests/test_bounded_run.py | 21 +++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 21f72b6..bfeb1dd 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -143,13 +143,7 @@ def cgroup_limit_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgrou return min(limits)[0] // (1024 * 1024) if limits else None -def cgroup_available_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]: - """Returns the smallest memory limit of the cgroup of this process and of its parents, less the use - at the level of that limit, or None when the limit or the use cannot be read.""" - limits = _cgroup_limits(proc_root, cgroup_root) - if not limits: - return None - limit, directory, use_name, inactive_name = min(limits) +def _level_available(limit: int, directory: str, use_name: str, inactive_name: str) -> Optional[int]: try: with open(os.path.join(directory, use_name)) as handle: use = int(handle.read().strip()) @@ -165,6 +159,19 @@ def cgroup_available_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/c return None +def cgroup_available_mib(proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[int]: + """Returns the smallest free memory of the cgroup of this process and of its parents: the limit of a + level less the use at that level. Returns None when the use at the smallest limit cannot be read.""" + limits = _cgroup_limits(proc_root, cgroup_root) + if not limits: + return None + smallest = _level_available(*min(limits)) + if smallest is None: + return None + others = [_level_available(*level) for level in limits] + return min([smallest] + [value for value in others if value is not None]) + + def total_memory_mib( proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup", read_physical: Callable[[], int] = physical_memory_mib, diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index f2484c7..09e43a3 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -675,6 +675,27 @@ def test_a_cgroup_whose_use_cannot_be_read_gives_the_free_memory_of_the_host(sel def test_no_cgroup_files_gives_the_free_memory_of_the_host(self): self.assertEqual(self.available(), 16384) + def test_a_parent_with_a_larger_limit_and_less_free_memory_decides(self): + self.membership("0::/container/unit-1.scope\n") + self.write("container/unit-1.scope", "memory.max", str(4096 * 1024 ** 2)) + self.write("container/unit-1.scope", "memory.current", str(1024 * 1024 ** 2)) + self.write("container/unit-1.scope", "memory.stat", "inactive_file 0\n") + self.write("container", "memory.max", str(8192 * 1024 ** 2)) + self.write("container", "memory.current", str(8000 * 1024 ** 2)) + self.write("container", "memory.stat", "inactive_file 0\n") + self.assertEqual(self.available(), 192) + + def test_levels_with_the_same_limit_give_the_smallest_free_memory(self): + for full in ("container", "container/unit-1.scope"): + with self.subTest(full=full): + shutil.rmtree(self.cgroups) + self.membership("0::/container/unit-1.scope\n") + for level in ("container", "container/unit-1.scope"): + self.write(level, "memory.max", str(4096 * 1024 ** 2)) + self.write(level, "memory.current", str((4000 if level == full else 1024) * 1024 ** 2)) + self.write(level, "memory.stat", "inactive_file 0\n") + self.assertEqual(self.available(), 96) + def test_the_use_is_read_at_the_level_of_the_limit_in_a_parent(self): self.membership("0::/container/unit-1.scope\n") self.write("container/unit-1.scope", "memory.max", "max") From 4b4b0f0a76959dd2c8c9b435406810d58254bb31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:35:48 +0100 Subject: [PATCH 59/65] docs(README): recommend project memory for the bounded commands (#45) Co-Authored-By: Claude Fable 5.1 --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b33aad9..9301c02 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,8 @@ A local path also works for development: `/plugin marketplace add /path/to/featu No further setup is required; the skills derive your repo and build commands from context. Optionally, paste [`templates/project-CLAUDE.md`](templates/project-CLAUDE.md) into your project's `CLAUDE.md` to give every session the workflow overview and the operational rules (commit conventions, safe git staging, GitHub-mutation confirmation). +Keep project memory on to get the most from `bounding-heavy-commands`. In Claude Code that is auto memory, which is on by default. The skill saves the measured memory budget and the bounded command line of each heavy command there, so a later session starts with them. With memory off, the queue still protects the machine, but each session measures the commands again and uses the default budget for a command that it did not measure. + ## Notes - Intra-plugin skill references are namespaced as `feature-dev-workflow:`. From 444951859377299143a606afc8c3f159a64a4b41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:41:58 +0100 Subject: [PATCH 60/65] chore(.github): use the action versions that run on Node 24 (#45) The versions before ran on Node 20, which the runner no longer has. They worked only because the runner moved them to Node 24 and printed a warning. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/script-tests.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/script-tests.yml b/.github/workflows/script-tests.yml index 20b6e76..c402ccc 100644 --- a/.github/workflows/script-tests.yml +++ b/.github/workflows/script-tests.yml @@ -22,10 +22,10 @@ jobs: - os: macos-latest python: system steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - if: matrix.python != 'system' - uses: actions/setup-python@v5 + uses: actions/setup-python@v7 with: python-version: ${{ matrix.python }} From 5ad2e482a4d094947421e6a1cfade5823dc5c27a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:50:25 +0100 Subject: [PATCH 61/65] fix(skills/bounding-heavy-commands): refuse to run when git does not name the repository in time (#45) When the git call took too long, the wrapper used the directory in place of the repository. Each worktree then had its own lock for one --exclusive name, and two commands ran together on the same resource. The wrapper now ends with an error. A machine with no git still uses the directory. Co-Authored-By: Claude Fable 5.1 --- .../bounding-heavy-commands/scripts/bounded_run.py | 6 +++++- .../scripts/tests/test_bounded_run.py | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index bfeb1dd..e51240a 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -287,8 +287,12 @@ def repository_id(directory: str) -> str: ) if done.returncode == 0 and done.stdout.strip(): root = os.path.realpath(os.path.join(directory, done.stdout.strip())) - except (OSError, subprocess.TimeoutExpired): + except FileNotFoundError: + # A machine with no git has no worktrees, so the directory names the repository. pass + except (OSError, subprocess.TimeoutExpired) as error: + # The directory in place of the repository gives each worktree a lock of its own. + raise WrapperError("cannot find the repository of %s: %s" % (directory, error)) return hashlib.sha256(root.encode("utf-8")).hexdigest()[:12] diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 09e43a3..7640aff 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -590,6 +590,18 @@ def test_worktrees_of_one_repository_have_the_same_id(self): subprocess.run(git + ["-C", main, "worktree", "add", "--quiet", "--detach", other], check=True) self.assertEqual(bounded_run.repository_id(main), bounded_run.repository_id(other)) + def test_a_git_call_that_takes_too_long_gives_an_error(self): + slow = subprocess.TimeoutExpired(["git"], 10) + with tempfile.TemporaryDirectory() as directory, mock.patch.object(bounded_run.subprocess, "run", side_effect=slow): + with self.assertRaisesRegex(bounded_run.WrapperError, "cannot find the repository of"): + bounded_run.repository_id(directory) + + def test_a_machine_with_no_git_uses_the_directory(self): + with tempfile.TemporaryDirectory() as directory: + with mock.patch.object(bounded_run.subprocess, "run", side_effect=FileNotFoundError("git")): + without = bounded_run.repository_id(directory) + self.assertEqual(without, bounded_run.repository_id(directory)) + def test_two_directories_have_different_ids(self): with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second: self.assertNotEqual(bounded_run.repository_id(first), bounded_run.repository_id(second)) From fcaf35f4cd636065b3b02ff22b2dba41d75a3274 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:50:25 +0100 Subject: [PATCH 62/65] fix(skills/bounding-heavy-commands): end the command on a second stop signal during its start (#45) Two stop signals that came while the command started were both recorded, and the wrapper sent only the first to the command. A command that ignores that signal then ran to its end. The wrapper now sends SIGKILL, as it does for a second signal after the start. Co-Authored-By: Claude Fable 5.1 --- .../scripts/bounded_run.py | 2 +- .../scripts/tests/test_bounded_run.py | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index e51240a..41c0aae 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -660,7 +660,7 @@ def forward(signum: int, frame: object) -> None: try: if received: try: - os.killpg(process.pid, received[0]) + os.killpg(process.pid, received[0] if len(received) == 1 else signal.SIGKILL) except (ProcessLookupError, PermissionError): pass if on_start is not None: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 7640aff..d28b47f 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -1086,6 +1086,31 @@ def on_start(pid): self.assertFalse(alive, "the command still runs") +class SignalAtStartTest(unittest.TestCase): + def test_two_stop_signals_before_the_command_runs_end_a_command_that_ignores_the_first(self): + real = subprocess.Popen + + base = tempfile.TemporaryDirectory() + self.addCleanup(base.cleanup) + ready = os.path.join(base.name, "ready") + + def start_then_signal(*args, **kwargs): + process = real(*args, **kwargs) + limit = time.monotonic() + 30 + while not os.path.exists(ready) and time.monotonic() < limit: + time.sleep(0.02) + os.kill(os.getpid(), signal.SIGTERM) + os.kill(os.getpid(), signal.SIGTERM) + return process + + script = "import signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); open(%r, 'w').close(); time.sleep(20)" % ready + started = time.monotonic() + with mock.patch.object(bounded_run.subprocess, "Popen", start_then_signal): + code, _ = bounded_run.run_command([sys.executable, "-c", script], os.environ) + self.assertEqual(code, 128 + signal.SIGTERM) + self.assertLess(time.monotonic() - started, 10) + + class LeftProcessTest(unittest.TestCase): def setUp(self): patcher = mock.patch.object(bounded_run, "log") From 7419ff66a8d96f626e95e0ee2447d9dd738389c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Tue, 29 Sep 2026 09:57:40 +0100 Subject: [PATCH 63/65] fix(skills/bounding-heavy-commands): count the slots of a very large budget with whole numbers (#45) The count of slots divided the budget as a float. A budget too large for a float gave a traceback in place of the budget of the queue. Co-Authored-By: Claude Fable 5.1 --- skills/bounding-heavy-commands/scripts/bounded_run.py | 2 +- .../scripts/tests/test_bounded_run.py | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 41c0aae..53e6035 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -202,7 +202,7 @@ def queue_mib(total_mib: int, slot_mib: int, reserve_mib: int) -> int: def slots_needed(budget_mib: int, slot_mib: int, count: int) -> int: - return min(count, max(1, math.ceil(budget_mib / slot_mib))) + return min(count, max(1, -(-budget_mib // slot_mib))) def default_budget_mib(total_mib: int, slot_mib: int) -> int: diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index d28b47f..0320ba5 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -107,6 +107,9 @@ def test_a_budget_takes_the_slots_that_cover_it(self): self.assertEqual(bounded_run.slots_needed(6145, 2048, 12), 4) self.assertEqual(bounded_run.slots_needed(100, 2048, 12), 1) + def test_a_budget_too_large_for_a_float_takes_all_slots(self): + self.assertEqual(bounded_run.slots_needed(10 ** 400, 2048, 12), 12) + def test_a_budget_larger_than_the_queue_takes_all_slots(self): self.assertEqual(bounded_run.slots_needed(99999, 2048, 3), 3) @@ -1626,6 +1629,13 @@ def test_a_budget_larger_than_the_queue_runs_with_a_warning(self): self.assertEqual(second.wait(timeout=60), 0) self.assertEqual(self.peak_concurrency(), 1) + def test_a_budget_too_large_for_a_float_gives_the_budget_of_the_queue(self): + process = self.wrapper(["--memory", "1" + "0" * 400 + "G"], [sys.executable, "-c", "pass"]) + output, errors = process.communicate(timeout=60) + self.assertEqual(process.returncode, 0, errors) + self.assertNotIn("Traceback", errors) + self.assertRegex(errors, r"bounded-run: budget 4096 MiB, peak ") + def test_a_budget_larger_than_the_queue_gives_the_command_the_budget_of_the_queue(self): script = "import os; print(os.environ['BOUNDED_RUN_MEMORY_MIB'])" process = self.wrapper(["--memory", "64G"], [sys.executable, "-c", script]) From bb292a3a1e68f0bbf5dd013b8aab659027023842 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:04:56 +0100 Subject: [PATCH 64/65] fix(skills/bounding-heavy-commands): refuse to run when git fails for a reason other than no repository (#45) Each result of git other than success counted as "not a repository", and the wrapper used the directory. A fault such as an owner that git does not trust then gave each worktree its own lock for one --exclusive name. The wrapper now uses the directory only when git says that the directory is not a repository. Co-Authored-By: Claude Fable 5.1 --- .../bounding-heavy-commands/scripts/bounded_run.py | 5 +++++ .../scripts/tests/test_bounded_run.py | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/skills/bounding-heavy-commands/scripts/bounded_run.py b/skills/bounding-heavy-commands/scripts/bounded_run.py index 53e6035..2639961 100755 --- a/skills/bounding-heavy-commands/scripts/bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/bounded_run.py @@ -284,9 +284,14 @@ def repository_id(directory: str) -> str: done = subprocess.run( ["git", "rev-parse", "--git-common-dir"], cwd=directory, capture_output=True, text=True, timeout=10, + env=dict(os.environ, LC_ALL="C", LANGUAGE="C"), ) if done.returncode == 0 and done.stdout.strip(): root = os.path.realpath(os.path.join(directory, done.stdout.strip())) + elif "not a git repository" not in done.stderr: + # A fault of git in a worktree must not give that worktree a lock of its own. + lines = done.stderr.strip().splitlines() + raise WrapperError("cannot find the repository of %s: %s" % (directory, lines[0] if lines else "git gave no answer")) except FileNotFoundError: # A machine with no git has no worktrees, so the directory names the repository. pass diff --git a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py index 0320ba5..9b3aade 100644 --- a/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py +++ b/skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py @@ -599,6 +599,18 @@ def test_a_git_call_that_takes_too_long_gives_an_error(self): with self.assertRaisesRegex(bounded_run.WrapperError, "cannot find the repository of"): bounded_run.repository_id(directory) + def test_a_git_fault_other_than_no_repository_gives_an_error(self): + done = subprocess.CompletedProcess(["git"], 128, "", "fatal: detected dubious ownership in repository at '/x'\n") + with tempfile.TemporaryDirectory() as directory, mock.patch.object(bounded_run.subprocess, "run", return_value=done): + with self.assertRaisesRegex(bounded_run.WrapperError, "cannot find the repository of .*dubious ownership"): + bounded_run.repository_id(directory) + + def test_git_answers_in_the_language_that_the_wrapper_reads(self): + done = subprocess.CompletedProcess(["git"], 128, "", "fatal: not a git repository (or any of the parent directories): .git\n") + with tempfile.TemporaryDirectory() as directory, mock.patch.object(bounded_run.subprocess, "run", return_value=done) as run: + bounded_run.repository_id(directory) + self.assertEqual(run.call_args.kwargs["env"]["LC_ALL"], "C") + def test_a_machine_with_no_git_uses_the_directory(self): with tempfile.TemporaryDirectory() as directory: with mock.patch.object(bounded_run.subprocess, "run", side_effect=FileNotFoundError("git")): From 187f49eb549ec79d02e9be7d22faea06d428a2a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=86gir=20M=C3=A1ni=20Hauksson?= <54936225+sourcehawk@users.noreply.github.com> Date: Tue, 29 Sep 2026 10:04:56 +0100 Subject: [PATCH 65/65] fix(skills/fanning-out-with-worktrees): name the machine on which the wrapper cannot run (#45) The rule against a smaller wave gave the queue as its reason and did not say what holds when no queue exists. Co-Authored-By: Claude Fable 5.1 --- skills/fanning-out-with-worktrees/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/skills/fanning-out-with-worktrees/SKILL.md b/skills/fanning-out-with-worktrees/SKILL.md index cfef8a9..0165be6 100644 --- a/skills/fanning-out-with-worktrees/SKILL.md +++ b/skills/fanning-out-with-worktrees/SKILL.md @@ -144,7 +144,7 @@ When every wave is complete (every sub-issue closed, every row `self-merged`, ev - **Orchestrator fixing review findings in place.** The worktree subagent wrote the code and holds the context; it fixes, then the orchestrator re-reviews. A silent orchestrator fix skips the author and erodes the shared understanding the parallel agents run on. - **Letting the worktree subagent review its own PR.** A subagent reviewing the code it just wrote has the same blind spots in review that it had in implementation. The orchestrator owns sub-PR review precisely because it didn't write the code. - **Letting a bubble-up concern die in one subagent.** Propagation is the whole point of the watch loop. -- **Shrinking the wave to spare the machine.** The number of subagents does not decide the load; the commands they run do. Dispatch the wave the plan calls for and hand every subagent the bounded commands (dispatch item 5). Subagents that wait in the queue cost time, not memory. +- **Shrinking the wave to spare the machine.** The number of subagents does not decide the load; the commands they run do. Dispatch the wave the plan calls for and hand every subagent the bounded commands (dispatch item 5). Subagents that wait in the queue cost time, not memory. On a machine on which the wrapper cannot run, no queue exists: dispatch the same wave, and let only one subagent at a time run a heavy command, as `feature-dev-workflow:bounding-heavy-commands` says. - **Forgetting to manually close the sub-issue when `sub_pr_target: feature-branch`.** The keyword doesn't fire on non-default-branch merges; the issue page silently shows "open" even though the work shipped. - **Using `Towards #` when `sub_pr_target: main`.** `Closes` fires on merge to the default branch; `Towards` intentionally blocks auto-close. Using the wrong keyword silently leaves sub-issues open after they merge to main and forces a manual cleanup pass. - **Letting the state file go stale.** A resumed session reads it as ground truth. Update every row as reality moves; commit **and push** the state-file diff per phase transition — an unpushed local commit diverges the feature branch the moment the next sub-PR squash-merges on GitHub (see Step 5.4).