Skip to content

Commit 59df696

Browse files
sourcehawkclaude
andcommitted
fix(skills/bounding-heavy-commands): let one wrapper at a time check the memory and start
Two wrappers that hold different slots could both read the free memory before either command had a scope, both pass the check, and together promise more memory than the machine has. The check now runs under a lock file that all wrappers share. The wrapper keeps the lock until the scope of its command is in the slice where the next check counts it, or for at most 5 seconds. A wrapper that waits for memory frees the lock between two readings, so a command that fits can still start. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1fb65ef commit 59df696

2 files changed

Lines changed: 110 additions & 2 deletions

File tree

‎skills/bounding-heavy-commands/scripts/bounded_run.py‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
POLL_SECONDS = 2.0
6363
MEMORY_WAIT_SECONDS = 300.0
6464
SAMPLE_SECONDS = 1.0
65+
SCOPE_WAIT_SECONDS = 5.0
6566
MARGIN_EXACT = 0.25
6667
MARGIN_APPROXIMATE = 0.5
6768
BUDGET_STEP_MIB = 256
@@ -471,15 +472,19 @@ def wait_for_memory(
471472
read_available: Callable[[], Optional[int]] = available_memory_mib,
472473
read_outstanding: Callable[[], Optional[int]] = lambda: None,
473474
sleep: Callable[[float], None] = time.sleep,
475+
lock: Callable[[], None] = lambda: None,
476+
unlock: Callable[[], None] = lambda: None,
474477
) -> None:
475478
"""Returns when the free memory, less the unused budgets of running commands and the headroom, holds the budget.
476479
477480
There is no time limit, so the call can block for as long as the machine is full. Returns at once when
478481
the free memory cannot be read. read_outstanding gives None where the unused budgets cannot be counted.
482+
The call returns with lock held: the caller calls unlock once the new command counts in read_outstanding.
479483
"""
480484
waited = 0.0
481485
next_line = 0.0
482486
while True:
487+
lock()
483488
available = read_available()
484489
if available is None:
485490
log("cannot read the free memory; starting")
@@ -493,6 +498,7 @@ def wait_for_memory(
493498
if waited >= next_line:
494499
log(state + ("; waiting" if waited == 0 else "; still waiting after %ds" % waited))
495500
next_line = waited + interval_seconds
501+
unlock()
496502
sleep(poll_seconds)
497503
waited += poll_seconds
498504

@@ -591,6 +597,18 @@ def unused_budget_mib(parent: str, skip: Sequence[str]) -> int:
591597
return unused // (1024 * 1024)
592598

593599

600+
def wait_for_scope(parent: str, unit: str, limit_seconds: float, sleep: Callable[[float], None] = time.sleep) -> bool:
601+
"""Returns True when the scope of the unit is in parent, or False when it is not there after limit_seconds."""
602+
path = os.path.join(parent, unit + ".scope")
603+
waited = 0.0
604+
while not os.path.isdir(path):
605+
if waited >= limit_seconds:
606+
return False
607+
sleep(0.02)
608+
waited += 0.02
609+
return True
610+
611+
594612
def cgroup_directory(pid: int, unit: str, proc_root: str = "/proc", cgroup_root: str = "/sys/fs/cgroup") -> Optional[str]:
595613
try:
596614
with open(os.path.join(proc_root, str(pid), "cgroup")) as handle:
@@ -946,17 +964,39 @@ def read_sample() -> Optional[int]:
946964
tracker.start()
947965
trackers.append(tracker)
948966

967+
# Without one lock over the check and the start, two wrappers with different slots both pass the check before either scope counts.
968+
memory_lock_path = os.path.join(directory, "memory.lock")
969+
memory_lock: List[int] = []
970+
971+
def lock_memory() -> None:
972+
descriptor = _lock(memory_lock_path, wait=True)
973+
if descriptor is not None:
974+
memory_lock.append(descriptor)
975+
976+
def unlock_memory() -> None:
977+
while memory_lock:
978+
os.close(memory_lock.pop())
979+
980+
def on_start(pid: int) -> None:
981+
start_tracker(pid)
982+
if scopes is not None and memory_lock:
983+
if not wait_for_scope(scopes, unit, SCOPE_WAIT_SECONDS):
984+
log("the scope of the command did not appear after %ds; the next command may not count its budget" % SCOPE_WAIT_SECONDS)
985+
unlock_memory()
986+
949987
reported: Optional[int] = None
950988
reservation = reserve(directory, count, needed, exclusive_files, settings.poll_seconds)
951989
try:
952990
wait_for_memory(
953991
wait_budget, settings.memory_wait_seconds, settings.poll_seconds,
954992
headroom_mib=headroom_mib(settings.total_mib, wait_budget, most),
955993
read_available=read_available, read_outstanding=read_outstanding,
994+
lock=lock_memory, unlock=unlock_memory,
956995
)
957-
code, maxrss = run_command(command, child_environ, start_tracker)
996+
code, maxrss = run_command(command, child_environ, on_start)
958997
tracked = trackers[0].finish() if trackers else None
959998
finally:
999+
unlock_memory()
9601000
if capped:
9611001
reported = read_peak_file(peak_file)
9621002
reservation.release()

‎skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import subprocess
1010
import sys
1111
import tempfile
12+
import threading
1213
import time
1314
import unittest
1415
from pathlib import Path
@@ -793,6 +794,20 @@ def test_starts_when_the_memory_is_not_readable(self):
793794
self.assertEqual(self.wait([None], 300), [])
794795
self.assertEqual(self.lines(), ["cannot read the free memory; starting"])
795796

797+
def test_each_reading_holds_the_lock_and_the_call_returns_with_it_held(self):
798+
events = []
799+
readings = [1000, 5000]
800+
801+
def read():
802+
events.append("read")
803+
return readings.pop(0)
804+
805+
bounded_run.wait_for_memory(
806+
4096, 300, 5.0, read_available=read, sleep=lambda seconds: events.append("sleep"),
807+
lock=lambda: events.append("lock"), unlock=lambda: events.append("unlock"),
808+
)
809+
self.assertEqual(events, ["lock", "read", "unlock", "sleep", "lock", "read"])
810+
796811
def test_the_headroom_is_not_given_out(self):
797812
self.assertEqual(self.wait([5000, 5200], 300, headroom=1024), [5.0])
798813

@@ -1504,6 +1519,59 @@ def unused(parent, skip):
15041519
self.assertIn("bounded-run-2-111111.scope", skip)
15051520
self.assertTrue(any(re.match(r"^bounded-run-%d-[0-9a-f]{6}\.scope$" % os.getpid(), name) for name in skip), skip)
15061521

1522+
def run_with_scopes(self, appear_after):
1523+
"""Runs bounded() with a capped command whose scope appears in a temporary slice after appear_after seconds, or never when None.
1524+
1525+
Returns whether the memory lock was free while the scope did not exist yet, and whether it was free when the command started.
1526+
"""
1527+
scopes = os.path.join(self.base.name, "slice")
1528+
os.makedirs(scopes)
1529+
lock_path = os.path.join(self.directory, "memory.lock")
1530+
free = {}
1531+
1532+
def lock_is_free():
1533+
descriptor = bounded_run._try_lock(lock_path)
1534+
if descriptor is None:
1535+
return False
1536+
os.close(descriptor)
1537+
return True
1538+
1539+
def fake_run_command(command, environ, on_start=None):
1540+
unit = command[command.index("--inside-cap") + 2]
1541+
1542+
def appear():
1543+
time.sleep(0.2)
1544+
free["before the scope"] = lock_is_free()
1545+
if appear_after is not None:
1546+
os.mkdir(os.path.join(scopes, unit + ".scope"))
1547+
1548+
thread = threading.Thread(target=appear)
1549+
thread.start()
1550+
on_start(os.getpid())
1551+
thread.join()
1552+
free["at the start"] = lock_is_free()
1553+
return 0, 0
1554+
1555+
options = bounded_run.Options()
1556+
options.memory = "1G"
1557+
options.command = [sys.executable, "-c", "pass"]
1558+
with mock.patch.object(bounded_run, "probe_cap", return_value="0::/slice/bounded-run-1-000000-probe.scope\n"), \
1559+
mock.patch.object(bounded_run, "scope_parent_directory", return_value=scopes), \
1560+
mock.patch.object(bounded_run, "SCOPE_WAIT_SECONDS", 0.5), \
1561+
mock.patch.object(bounded_run, "run_command", fake_run_command):
1562+
self.assertEqual(bounded_run.bounded(options, self.environ), 0)
1563+
return free
1564+
1565+
def test_the_next_memory_check_waits_until_the_scope_of_the_command_counts(self):
1566+
free = self.run_with_scopes(appear_after=0.2)
1567+
self.assertEqual(free, {"before the scope": False, "at the start": True})
1568+
1569+
def test_a_scope_that_never_appears_frees_the_memory_check_after_a_time_limit(self):
1570+
started = time.monotonic()
1571+
free = self.run_with_scopes(appear_after=None)
1572+
self.assertEqual(free, {"before the scope": False, "at the start": True})
1573+
self.assertLess(time.monotonic() - started, 5)
1574+
15071575
def test_the_wait_counts_no_unused_budget_without_a_cap(self):
15081576
self.assertIsNone(self.wait_arguments(None)["read_outstanding"]())
15091577

@@ -1856,7 +1924,7 @@ def test_the_command_does_not_inherit_the_locks(self):
18561924
)
18571925
process = self.wrapper(["--memory", "4G", "--exclusive", "port"], [sys.executable, "-c", script])
18581926
output, errors = process.communicate(timeout=60)
1859-
self.assertEqual(output, "locks 4 inherited 0\n", errors)
1927+
self.assertEqual(output, "locks 5 inherited 0\n", errors)
18601928

18611929
def test_commands_with_the_same_exclusive_name_take_turns(self):
18621930
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

0 commit comments

Comments
 (0)