Hold each heavy command for one of a heavy slot per 4 CPUs, and each worker until a quarter of memory is available

This commit is contained in:
2026-10-23 10:40:57 +02:00
parent 9df08bd41e
commit 6c823de29c
19 changed files with 303 additions and 6 deletions
View File
+84
View File
@@ -0,0 +1,84 @@
"""Run a heavy command once it holds one of the machine's heavy slots, so sessions running at once cannot starve the machine.
usage: run-heavy <command> [<arg>...]
A heavy command is one that loads the machine for minutes: a full gate, mutation tests, an e2e run,
a docker build. The machine has one heavy slot per 4 CPUs, and at least one, shared by every
session that runs run-heavy. Each slot is a file locked with flock, under
$XDG_STATE_HOME/run-heavy (default ~/.local/state/run-heavy). While every slot is held, run-heavy
says so once on stderr and waits. It then runs the command in its place, which holds the slot until
it and every process that inherited the lock exit. Its exit code is the command's.
A command it runs carries the slot's number in RUN_HEAVY_SLOT, and run-heavy called with that set
runs its command at once, so a gate that wraps its own steps cannot wait on itself.
Exit 1, saying why, when no command is given or the slot folder cannot be made; exit 127 when the
command cannot start.
"""
import fcntl
import os
import pathlib
import sys
import time
import typing
CPUS_PER_SLOT = 4
# Names the slot a command runs in, so a heavy command it runs does not wait for a second slot.
HELD = "RUN_HEAVY_SLOT"
# Seconds between tries while every slot is held; a slot frees as its command exits.
POLL_SECONDS = 1
USAGE = "usage: run-heavy <command> [<arg>...]"
def slot_count(cpus: int | None) -> int:
return max(1, (cpus or 0) // CPUS_PER_SLOT)
def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path:
state = env.get("XDG_STATE_HOME") or str(pathlib.Path.home() / ".local" / "state")
return pathlib.Path(state) / "run-heavy"
def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
"""The number and open file of a slot this call locked; None while every slot is held."""
for slot in range(slots):
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
os.close(fd)
continue
return slot, fd
return None
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if not argv:
print(f"run-heavy: no command given; {USAGE}", file=sys.stderr)
return 1
if HELD not in env:
folder = slot_folder(env)
try:
folder.mkdir(parents=True, exist_ok=True)
except OSError as failure:
print(f"run-heavy: cannot make the slot folder {folder}: {failure.strerror}", file=sys.stderr)
return 1
slots = slot_count(os.cpu_count())
said = False
while (taken := taken_slot(folder, slots)) is None:
if not said:
print(f"run-heavy: waiting for one of the machine's {slots} heavy slots", file=sys.stderr, flush=True)
said = True
time.sleep(POLL_SECONDS)
slot, fd = taken
# The command inherits the locked file, so the slot stays held until it exits.
os.set_inheritable(fd, True)
env = {**env, HELD: str(slot)}
try:
os.execvpe(argv[0], argv, env)
except OSError as failure:
print(f"run-heavy: cannot run {argv[0]}: {failure.strerror}", file=sys.stderr)
return 127
+100
View File
@@ -0,0 +1,100 @@
import contextlib
import fcntl
import os
import pathlib
import subprocess
import sys
import tempfile
import time
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from run_heavy import main
TOOL = pathlib.Path(__file__).resolve().parents[1] / "run-heavy"
class SlotCount(unittest.TestCase):
def test_one_slot_per_four_cpus_and_never_none(self):
for cpus, slots in ((16, 4), (8, 2), (7, 1), (4, 1), (1, 1), (None, 1)):
self.assertEqual(main.slot_count(cpus), slots, cpus)
class RunHeavy(unittest.TestCase):
def setUp(self):
state = tempfile.TemporaryDirectory()
self.addCleanup(state.cleanup)
self.env = {**os.environ, "XDG_STATE_HOME": state.name}
self.env.pop(main.HELD, None)
self.slots = pathlib.Path(state.name) / "run-heavy"
def run_tool(self, *args: str, env=None) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True, env=env or self.env, timeout=30)
def start_tool(self, *args: str, env=None) -> subprocess.Popen[str]:
tool = subprocess.Popen([sys.executable, str(TOOL), *args], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env or self.env)
self.addCleanup(tool.kill)
return tool
@contextlib.contextmanager
def every_slot_held(self):
self.slots.mkdir(parents=True, exist_ok=True)
with contextlib.ExitStack() as held:
for slot in range(main.slot_count(os.cpu_count())):
file = held.enter_context(open(self.slots / f"slot-{slot}", "a"))
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def free_slots(self) -> int:
free = 0
for slot in range(main.slot_count(os.cpu_count())):
with open(self.slots / f"slot-{slot}", "a") as file:
try:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
free += 1
except BlockingIOError:
pass
return free
def test_runs_the_command_and_exits_with_its_code(self):
result = self.run_tool("sh", "-c", "echo out; echo err >&2; exit 3")
self.assertEqual((result.returncode, result.stdout, result.stderr), (3, "out\n", "err\n"))
def test_holds_a_slot_while_the_command_runs_and_frees_it_after(self):
tool = self.start_tool("sh", "-c", "echo started; read line")
self.assertEqual(tool.stdout.readline(), "started\n")
self.assertEqual(self.free_slots(), main.slot_count(os.cpu_count()) - 1)
tool.communicate("\n", timeout=30)
self.assertEqual(self.free_slots(), main.slot_count(os.cpu_count()))
def test_waits_while_every_slot_is_held_and_says_so_once(self):
with self.every_slot_held():
tool = self.start_tool("echo", "ran")
time.sleep(3 * main.POLL_SECONDS)
self.assertIsNone(tool.poll())
out, err = tool.communicate(timeout=30)
self.assertEqual((tool.returncode, out), (0, "ran\n"))
self.assertEqual(err.count("waiting"), 1, err)
def test_a_command_inside_a_held_slot_runs_at_once(self):
with self.every_slot_held():
result = self.run_tool("echo", "nested", env={**self.env, main.HELD: "0"})
self.assertEqual((result.returncode, result.stdout), (0, "nested\n"))
def test_a_command_that_cannot_start_exits_127_saying_why(self):
result = self.run_tool("no-such-command-anywhere")
self.assertEqual((result.returncode, result.stdout), (127, ""))
self.assertIn("no-such-command-anywhere", result.stderr)
def test_no_command_exits_1_with_the_usage_and_help_exits_0(self):
bare = self.run_tool()
self.assertEqual((bare.returncode, bare.stdout), (1, ""))
self.assertIn("usage: run-heavy <command>", bare.stderr)
helped = self.run_tool("--help")
self.assertEqual(helped.returncode, 0)
self.assertIn("usage: run-heavy <command>", helped.stdout)
if __name__ == "__main__":
unittest.main()