Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions skills/bounding-heavy-commands/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,14 @@ A part of a recorded command (one test file, one target) uses the bounded comman
python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure -- <command>
```

5. Record the suggested budget that the wrapper prints, but only from a run in which the command did its full work. It is the peak plus a margin, and the margin is larger where the measurement is approximate. A run that stopped early gives a peak that is too small: a suite that stops at its first failure, a command that failed at its start, a run that a signal or the hard cap stopped. Do not record the budget of such a run, and save no record for the command yet. Run the command with `--measure` again each time that you run it, until one run does its full work. A measurement with no `--memory` takes the whole queue, because the peak of the command is not known: it waits until no other bounded command runs, and no other starts while it runs. When it waits, tell the user that a first measurement waits for the other bounded commands to end. If the hard cap stopped a measurement with `--memory`, measure again with two times that budget. If it stopped a measurement with no `--memory`, the command needs more memory than the queue has: tell the user, with the budget that the wrapper printed.
5. Record the suggested budget that the wrapper prints, but only from a run in which the command did its full work. It is the peak plus a margin, and the margin is larger where the measurement is approximate. A run that stopped early gives a peak that is too small: a suite that stops at its first failure, a command that failed at its start, a run that a signal or the hard cap stopped. Do not record the budget of such a run, and save no record for the command yet. Run the command with `--measure` again each time that you run it, until one run does its full work. A measurement with no `--memory` takes the whole queue, because the peak of the command is not known: it waits until no other bounded command runs, and no other starts while it runs. While it is at the head of the line, the commands behind it wait too (§Rules for the wait). When it waits, tell the user that a first measurement waits for the other bounded commands to end. If the hard cap stopped a measurement with `--memory`, measure again with two times that budget. If it stopped a measurement with no `--memory`, the command needs more memory than the queue has: tell the user, with the budget that the wrapper printed.
6. Save the record.

The measured run is a real run of the command. Its result counts, also when the run stopped early, 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 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.
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. Waiting commands take turns in a line. Only the command at the head of the line tries for slots, so the smaller commands behind it do not take the slots that it waits for. The line has no fixed order, and a head that sees no slot come free for 5 minutes lets the commands behind it try first. So a small command can wait behind a large one, also when a slot is free. 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. 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.
Expand Down
81 changes: 75 additions & 6 deletions skills/bounding-heavy-commands/scripts/bounded_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
MINIMUM_RESERVE_MIB = 2048
MINIMUM_HEADROOM_MIB = 1024
POLL_SECONDS = 2.0
LINE_SECONDS = 300.0
MEMORY_WAIT_SECONDS = 300.0
SAMPLE_SECONDS = 1.0
SCOPE_WAIT_SECONDS = 5.0
Expand Down Expand Up @@ -414,20 +415,88 @@ def try_reserve(directory: str, count: int, needed: int, exclusive_files: Sequen
os.close(turn)


def _names_free(directory: str, exclusive_files: Sequence[str]) -> bool:
for name in exclusive_files:
descriptor = _try_lock(os.path.join(directory, name))
if descriptor is None:
return False
os.close(descriptor)
return True


def _free_slots(directory: str, count: int) -> int:
turn = _lock(os.path.join(directory, "reserve.lock"), wait=True)
try:
free = 0
for index in range(count):
descriptor = _try_lock(os.path.join(directory, "slot-%03d.lock" % index))
if descriptor is not None:
os.close(descriptor)
free += 1
return free
finally:
os.close(turn)


def reserve(
directory: str, count: int, needed: int, exclusive_files: Sequence[str], poll_seconds: float,
sleep: Callable[[float], None] = time.sleep,
clock: Callable[[], float] = time.monotonic,
line_seconds: float = LINE_SECONDS,
) -> Reservation:
announced = False
"""Waits in the line of all waiters, then for the slots and the exclusive names, and holds them.

Only the waiter at the head of the line tries for slots, so a command that arrives later cannot
take the slots that the head waits for. The head leaves the line when no slot comes free for
line_seconds, so a command that never ends cannot stop the whole queue.
"""
announced: List[bool] = []

def announce() -> None:
if not announced:
log("waiting for %d of %d slot(s)" % (needed, count))
announced.append(True)

def pause() -> None:
sleep(poll_seconds * (0.5 + random.random()))

line_path = os.path.join(directory, "line.lock")
behind = False
while True:
reservation = try_reserve(directory, count, needed, exclusive_files)
# A name held by a command that does not end would stop the whole line.
while not _names_free(directory, exclusive_files):
announce()
pause()
line = _lock(line_path, wait=False)
if line is None:
announce()
if not behind:
log("waiting behind other commands in the line")
behind = True
line = _lock(line_path, wait=True)
Comment thread
sourcehawk marked this conversation as resolved.
Resolved
try:
reservation = None
most_free = -1
since = clock()
while True:
reservation = try_reserve(directory, count, needed, exclusive_files)
if reservation is not None or not _names_free(directory, exclusive_files):
break
free = _free_slots(directory, count)
if free > most_free:
most_free, since = free, clock()
elif clock() - since >= line_seconds:
log("no slot came free for %ds; letting the commands behind this one try first" % line_seconds)
break
announce()
pause()
finally:
os.close(line)
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()))
# The waiters behind this one need a moment to take the line before this one asks again.
pause()


def parse_meminfo(text: str) -> Optional[int]:
Expand Down
154 changes: 149 additions & 5 deletions skills/bounding-heavy-commands/scripts/tests/test_bounded_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,81 @@ def sleep_and_check(seconds):
self.addCleanup(reservation.release)
self.assertTrue(turn_lock_acquired[0], "turn lock should be free while reserve waits")

def line_is_free(self):
descriptor = os.open(os.path.join(self.directory, "line.lock"), os.O_RDWR | os.O_CREAT, 0o600)
try:
bounded_run.fcntl.flock(descriptor, bounded_run.fcntl.LOCK_EX | bounded_run.fcntl.LOCK_NB)
return True
except BlockingIOError:
return False
finally:
os.close(descriptor)

def test_the_waiter_at_the_head_keeps_the_line_while_it_waits(self):
blocker = bounded_run.try_reserve(self.directory, 1, 1, [])
free_during_wait = []

def sleep(seconds):
free_during_wait.append(self.line_is_free())
if len(free_during_wait) == 2:
blocker.release()

reservation = bounded_run.reserve(self.directory, 1, 1, [], 0.2, sleep=sleep)
self.addCleanup(reservation.release)
self.assertEqual(free_during_wait, [False, False])
self.assertTrue(self.line_is_free(), "the line lock is still held after the slots were taken")

def test_the_head_leaves_the_line_when_no_slot_comes_free_for_the_time_limit(self):
blocker = bounded_run.try_reserve(self.directory, 2, 1, [])
now = [0.0]
free_during_wait = []

def sleep(seconds):
now[0] += 4.0
free_during_wait.append(self.line_is_free())
if len(free_during_wait) == 5:
blocker.release()

reservation = bounded_run.reserve(
self.directory, 2, 2, [], 0.2, sleep=sleep, clock=lambda: now[0], line_seconds=10.0,
)
self.addCleanup(reservation.release)
self.assertEqual(free_during_wait[:2], [False, False])
self.assertIn(True, free_during_wait[2:4])

def test_a_slot_that_comes_free_restarts_the_time_limit_of_the_head(self):
first = bounded_run.try_reserve(self.directory, 3, 1, [])
second = bounded_run.try_reserve(self.directory, 3, 1, [])
now = [0.0]
free_during_wait = []

def sleep(seconds):
now[0] += 4.0
free_during_wait.append(self.line_is_free())
if len(free_during_wait) == 2:
first.release()
if len(free_during_wait) == 4:
second.release()

reservation = bounded_run.reserve(
self.directory, 3, 3, [], 0.2, sleep=sleep, clock=lambda: now[0], line_seconds=10.0,
)
self.addCleanup(reservation.release)
self.assertEqual(free_during_wait, [False, False, False, False])

def test_a_waiter_does_not_keep_the_line_while_its_exclusive_name_is_held(self):
holder = bounded_run.try_reserve(self.directory, 2, 1, ["exclusive-abc-port.lock"])
free_during_wait = []

def sleep(seconds):
free_during_wait.append(self.line_is_free())
if len(free_during_wait) == 2:
holder.release()

reservation = bounded_run.reserve(self.directory, 2, 1, ["exclusive-abc-port.lock"], 0.2, sleep=sleep)
self.addCleanup(reservation.release)
self.assertEqual(free_during_wait, [True, True])


class LockFileTest(unittest.TestCase):
def setUp(self):
Expand Down Expand Up @@ -1925,21 +2000,22 @@ def test_a_command_that_needs_all_slots_runs_alone(self):
self.assertEqual(process.wait(timeout=60), 0)
self.assertEqual(self.peak_concurrency(), 1)

def test_a_waiting_command_holds_no_slot(self):
def test_a_waiting_command_holds_no_slot_and_is_not_overtaken(self):
release = os.path.join(self.base.name, "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") # ends at once once it gets its slots; the test waits for it to end
self.wait_for_stderr(large, "waiting for")
self.assertEqual(bounded_run._free_slots(self.environ["BOUNDED_RUN_LOCK_DIR"], 2), 1)
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"])
self.wait_for_stderr(small, "behind other commands")
Path(release).write_text("")
self.assertEqual(large.wait(timeout=60), 0)
self.assertEqual(small.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"]))
self.assertLess(order.index(["start", "large"]), order.index(["start", "small"]))

def test_a_hard_kill_of_the_wrapper_frees_the_slots_at_once(self):
holder = self.worker("holder", "4G", hold="300") # runs until the kill below ends it
Expand Down Expand Up @@ -1980,7 +2056,7 @@ def test_the_command_does_not_inherit_the_locks(self):
)
process = self.wrapper(["--memory", "4G", "--exclusive", "port"], [sys.executable, "-c", script])
output, errors = process.communicate(timeout=60)
self.assertEqual(output, "locks 5 inherited 0\n", errors)
self.assertEqual(output, "locks 6 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)] # brief; the test waits for each to end
Expand Down Expand Up @@ -2163,6 +2239,74 @@ def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self):
holder.send_signal(signal.SIGTERM)
self.assertEqual(holder.wait(timeout=60), 143)

def hold_the_line(self):
os.makedirs(self.environ["BOUNDED_RUN_LOCK_DIR"], exist_ok=True)
descriptor = os.open(os.path.join(self.environ["BOUNDED_RUN_LOCK_DIR"], "line.lock"), os.O_RDWR | os.O_CREAT, 0o600)
bounded_run.fcntl.flock(descriptor, bounded_run.fcntl.LOCK_EX)
return descriptor

def test_an_interrupt_behind_others_in_the_line_gives_130_and_no_traceback(self):
line = self.hold_the_line()
self.addCleanup(os.close, line)
waiting = self.worker("waiting", "2G", hold="0") # never reached; interrupted while still in the line
self.wait_for_stderr(waiting, "behind other commands")
waiting.send_signal(signal.SIGINT)
self.assertEqual(waiting.wait(timeout=10), 130)
buffer = self.stderr_of(waiting)
self.assertNotIn("Traceback", buffer)
self.assertIn("interrupted while waiting", buffer)

def test_a_waiter_that_dies_in_the_line_does_not_block_the_next(self):
release = os.path.join(self.base.name, "release")
holder = self.worker("holder", "2G", hold="300", release=release) # runs until the release file below ends it
self.wait_for_event("start", "holder")
head = self.worker("head", "4G", hold="0") # killed while it waits at the head of the line
self.wait_for_stderr(head, "waiting for")
follower = self.worker("follower", "4G", hold="0") # ends at once once it gets its slots
self.wait_for_stderr(follower, "behind other commands")
head.kill()
head.wait(timeout=60)
Path(release).write_text("")
self.assertEqual(holder.wait(timeout=60), 0)
self.assertEqual(follower.wait(timeout=30), 0)
directory = self.environ["BOUNDED_RUN_LOCK_DIR"]
for name in os.listdir(directory):
self.assertTrue(name.endswith(".lock"), name)
self.assertEqual(os.path.getsize(os.path.join(directory, name)), 0, name)

def a_large_command_starts_under_a_steady_stream_of_small_commands(self, options, command):
"""Keeps at least one slot held by 1-slot commands, and fails when the large command does not start in time."""
large = None
stream = []
deadline = time.time() + 30
try:
while time.time() < deadline:
if sum(1 for process in stream if process.poll() is None) < 4:
stream.append(self.worker("small%d" % len(stream), "2G", hold="0.3")) # brief; the test waits for each to end
if large is None and len(stream) >= 4:
self.wait_for_event("start", "small0")
large = self.wrapper(options, command)
if large is not None and any(line.split()[:2] == ["start", "large"] for line in self.read_events()):
break
time.sleep(0.05)
else:
self.fail("the large command did not start within 30 seconds, while %d small commands started" % len(stream))
finally:
for process in stream:
process.wait(timeout=60)
self.assertEqual(large.wait(timeout=60), 0)
self.assertGreater(len([line for line in self.read_events() if line.startswith("start small")]), 4)

def test_a_command_that_needs_all_slots_starts_while_small_commands_keep_arriving(self):
self.a_large_command_starts_under_a_steady_stream_of_small_commands(
["--memory", "4G"], [sys.executable, "-c", WORKER, "large"],
)

def test_a_first_measurement_starts_while_small_commands_keep_arriving(self):
self.a_large_command_starts_under_a_steady_stream_of_small_commands(
["--measure"], [sys.executable, "-c", WORKER, "large"],
)


@unittest.skipUnless(
bounded_run.choose_cap_prefix(256, 1, "bounded-run-test-%d" % os.getpid(), bounded_run.probe_cap) is not None,
Expand Down
Loading