Skip to content

Commit 07c1dbc

Browse files
sourcehawkclaude
andcommitted
fix(skills/bounding-heavy-commands): stop smaller commands from overtaking a waiting command
The wrapper kept no order among waiting commands. A command that needs many slots started only when all of them were free at the same moment, so a steady stream of smaller commands could keep it waiting for as long as the stream went on. A first measurement, which needs every slot, was the worst case, while the skill told agents that the queue puts commands in sequence. Waiters now take a blocking flock on an empty line.lock before they try for slots, and keep it until they hold their slots. Only the waiter at the head of the line tries; the others block in the kernel, which also releases the line lock of a waiter that dies. A waiter behind others logs that it waits behind other commands in the line. Two cases would stop the whole line, so the head does not keep it there. A waiter checks its exclusive names before it enters the line and leaves the line when a name is taken, so a server that holds a name does not block the commands of other names. The head also leaves the line when no slot comes free for 300 seconds, so a server that holds a slot cannot block its own client behind a command that needs that slot. reserve.lock and the all-or-nothing try stay, so an older copy of the wrapper still shares the slots safely. Closes #54 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1fb65ef commit 07c1dbc

3 files changed

Lines changed: 226 additions & 13 deletions

File tree

‎skills/bounding-heavy-commands/SKILL.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,14 @@ A part of a recorded command (one test file, one target) uses the bounded comman
9292
python3 "${CLAUDE_PLUGIN_ROOT}/skills/bounding-heavy-commands/scripts/bounded_run.py" --measure -- <command>
9393
```
9494

95-
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.
95+
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, the commands that arrive after it wait behind it, 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.
9696
6. Save the record.
9797

9898
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.
9999

100100
## Rules for the wait
101101

102-
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.
102+
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. A command that needs many slots is not overtaken by smaller commands that arrive after it. 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.
103103

104104
- **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.
105105
- **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.

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

Lines changed: 75 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
MINIMUM_RESERVE_MIB = 2048
6161
MINIMUM_HEADROOM_MIB = 1024
6262
POLL_SECONDS = 2.0
63+
LINE_SECONDS = 300.0
6364
MEMORY_WAIT_SECONDS = 300.0
6465
SAMPLE_SECONDS = 1.0
6566
MARGIN_EXACT = 0.25
@@ -413,20 +414,88 @@ def try_reserve(directory: str, count: int, needed: int, exclusive_files: Sequen
413414
os.close(turn)
414415

415416

417+
def _names_free(directory: str, exclusive_files: Sequence[str]) -> bool:
418+
for name in exclusive_files:
419+
descriptor = _try_lock(os.path.join(directory, name))
420+
if descriptor is None:
421+
return False
422+
os.close(descriptor)
423+
return True
424+
425+
426+
def _free_slots(directory: str, count: int) -> int:
427+
turn = _lock(os.path.join(directory, "reserve.lock"), wait=True)
428+
try:
429+
free = 0
430+
for index in range(count):
431+
descriptor = _try_lock(os.path.join(directory, "slot-%03d.lock" % index))
432+
if descriptor is not None:
433+
os.close(descriptor)
434+
free += 1
435+
return free
436+
finally:
437+
os.close(turn)
438+
439+
416440
def reserve(
417441
directory: str, count: int, needed: int, exclusive_files: Sequence[str], poll_seconds: float,
418442
sleep: Callable[[float], None] = time.sleep,
443+
clock: Callable[[], float] = time.monotonic,
444+
line_seconds: float = LINE_SECONDS,
419445
) -> Reservation:
420-
announced = False
446+
"""Waits in the line of all waiters, then for the slots and the exclusive names, and holds them.
447+
448+
Only the waiter at the head of the line tries for slots, so a command that arrives later cannot
449+
take the slots that the head waits for. The head leaves the line when no slot comes free for
450+
line_seconds, so a command that never ends cannot stop the whole queue.
451+
"""
452+
announced: List[bool] = []
453+
454+
def announce() -> None:
455+
if not announced:
456+
log("waiting for %d of %d slot(s)" % (needed, count))
457+
announced.append(True)
458+
459+
def pause() -> None:
460+
sleep(poll_seconds * (0.5 + random.random()))
461+
462+
line_path = os.path.join(directory, "line.lock")
463+
behind = False
421464
while True:
422-
reservation = try_reserve(directory, count, needed, exclusive_files)
465+
# A name held by a command that does not end would stop the whole line.
466+
while not _names_free(directory, exclusive_files):
467+
announce()
468+
pause()
469+
line = _lock(line_path, wait=False)
470+
if line is None:
471+
announce()
472+
if not behind:
473+
log("waiting behind other commands in the line")
474+
behind = True
475+
line = _lock(line_path, wait=True)
476+
try:
477+
reservation = None
478+
most_free = -1
479+
since = clock()
480+
while True:
481+
reservation = try_reserve(directory, count, needed, exclusive_files)
482+
if reservation is not None or not _names_free(directory, exclusive_files):
483+
break
484+
free = _free_slots(directory, count)
485+
if free > most_free:
486+
most_free, since = free, clock()
487+
elif clock() - since >= line_seconds:
488+
log("no slot came free for %ds; letting the commands behind this one try first" % line_seconds)
489+
break
490+
announce()
491+
pause()
492+
finally:
493+
os.close(line)
423494
if reservation is not None:
424495
log("holding %d of %d slot(s)" % (needed, count))
425496
return reservation
426-
if not announced:
427-
log("waiting for %d of %d slot(s)" % (needed, count))
428-
announced = True
429-
sleep(poll_seconds * (0.5 + random.random()))
497+
# The waiters behind this one need a moment to take the line before this one asks again.
498+
pause()
430499

431500

432501
def parse_meminfo(text: str) -> Optional[int]:

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

Lines changed: 149 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,81 @@ def sleep_and_check(seconds):
515515
self.addCleanup(reservation.release)
516516
self.assertTrue(turn_lock_acquired[0], "turn lock should be free while reserve waits")
517517

518+
def line_is_free(self):
519+
descriptor = os.open(os.path.join(self.directory, "line.lock"), os.O_RDWR | os.O_CREAT, 0o600)
520+
try:
521+
bounded_run.fcntl.flock(descriptor, bounded_run.fcntl.LOCK_EX | bounded_run.fcntl.LOCK_NB)
522+
return True
523+
except BlockingIOError:
524+
return False
525+
finally:
526+
os.close(descriptor)
527+
528+
def test_the_waiter_at_the_head_keeps_the_line_while_it_waits(self):
529+
blocker = bounded_run.try_reserve(self.directory, 1, 1, [])
530+
free_during_wait = []
531+
532+
def sleep(seconds):
533+
free_during_wait.append(self.line_is_free())
534+
if len(free_during_wait) == 2:
535+
blocker.release()
536+
537+
reservation = bounded_run.reserve(self.directory, 1, 1, [], 0.2, sleep=sleep)
538+
self.addCleanup(reservation.release)
539+
self.assertEqual(free_during_wait, [False, False])
540+
self.assertTrue(self.line_is_free(), "the line lock is still held after the slots were taken")
541+
542+
def test_the_head_leaves_the_line_when_no_slot_comes_free_for_the_time_limit(self):
543+
blocker = bounded_run.try_reserve(self.directory, 2, 1, [])
544+
now = [0.0]
545+
free_during_wait = []
546+
547+
def sleep(seconds):
548+
now[0] += 4.0
549+
free_during_wait.append(self.line_is_free())
550+
if len(free_during_wait) == 5:
551+
blocker.release()
552+
553+
reservation = bounded_run.reserve(
554+
self.directory, 2, 2, [], 0.2, sleep=sleep, clock=lambda: now[0], line_seconds=10.0,
555+
)
556+
self.addCleanup(reservation.release)
557+
self.assertEqual(free_during_wait[:2], [False, False])
558+
self.assertIn(True, free_during_wait[2:4])
559+
560+
def test_a_slot_that_comes_free_restarts_the_time_limit_of_the_head(self):
561+
first = bounded_run.try_reserve(self.directory, 3, 1, [])
562+
second = bounded_run.try_reserve(self.directory, 3, 1, [])
563+
now = [0.0]
564+
free_during_wait = []
565+
566+
def sleep(seconds):
567+
now[0] += 4.0
568+
free_during_wait.append(self.line_is_free())
569+
if len(free_during_wait) == 2:
570+
first.release()
571+
if len(free_during_wait) == 4:
572+
second.release()
573+
574+
reservation = bounded_run.reserve(
575+
self.directory, 3, 3, [], 0.2, sleep=sleep, clock=lambda: now[0], line_seconds=10.0,
576+
)
577+
self.addCleanup(reservation.release)
578+
self.assertEqual(free_during_wait, [False, False, False, False])
579+
580+
def test_a_waiter_does_not_keep_the_line_while_its_exclusive_name_is_held(self):
581+
holder = bounded_run.try_reserve(self.directory, 2, 1, ["exclusive-abc-port.lock"])
582+
free_during_wait = []
583+
584+
def sleep(seconds):
585+
free_during_wait.append(self.line_is_free())
586+
if len(free_during_wait) == 2:
587+
holder.release()
588+
589+
reservation = bounded_run.reserve(self.directory, 2, 1, ["exclusive-abc-port.lock"], 0.2, sleep=sleep)
590+
self.addCleanup(reservation.release)
591+
self.assertEqual(free_during_wait, [True, True])
592+
518593

519594
class LockFileTest(unittest.TestCase):
520595
def setUp(self):
@@ -1801,21 +1876,22 @@ def test_a_command_that_needs_all_slots_runs_alone(self):
18011876
self.assertEqual(process.wait(timeout=60), 0)
18021877
self.assertEqual(self.peak_concurrency(), 1)
18031878

1804-
def test_a_waiting_command_holds_no_slot(self):
1879+
def test_a_waiting_command_holds_no_slot_and_is_not_overtaken(self):
18051880
release = os.path.join(self.base.name, "release")
18061881
long_holder = self.worker("holder", "2G", hold="300", release=release) # runs until the release file below ends it early
18071882
self.wait_for_event("start", "holder")
18081883
large = self.worker("large", "4G", hold="0") # ends at once once it gets its slots; the test waits for it to end
18091884
self.wait_for_stderr(large, "waiting for")
1885+
self.assertEqual(bounded_run._free_slots(self.environ["BOUNDED_RUN_LOCK_DIR"], 2), 1)
18101886
small = self.worker("small", "2G", hold="0") # ends at once; the test waits for it to end
1811-
self.assertEqual(small.wait(timeout=60), 0)
1812-
names = [line.split()[1] for line in self.read_events() if line.startswith("end ")]
1813-
self.assertEqual(names, ["small"])
1887+
self.wait_for_stderr(small, "behind other commands")
18141888
Path(release).write_text("")
18151889
self.assertEqual(large.wait(timeout=60), 0)
1890+
self.assertEqual(small.wait(timeout=60), 0)
18161891
self.assertEqual(long_holder.wait(timeout=60), 0)
18171892
order = [line.split()[:2] for line in self.read_events()]
18181893
self.assertLess(order.index(["end", "holder"]), order.index(["start", "large"]))
1894+
self.assertLess(order.index(["start", "large"]), order.index(["start", "small"]))
18191895

18201896
def test_a_hard_kill_of_the_wrapper_frees_the_slots_at_once(self):
18211897
holder = self.worker("holder", "4G", hold="300") # runs until the kill below ends it
@@ -1856,7 +1932,7 @@ def test_the_command_does_not_inherit_the_locks(self):
18561932
)
18571933
process = self.wrapper(["--memory", "4G", "--exclusive", "port"], [sys.executable, "-c", script])
18581934
output, errors = process.communicate(timeout=60)
1859-
self.assertEqual(output, "locks 4 inherited 0\n", errors)
1935+
self.assertEqual(output, "locks 5 inherited 0\n", errors)
18601936

18611937
def test_commands_with_the_same_exclusive_name_take_turns(self):
18621938
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
@@ -2039,6 +2115,74 @@ def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self):
20392115
holder.send_signal(signal.SIGTERM)
20402116
self.assertEqual(holder.wait(timeout=60), 143)
20412117

2118+
def hold_the_line(self):
2119+
os.makedirs(self.environ["BOUNDED_RUN_LOCK_DIR"], exist_ok=True)
2120+
descriptor = os.open(os.path.join(self.environ["BOUNDED_RUN_LOCK_DIR"], "line.lock"), os.O_RDWR | os.O_CREAT, 0o600)
2121+
bounded_run.fcntl.flock(descriptor, bounded_run.fcntl.LOCK_EX)
2122+
return descriptor
2123+
2124+
def test_an_interrupt_behind_others_in_the_line_gives_130_and_no_traceback(self):
2125+
line = self.hold_the_line()
2126+
self.addCleanup(os.close, line)
2127+
waiting = self.worker("waiting", "2G", hold="0") # never reached; interrupted while still in the line
2128+
self.wait_for_stderr(waiting, "behind other commands")
2129+
waiting.send_signal(signal.SIGINT)
2130+
self.assertEqual(waiting.wait(timeout=10), 130)
2131+
buffer = self.stderr_of(waiting)
2132+
self.assertNotIn("Traceback", buffer)
2133+
self.assertIn("interrupted while waiting", buffer)
2134+
2135+
def test_a_waiter_that_dies_in_the_line_does_not_block_the_next(self):
2136+
release = os.path.join(self.base.name, "release")
2137+
holder = self.worker("holder", "2G", hold="300", release=release) # runs until the release file below ends it
2138+
self.wait_for_event("start", "holder")
2139+
head = self.worker("head", "4G", hold="0") # killed while it waits at the head of the line
2140+
self.wait_for_stderr(head, "waiting for")
2141+
follower = self.worker("follower", "4G", hold="0") # ends at once once it gets its slots
2142+
self.wait_for_stderr(follower, "behind other commands")
2143+
head.kill()
2144+
head.wait(timeout=60)
2145+
Path(release).write_text("")
2146+
self.assertEqual(holder.wait(timeout=60), 0)
2147+
self.assertEqual(follower.wait(timeout=30), 0)
2148+
directory = self.environ["BOUNDED_RUN_LOCK_DIR"]
2149+
for name in os.listdir(directory):
2150+
self.assertTrue(name.endswith(".lock"), name)
2151+
self.assertEqual(os.path.getsize(os.path.join(directory, name)), 0, name)
2152+
2153+
def a_large_command_starts_under_a_steady_stream_of_small_commands(self, options, command):
2154+
"""Keeps at least one slot held by 1-slot commands, and fails when the large command does not start in time."""
2155+
large = None
2156+
stream = []
2157+
deadline = time.time() + 30
2158+
try:
2159+
while time.time() < deadline:
2160+
if sum(1 for process in stream if process.poll() is None) < 4:
2161+
stream.append(self.worker("small%d" % len(stream), "2G", hold="0.3")) # brief; the test waits for each to end
2162+
if large is None and len(stream) >= 4:
2163+
self.wait_for_event("start", "small0")
2164+
large = self.wrapper(options, command)
2165+
if large is not None and any(line.split()[:2] == ["start", "large"] for line in self.read_events()):
2166+
break
2167+
time.sleep(0.05)
2168+
else:
2169+
self.fail("the large command did not start within 30 seconds, while %d small commands started" % len(stream))
2170+
finally:
2171+
for process in stream:
2172+
process.wait(timeout=60)
2173+
self.assertEqual(large.wait(timeout=60), 0)
2174+
self.assertGreater(len([line for line in self.read_events() if line.startswith("start small")]), 4)
2175+
2176+
def test_a_command_that_needs_all_slots_starts_while_small_commands_keep_arriving(self):
2177+
self.a_large_command_starts_under_a_steady_stream_of_small_commands(
2178+
["--memory", "4G"], [sys.executable, "-c", WORKER, "large"],
2179+
)
2180+
2181+
def test_a_first_measurement_starts_while_small_commands_keep_arriving(self):
2182+
self.a_large_command_starts_under_a_steady_stream_of_small_commands(
2183+
["--measure"], [sys.executable, "-c", WORKER, "large"],
2184+
)
2185+
20422186

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

0 commit comments

Comments
 (0)