Skip to content

Commit 62edffa

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 9ad86b7 commit 62edffa

3 files changed

Lines changed: 225 additions & 12 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
SCOPE_WAIT_SECONDS = 5.0
@@ -414,20 +415,88 @@ def try_reserve(directory: str, count: int, needed: int, exclusive_files: Sequen
414415
os.close(turn)
415416

416417

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

432501

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

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

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

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

520595
class LockFileTest(unittest.TestCase):
521596
def setUp(self):
@@ -1892,21 +1967,22 @@ def test_a_command_that_needs_all_slots_runs_alone(self):
18921967
self.assertEqual(process.wait(timeout=60), 0)
18931968
self.assertEqual(self.peak_concurrency(), 1)
18941969

1895-
def test_a_waiting_command_holds_no_slot(self):
1970+
def test_a_waiting_command_holds_no_slot_and_is_not_overtaken(self):
18961971
release = os.path.join(self.base.name, "release")
18971972
long_holder = self.worker("holder", "2G", hold="300", release=release) # runs until the release file below ends it early
18981973
self.wait_for_event("start", "holder")
18991974
large = self.worker("large", "4G", hold="0") # ends at once once it gets its slots; the test waits for it to end
19001975
self.wait_for_stderr(large, "waiting for")
1976+
self.assertEqual(bounded_run._free_slots(self.environ["BOUNDED_RUN_LOCK_DIR"], 2), 1)
19011977
small = self.worker("small", "2G", hold="0") # ends at once; the test waits for it to end
1902-
self.assertEqual(small.wait(timeout=60), 0)
1903-
names = [line.split()[1] for line in self.read_events() if line.startswith("end ")]
1904-
self.assertEqual(names, ["small"])
1978+
self.wait_for_stderr(small, "behind other commands")
19051979
Path(release).write_text("")
19061980
self.assertEqual(large.wait(timeout=60), 0)
1981+
self.assertEqual(small.wait(timeout=60), 0)
19071982
self.assertEqual(long_holder.wait(timeout=60), 0)
19081983
order = [line.split()[:2] for line in self.read_events()]
19091984
self.assertLess(order.index(["end", "holder"]), order.index(["start", "large"]))
1985+
self.assertLess(order.index(["start", "large"]), order.index(["start", "small"]))
19101986

19111987
def test_a_hard_kill_of_the_wrapper_frees_the_slots_at_once(self):
19121988
holder = self.worker("holder", "4G", hold="300") # runs until the kill below ends it
@@ -2130,6 +2206,74 @@ def test_an_interrupt_in_the_queue_gives_130_and_no_traceback(self):
21302206
holder.send_signal(signal.SIGTERM)
21312207
self.assertEqual(holder.wait(timeout=60), 143)
21322208

2209+
def hold_the_line(self):
2210+
os.makedirs(self.environ["BOUNDED_RUN_LOCK_DIR"], exist_ok=True)
2211+
descriptor = os.open(os.path.join(self.environ["BOUNDED_RUN_LOCK_DIR"], "line.lock"), os.O_RDWR | os.O_CREAT, 0o600)
2212+
bounded_run.fcntl.flock(descriptor, bounded_run.fcntl.LOCK_EX)
2213+
return descriptor
2214+
2215+
def test_an_interrupt_behind_others_in_the_line_gives_130_and_no_traceback(self):
2216+
line = self.hold_the_line()
2217+
self.addCleanup(os.close, line)
2218+
waiting = self.worker("waiting", "2G", hold="0") # never reached; interrupted while still in the line
2219+
self.wait_for_stderr(waiting, "behind other commands")
2220+
waiting.send_signal(signal.SIGINT)
2221+
self.assertEqual(waiting.wait(timeout=10), 130)
2222+
buffer = self.stderr_of(waiting)
2223+
self.assertNotIn("Traceback", buffer)
2224+
self.assertIn("interrupted while waiting", buffer)
2225+
2226+
def test_a_waiter_that_dies_in_the_line_does_not_block_the_next(self):
2227+
release = os.path.join(self.base.name, "release")
2228+
holder = self.worker("holder", "2G", hold="300", release=release) # runs until the release file below ends it
2229+
self.wait_for_event("start", "holder")
2230+
head = self.worker("head", "4G", hold="0") # killed while it waits at the head of the line
2231+
self.wait_for_stderr(head, "waiting for")
2232+
follower = self.worker("follower", "4G", hold="0") # ends at once once it gets its slots
2233+
self.wait_for_stderr(follower, "behind other commands")
2234+
head.kill()
2235+
head.wait(timeout=60)
2236+
Path(release).write_text("")
2237+
self.assertEqual(holder.wait(timeout=60), 0)
2238+
self.assertEqual(follower.wait(timeout=30), 0)
2239+
directory = self.environ["BOUNDED_RUN_LOCK_DIR"]
2240+
for name in os.listdir(directory):
2241+
self.assertTrue(name.endswith(".lock"), name)
2242+
self.assertEqual(os.path.getsize(os.path.join(directory, name)), 0, name)
2243+
2244+
def a_large_command_starts_under_a_steady_stream_of_small_commands(self, options, command):
2245+
"""Keeps at least one slot held by 1-slot commands, and fails when the large command does not start in time."""
2246+
large = None
2247+
stream = []
2248+
deadline = time.time() + 30
2249+
try:
2250+
while time.time() < deadline:
2251+
if sum(1 for process in stream if process.poll() is None) < 4:
2252+
stream.append(self.worker("small%d" % len(stream), "2G", hold="0.3")) # brief; the test waits for each to end
2253+
if large is None and len(stream) >= 4:
2254+
self.wait_for_event("start", "small0")
2255+
large = self.wrapper(options, command)
2256+
if large is not None and any(line.split()[:2] == ["start", "large"] for line in self.read_events()):
2257+
break
2258+
time.sleep(0.05)
2259+
else:
2260+
self.fail("the large command did not start within 30 seconds, while %d small commands started" % len(stream))
2261+
finally:
2262+
for process in stream:
2263+
process.wait(timeout=60)
2264+
self.assertEqual(large.wait(timeout=60), 0)
2265+
self.assertGreater(len([line for line in self.read_events() if line.startswith("start small")]), 4)
2266+
2267+
def test_a_command_that_needs_all_slots_starts_while_small_commands_keep_arriving(self):
2268+
self.a_large_command_starts_under_a_steady_stream_of_small_commands(
2269+
["--memory", "4G"], [sys.executable, "-c", WORKER, "large"],
2270+
)
2271+
2272+
def test_a_first_measurement_starts_while_small_commands_keep_arriving(self):
2273+
self.a_large_command_starts_under_a_steady_stream_of_small_commands(
2274+
["--measure"], [sys.executable, "-c", WORKER, "large"],
2275+
)
2276+
21332277

21342278
@unittest.skipUnless(
21352279
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)