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
@@ -0,0 +1,35 @@
"""Ends a worker whose claude -p printed its final result and then waits on a background shell that never ends.
Claude Code's own time limit for a background command cannot do this: `BASH_DEFAULT_TIMEOUT_MS` and `BASH_MAX_TIMEOUT_MS` only raise the limit, and a call's `timeout` of up to 2 hours replaces the 10 minutes of a `claude -p` run (docs: code.claude.com/docs/en/tools-reference.md → "Time limit for background commands"). On 2026-11-18 a worker waited 95 minutes in an `until` loop whose `pgrep -f` matched its own command line.
"""
import pathlib
from loop_effects.child_shells import Shell
from loop_effects.effects import Effects, Streaming, say
# Seconds between the checks, counted from the last line the worker printed.
CHECK_EVERY = 300
# Seconds a final result must have stood, and a shell's output must have been quiet, before a shell is stopped.
SETTLED = 180
RECORD = "lingering-workers.md"
def stopped_shells(proc: Streaming, settled_at: float | None, record: pathlib.Path, effects: Effects) -> None:
"""Stops the shells of a claude that printed its final result at settled_at and is still alive, and says so on the terminal and in record. Stops nothing where the claude is still working, or a shell writes output or holds a run-heavy slot."""
now = effects.now()
if settled_at is None or now - settled_at <= SETTLED:
return
shells = proc.shells()
if any(now - shell.written <= SETTLED or shell.holds_slot for shell in shells):
return
for shell in shells:
proc.stop(shell)
line = stop_line(shell, now)
say(line, effects, stdout=True)
record.parent.mkdir(parents=True, exist_ok=True)
with record.open("a") as handle:
handle.write(f"- {effects.local_time(now)} {line}\n")
def stop_line(shell: Shell, now: float) -> str:
return f"stopped pid {shell.pid} ({int(now - shell.started)} s old, quiet {int(now - shell.written)} s) that held a worker after its final result: {shell.command}"
+1 -1
View File
@@ -122,7 +122,7 @@ def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: boo
if isinstance(answered, QuotedAnswer):
say(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", cycle.effects, stdout=True)
# worker_start runs inside the lambda: a failed attempt may have opened the session.
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, stepped), worker_environment(cycle), cycle.effects), cycle.effects):
if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered, stepped), worker_environment(cycle), cycle.project_archive, cycle.effects), cycle.effects):
return stop
path = transcript_file(cycle.session)
return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}")
+11 -2
View File
@@ -1,4 +1,7 @@
import pathlib
from claude_code.entries import AssistantTurn, ends_stream, entry_from, hit_limit, json_object, limit_said, rejected_until
from loop_claude.cycle.lingering_workers import CHECK_EVERY, RECORD, stopped_shells
from loop_effects.effects import Effects, say
from failure import Failure
from claude_code.reply import Limited
@@ -15,16 +18,22 @@ AUTO_COMPACT_WINDOW = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
COMPACT_WINDOW = 200_000
def run_worker(root: str, args: list[str], env: dict[str, str], effects: Effects) -> Failure | Limited | None:
def run_worker(root: str, args: list[str], env: dict[str, str], project_archive: pathlib.Path, effects: Effects) -> Failure | Limited | None:
wait_for_memory(effects)
try:
proc = effects.stream_claude(args, root, env)
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
result: dict | None = None
# When the last line the worker printed, if it is a result: a worker that prints on is working.
settled_at: float | None = None
resets: list[int] = []
for raw in proc.lines():
for raw in proc.lines(CHECK_EVERY):
if raw is None:
stopped_shells(proc, settled_at, project_archive / RECORD, effects)
continue
event = json_object(raw) or {}
settled_at = effects.now() if ends_stream(event) else None
if ends_stream(event):
result = event
if (resets_at := rejected_until(event)) is not None:
+5
View File
@@ -48,6 +48,11 @@ failure, keeps its window, with its last lines, and its chunk keeps its items; t
claude session is named "A <key> loop-claude <window>", so a rerun resumes a chunk left open, and is
deleted when the chunk finishes. A fresh worker is told the items the project's other chunks hold,
running or stopped: each one's own and those on its latest `Chunk items:` line, and leaves them out.
A worker whose claude printed its final result and still waits on a background shell that has
written nothing for 3 minutes loses that shell, found at the next 5-minute check. A shell that
writes, or holds a run-heavy slot, keeps the worker alive. Each stop is printed and appended to
lingering-workers.md in the project's transcript archive
(bin/loop_claude/cycle/lingering_workers.py).
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
loop-claude prints the question in the chunk's window and rings its bell. Until it is answered the
+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"])