End a worker that lingers after its final result by stopping the quiet background shells it left
CI / tests (pull_request) Failing after 4m10s

This commit is contained in:
2026-11-18 16:53:30 +01:00
parent aa34fb8912
commit 72ffb9f748
9 changed files with 272 additions and 15 deletions
+67 -7
View File
@@ -30,7 +30,7 @@ from claude_code import entries, reply, session
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished
from git_cli.git_repo import git
from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker
from loop_claude.cycle import interrupt, judge, lingering_workers, prompts, retry, run, spend, states, worker
from claude_code.reply import Limited
from loop_claude.loop import main, reload, routing_check, this_loop, usage
from machine_load import memory
@@ -43,6 +43,7 @@ from model_routing.ladder import ProjectRung, Rung
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route, route_from, WorkerLine
from loop_claude import routing
from loop_effects.child_shells import Shell
from loop_claude.stop import Stop
from loop_claude import tmux
from claude_code.tokens import Tokens, tokens_of
@@ -212,12 +213,26 @@ class Worker:
class Streamed:
def __init__(self, code, *events):
"""A started claude. An event of None is an idle stretch of CHECK_EVERY seconds, which advances `clock` by that; `held` are the shells it has, and `stopped` collects the ones stopped."""
def __init__(self, code, *events, clock=None, held=()):
self.code = code
self.events = events or ({"type": "result"},)
self.clock = clock
self.held = list(held)
self.stopped = []
def lines(self):
return [json.dumps(event) + "\n" for event in self.events]
def lines(self, idle):
for event in self.events:
if event is None:
self.clock[0] += idle
yield None if event is None else json.dumps(event) + "\n"
def shells(self):
return self.held
def stop(self, shell):
self.stopped.append(shell)
def wait(self):
return self.code
@@ -740,7 +755,7 @@ class Limits(unittest.TestCase):
allowed = {"type": "rate_limit_event", "rate_limit_info": {"status": "allowed", "resetsAt": NOW + 9000}}
limited = {"type": "result", "api_error_status": 429, "result": "You've hit your session limit"}
fake = FakeEffects(streams=[Streamed(1, rejected[1], allowed, rejected[0], limited)])
self.assertEqual(worker.run_worker("/r", [], {}, fake.effects()), Limited(NOW + 600, "You've hit your session limit"))
self.assertEqual(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), fake.effects()), Limited(NOW + 600, "You've hit your session limit"))
def test_a_limit_outranks_the_exit_code_and_its_message_fits_one_line(self):
def limited(**said):
@@ -762,18 +777,63 @@ class Limits(unittest.TestCase):
self.assertEqual(entries.rejected_until({"type": "rate_limit_event", "rate_limit_info": info}), want)
class LingeringWorkers(unittest.TestCase):
RESULT = {"type": "result"}
def worker_with(self, *events, held=()):
"""Runs a worker whose claude prints events and holds shells `held`; returns the claude, what loop-claude said and the record's text."""
clock = [NOW]
streamed = Streamed(0, *events, clock=clock, held=held)
fake = FakeEffects(streams=[streamed])
effects = dataclasses.replace(fake.effects(), now=lambda: clock[0])
with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()) as said:
worker.run_worker("/r", [], {}, pathlib.Path(folder), effects)
record = pathlib.Path(folder, lingering_workers.RECORD)
return streamed, said.getvalue(), record.read_text() if record.exists() else ""
def shell(self, written=NOW - 1000, holds_slot=False):
return Shell(pid=7, started=NOW - 1000, command="until false; do sleep 15; done", written=written, holds_slot=holds_slot)
def test_a_worker_that_lingers_after_its_result_loses_its_quiet_shell_and_the_stop_is_said_and_recorded(self):
shell = self.shell()
streamed, said, record = self.worker_with(self.RESULT, None, held=[shell])
self.assertEqual(streamed.stopped, [shell])
line = f"stopped pid 7 (1300 s old, quiet 1300 s) that held a worker after its final result: {shell.command}"
self.assertEqual(said, f"<{NOW + 300}> {line}\n")
self.assertEqual(record, f"- <{NOW + 300}> {line}\n")
def test_nothing_is_stopped_where_the_worker_printed_after_its_result_or_no_check_came_due(self):
for events in ((self.RESULT, {"type": "assistant", "message": {"content": []}}, None), (self.RESULT,), (None,), ({"type": "assistant", "message": {"content": []}}, None)):
with self.subTest(events=events):
streamed, said, record = self.worker_with(*events, held=[self.shell()])
self.assertEqual((streamed.stopped, said, record), ([], "", ""))
def test_nothing_is_stopped_while_a_shell_writes_output_or_holds_a_heavy_slot(self):
for busy in (self.shell(written=NOW + 200), self.shell(holds_slot=True)):
with self.subTest(busy=busy):
streamed, _, _ = self.worker_with(self.RESULT, None, held=[self.shell(), busy])
self.assertEqual(streamed.stopped, [])
def test_a_check_before_the_result_has_stood_long_enough_stops_nothing(self):
fake = FakeEffects()
effects = dataclasses.replace(fake.effects(), now=lambda: NOW + lingering_workers.SETTLED)
proc = Streamed(0, held=[self.shell()])
lingering_workers.stopped_shells(proc, NOW, pathlib.Path("/unused"), effects)
self.assertEqual(proc.stopped, [])
class MemoryWait(unittest.TestCase):
def test_a_worker_starts_only_once_a_quarter_of_memory_is_available(self):
fake = FakeEffects(free_memory=[memory.Memory(available=3, total=16), memory.Memory(available=3, total=16), memory.Memory(available=4, total=16)], streams=[Streamed(0)])
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertIsNone(worker.run_worker("/r", [], {}, fake.effects()))
self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), fake.effects()))
self.assertEqual([seam for seam, _ in fake.calls], ["memory", "sleep", "memory", "sleep", "memory", "stream_claude"])
self.assertEqual(fake.made("sleep"), [worker.MEMORY_POLL] * 2)
self.assertEqual(said.getvalue().count("waiting"), 1, said.getvalue())
def test_a_worker_starts_at_once_where_memory_cannot_be_read(self):
fake = FakeEffects(free_memory=[None], streams=[Streamed(0)])
self.assertIsNone(worker.run_worker("/r", [], {}, fake.effects()))
self.assertIsNone(worker.run_worker("/r", [], {}, pathlib.Path("/archive"), fake.effects()))
self.assertEqual([seam for seam, _ in fake.calls], ["memory", "stream_claude"])