Answer principles round 1: 0 🔴, 5 🟡; enforce run-heavy in rule-hook, take slots through one tested function, exit 125 on lock errors, fake meminfo in black-box tests

This commit is contained in:
2026-10-23 10:55:55 +02:00
parent 6725ee4c9d
commit c7dbd56f39
14 changed files with 136 additions and 59 deletions
+4 -10
View File
@@ -1,10 +1,4 @@
"""How much of the machine's memory is available, so loop-claude starts a worker only while a quarter is.
loop-claude reads MemAvailable and MemTotal from /proc/meminfo before each worker starts. While less
than a quarter is available, it says so once on stderr and reads again each minute, so loops running
at once do not push the machine into swap. Where the file cannot be read, as off Linux, the worker
starts at once.
"""
"""How much of the machine's memory is available, as /proc/meminfo's MemAvailable and MemTotal state it, and whether that leaves room for a worker: a quarter of it."""
import dataclasses
import pathlib
import re
@@ -32,9 +26,9 @@ def parsed(meminfo: str) -> Memory | None:
return Memory(available=int(fields["MemAvailable"]), total=int(fields["MemTotal"]))
def read_memory(meminfo: pathlib.Path = MEMINFO) -> Memory | None:
"""The machine's memory; None where meminfo cannot be read, as off Linux."""
def read_memory(meminfo: pathlib.Path | None = None) -> Memory | None:
"""The machine's memory, read from meminfo or else MEMINFO; None where it cannot be read, as off Linux."""
try:
return parsed(meminfo.read_text())
return parsed((meminfo or MEMINFO).read_text())
except OSError:
return None
+23 -1
View File
@@ -2,9 +2,17 @@
import fcntl
import os
import pathlib
import time
import typing
CPUS_PER_SLOT = 4
# Seconds between tries while every slot is held; a slot frees as its command exits.
POLL_SECONDS = 1
def usable_cpus() -> int | None:
"""The CPUs this process may run on, which an affinity mask can make fewer than the machine's; None where the count is unknown."""
return len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count()
def slot_count(cpus: int | None) -> int:
@@ -17,7 +25,7 @@ def slot_folder(env: typing.Mapping[str, str]) -> pathlib.Path:
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."""
"""The number and open file of a slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
for slot in range(slots):
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
try:
@@ -25,5 +33,19 @@ def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
except BlockingIOError:
os.close(fd)
continue
except OSError:
os.close(fd)
raise
return slot, fd
return None
def waited_slot(folder: pathlib.Path, slots: int, say: typing.Callable[[], None], sleep: typing.Callable[[float], None] = time.sleep) -> tuple[int, int]:
"""The number and open file of a slot this call locked, once one frees. While every slot is held, it calls say once and tries again each POLL_SECONDS."""
said = False
while (taken := taken_slot(folder, slots)) is None:
if not said:
say()
said = True
sleep(POLL_SECONDS)
return taken
+28 -1
View File
@@ -1,3 +1,5 @@
import fcntl
import os
import pathlib
import sys
import tempfile
@@ -7,6 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from machine_load import memory
from machine_load.slots import slot_count
from machine_load import slots
class SlotCount(unittest.TestCase):
@@ -15,7 +18,7 @@ class SlotCount(unittest.TestCase):
self.assertEqual(slot_count(cpus), slots, cpus)
class Memory(unittest.TestCase):
class MemoryShare(unittest.TestCase):
def test_has_room_from_a_quarter_of_memory_available(self):
self.assertFalse(memory.Memory(available=3, total=16).has_room())
self.assertTrue(memory.Memory(available=4, total=16).has_room())
@@ -34,6 +37,30 @@ class Memory(unittest.TestCase):
self.assertIsNone(memory.read_memory(pathlib.Path(temp, "gone")))
class WaitedSlot(unittest.TestCase):
def test_waits_while_every_slot_is_held_saying_so_once_then_takes_the_freed_one(self):
with tempfile.TemporaryDirectory() as folder:
held = [open(pathlib.Path(folder, f"slot-{slot}"), "a") for slot in range(2)]
for file in held:
fcntl.flock(file, fcntl.LOCK_EX | fcntl.LOCK_NB)
said, slept = [], []
def sleep(seconds):
slept.append(seconds)
if len(slept) == 2:
held[1].close()
slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: said.append(True), sleep)
os.close(fd)
held[0].close()
self.assertEqual((slot, said, slept), (1, [True], [slots.POLL_SECONDS] * 2))
def test_takes_a_free_slot_at_once(self):
with tempfile.TemporaryDirectory() as folder:
slot, fd = slots.waited_slot(pathlib.Path(folder), 2, lambda: self.fail("said it waits"), lambda seconds: self.fail("slept"))
os.close(fd)
self.assertEqual(slot, 0)
if __name__ == "__main__":
unittest.main()