Judge a worker that stalls before its result with a headless claude, and report the verdict without a kill
CI / tests (pull_request) Failing after 4m3s

This commit is contained in:
2026-11-19 08:55:14 +01:00
parent a559bbfcbf
commit 08038d93eb
10 changed files with 327 additions and 20 deletions
+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=== {cycle.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.project_archive, 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.project.rung if cycle.project else cycle.route.rung, 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}")
+91
View File
@@ -0,0 +1,91 @@
"""Asks a headless claude whether a worker that prints nothing before its final result is stuck, where one of its shells shows a sign of it, and reports the verdict.
A worker can stall on a command that hangs, as a full test run did on a shell that ignored SIGINT (item 402). The check runs on the tick `lingering_workers` uses, CHECK_EVERY seconds after the worker's last line, so a worker that prints is never checked. A shell shows a sign where it used no CPU since the last check and wrote nothing for QUIET seconds, or where it is older than OLD; one that runs a busy tool, as `Shell.runs_busy_tool` says, shows none, since a wait for a gate is work. Each chunk's loop checks its own worker: no process watches a whole tmux session, and the shells' commands, processes and output hold what the worker's pane shows.
The verdict is only reported, on the terminal and in RECORD in the project's transcript archive, and kills nothing until its verdicts have matched what the human would have done.
"""
import dataclasses
import json
import pathlib
import typing
from agent_cycle.lingering_workers import CHECK_EVERY, QUIET
from claude_code.entries import structured_output
from claude_code.reply import claude_reply, Limited
from failure import Failure
from loop_effects.child_shells import Shell
from loop_effects.effects import Effects, say, Streaming
from model_routing.ladder import Rung
from text_files.utc_stamp import utc
# Seconds after which a shell holds a worker longer than a chunk usually runs.
OLD = 4 * 3600
RECORD = "stuck-workers.md"
VERDICTS = ("working", "waiting on a person", "stuck")
SCHEMA = {
"type": "object",
"properties": {
"verdict": {"enum": list(VERDICTS)},
"process": {"type": "integer", "description": "The pid of the process that holds the worker, from the evidence."},
"why": {"type": "string", "description": "One sentence on why that process holds it."},
},
"required": ["verdict", "process", "why"],
"additionalProperties": False,
}
PROMPT = f"""A headless Claude Code worker has printed nothing for {CHECK_EVERY} seconds. Judge from its shells below whether it is `working`, `waiting on a person` or `stuck`, and name the pid of the process that holds it and why.
A worker that waits on a gate, such as run-heavy's wait for a slot or a test run that still writes output or uses CPU, is working. Stuck means the process will not finish on its own, as a command waiting on a child that never exits.
"""
@dataclasses.dataclass
class Watch:
"""What checks a worker for stuck shells: the rung its investigations run on, the project's transcript archive, and each shell's CPU seconds at the last check."""
rung: Rung
archive: pathlib.Path
cpu: dict[int, float] = dataclasses.field(default_factory=dict)
def check(self, proc: Streaming, root: str, effects: Effects) -> None:
"""Investigates the worker whose claude is proc where a shell shows a sign, and says the verdict on the terminal and in RECORD; a failed investigation is said on stderr."""
now = effects.now()
shells = proc.shells()
signs = [sign for shell in shells if (sign := sign_of(shell, self.cpu.get(shell.pid), now))]
self.cpu = {shell.pid: shell.cpu for shell in shells}
if not signs:
return
judged = investigated(shells, self.rung, root, effects)
if isinstance(judged, Failure):
say(f"could not judge whether the worker is stuck: {judged.reason}", effects)
return
line = f"stuck check: {'; '.join(signs)}; a headless claude judged the worker {judged['verdict']}, held by process {judged['process']}: {judged['why']}"
say(line, effects, stdout=True)
record = self.archive / RECORD
try:
record.parent.mkdir(parents=True, exist_ok=True)
with record.open("a") as handle:
handle.write(f"- {utc(now)} {line}\n")
except OSError as failure:
say(f"could not record the stuck check in {record}: {failure.strerror}", effects)
def sign_of(shell: Shell, cpu_before: float | None, now: float) -> str:
"""What says shell may hold its worker stuck, given the CPU seconds it had used at the last check; empty where nothing does."""
if shell.runs_busy_tool:
return ""
idle = cpu_before == shell.cpu and now - shell.written > QUIET
if not (idle or now - shell.started > OLD):
return ""
return f"shell {shell.pid} has run {int(now - shell.started)} s, written nothing for {int(now - shell.written)} s{f' and used no CPU for {CHECK_EVERY} s' if idle else ''}: {shell.command}"
def investigated(shells: list[Shell], rung: Rung, root: str, effects: Effects) -> dict[str, typing.Any] | Failure:
"""A headless claude's verdict on the worker holding shells, as SCHEMA has it, or why there is none. It runs without tools, so it judges only the evidence it is handed."""
evidence = "\n\n".join(f"Shell {shell.pid}: {shell.command}\nIts processes, as pid, state, CPU and command line:\n{chr(10).join(shell.processes) or 'none'}\nThe end of its output:\n{shell.output or 'none'}" for shell in shells)
reply = claude_reply(effects.claude, ["--json-schema", json.dumps(SCHEMA), *rung.flags(), "--tools", ""], root, PROMPT + "\n" + evidence, "the stuck check")
if isinstance(reply, Limited):
return Failure(f"claude hit a limit: {reply.said}")
if isinstance(reply, Failure):
return reply
output = structured_output(reply)
if not (isinstance(output, dict) and output.get("verdict") in VERDICTS and isinstance(output.get("process"), int) and isinstance(output.get("why"), str)):
return Failure(f"answered outside its schema: {output!r}")
return output
+89
View File
@@ -0,0 +1,89 @@
import contextlib
import dataclasses
import io
import json
import pathlib
import tempfile
import unittest
from agent_cycle import stuck_workers, worker
from loop_claude.test_loop_claude import FakeEffects, NOW, Streamed, ran
from loop_effects.child_shells import Shell
from model_routing.ladder import Rung
from text_files.utc_stamp import utc
RUNG = Rung("claude-opus-5-5", "medium")
ASSISTANT = {"type": "assistant", "message": {"content": []}}
def verdict(said="stuck", process=8, why="pytest waits on a shell that ignores SIGINT"):
return ran(json.dumps({"type": "result", "structured_output": {"verdict": said, "process": process, "why": why}}))
def shell(cpu=2.0, started=NOW - 1000, written=NOW - 1000, runs_busy_tool=False):
return Shell(pid=7, started=started, command="bin/run-tests", written=written, runs_busy_tool=runs_busy_tool, cpu=cpu, processes=("8 S 2.0 s python3 -m pytest",), output="collected 40 items")
class StuckWorkers(unittest.TestCase):
def worker_with(self, *events, held=(), replies=()):
"""Runs a worker whose claude prints events and holds the shells held, while each investigation replies in turn; returns the claude, the fake, what was said on stdout and stderr and the record's text."""
clock = [NOW]
streamed = Streamed(0, *events, clock=clock, held=held)
fake = FakeEffects(streams=[streamed], claude=replies)
effects = dataclasses.replace(fake.effects(), now=lambda: clock[0])
with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stdout(io.StringIO()) as said, contextlib.redirect_stderr(io.StringIO()) as failed:
archive = pathlib.Path(folder, "transcripts", "project")
worker.run_worker("/r", [], {}, archive, RUNG, effects)
record = archive / stuck_workers.RECORD
return streamed, fake, said.getvalue(), failed.getvalue(), record.read_text() if record.exists() else ""
def test_a_silent_worker_whose_shell_used_no_cpu_since_the_last_check_is_investigated_and_the_verdict_said_and_recorded_without_a_kill(self):
streamed, fake, said, _, record = self.worker_with(ASSISTANT, None, None, held=[shell()], replies=[verdict()])
[(args, prompt)] = fake.made("claude")
self.assertEqual(args[args.index("--model") + 1 :][:3], ["claude-opus-5-5", "--effort", "medium"])
self.assertEqual(args[args.index("--tools") + 1], "")
for evidence in ("bin/run-tests", "8 S 2.0 s python3 -m pytest", "collected 40 items", "working", "waiting on a person", "stuck"):
self.assertIn(evidence, prompt)
line = "stuck check: shell 7 has run 1600 s, written nothing for 1600 s and used no CPU for 300 s: bin/run-tests; a headless claude judged the worker stuck, held by process 8: pytest waits on a shell that ignores SIGINT"
self.assertEqual(said, f"<{NOW + 600}> {line}\n")
self.assertEqual(record, f"- {utc(NOW + 600)} {line}\n")
self.assertEqual(streamed.stopped, [])
def test_a_shell_older_than_a_chunk_usually_runs_is_investigated_at_the_first_check(self):
_, fake, said, _, _ = self.worker_with(ASSISTANT, None, held=[shell(started=NOW - stuck_workers.OLD, written=NOW + 290)], replies=[verdict("working", 7, "the tests still print")])
self.assertEqual(len(fake.made("claude")), 1)
self.assertIn(f"shell 7 has run {stuck_workers.OLD + 300} s, written nothing for 10 s: bin/run-tests; a headless claude judged the worker working, held by process 7: the tests still print", said)
def test_a_worker_whose_shells_show_no_sign_is_not_investigated(self):
for events, held in (
((ASSISTANT, None, None), [shell(runs_busy_tool=True)]),
((ASSISTANT, None, None), [shell(written=NOW + 600 - 179)]),
((ASSISTANT, None), [shell()]),
((ASSISTANT, None, None), []),
(({"type": "result"}, None, None), [shell()]),
((ASSISTANT, None), [shell(started=NOW + 300 - stuck_workers.OLD)]),
):
with self.subTest(events=events, held=held):
_, fake, said, _, record = self.worker_with(*events, held=held)
self.assertEqual((fake.made("claude"), record), ([], ""))
def test_a_shell_that_used_cpu_since_the_last_check_is_not_investigated(self):
clock = [NOW]
used = [shell(cpu=2.0), shell(cpu=2.5)]
streamed = Streamed(0, ASSISTANT, None, None, clock=clock)
streamed.shells = lambda: [used.pop(0)]
fake = FakeEffects(streams=[streamed])
with contextlib.redirect_stdout(io.StringIO()):
worker.run_worker("/r", [], {}, pathlib.Path("/archive"), RUNG, dataclasses.replace(fake.effects(), now=lambda: clock[0]))
self.assertEqual(fake.made("claude"), [])
def test_an_investigation_that_fails_or_answers_outside_the_schema_is_said_on_stderr(self):
for reply, reason in ((ran(code=1, stderr="no model"), "no model"), (verdict("hung"), "answered outside its schema")):
with self.subTest(reason=reason):
_, _, said, failed, record = self.worker_with(ASSISTANT, None, None, held=[shell()], replies=[reply])
self.assertEqual((said, record), ("", ""))
self.assertIn(f"could not judge whether the worker is stuck: {reason}", failed)
if __name__ == "__main__":
unittest.main()
+10 -6
View File
@@ -9,6 +9,7 @@ from claude_code.transcript import part_line
from machine_load.memory import ROOM_SHARE
from model_routing.ladder import Rung
from claude_code.session import Session
from agent_cycle.stuck_workers import Watch
PRINTED_TOOL_INPUT = 160
# Seconds between reads of the machine's memory while too little of it is available to start a worker.
@@ -18,13 +19,14 @@ AUTO_COMPACT_WINDOW = "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
COMPACT_WINDOW = 200_000
def run_worker(root: str, args: list[str], env: dict[str, str], project_archive: pathlib.Path, effects: Effects) -> Failure | Limited | None:
def run_worker(root: str, args: list[str], env: dict[str, str], project_archive: pathlib.Path, investigator: Rung, effects: Effects) -> Failure | Limited | None:
"""Runs the worker's claude once the machine has room for it, as run_claude does with a Watch whose stuck checks run on investigator, the project's rung."""
wait_for_memory(effects)
return run_claude(root, args, env, effects, project_archive / RECORD)
return run_claude(root, args, env, effects, Watch(investigator, project_archive))
def run_claude(root: str, args: list[str], env: dict[str, str], effects: Effects, record: pathlib.Path | None = None) -> Failure | Limited | None:
"""Runs a headless claude at once, printing what it says, and returns how it failed, or None. Where record is given, a claude that lingers after its final result loses its quiet shells, as `lingering_workers.stopped_shells` says, and each stop is appended to record."""
def run_claude(root: str, args: list[str], env: dict[str, str], effects: Effects, watch: Watch | None = None) -> Failure | Limited | None:
"""Runs a headless claude at once, printing what it says, and returns how it failed, or None. Where watch is given, a claude that lingers after its final result loses its quiet shells, as `lingering_workers.stopped_shells` says, each stop appended to RECORD in watch's archive; and a silent claude that has printed no result is checked for stuck shells, as `stuck_workers` says."""
try:
proc = effects.stream_claude(args, root, env)
except OSError as failure:
@@ -35,8 +37,10 @@ def run_claude(root: str, args: list[str], env: dict[str, str], effects: Effects
resets: list[int] = []
for raw in proc.lines(CHECK_EVERY):
if raw is None:
if record is not None:
stopped_shells(proc, printed_result, record, effects)
if watch is not None:
stopped_shells(proc, printed_result, watch.archive / RECORD, effects)
if not printed_result:
watch.check(proc, root, effects)
continue
event = json_object(raw) or {}
printed_result = ends_stream(event)