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
CI / tests (pull_request) Failing after 4m3s
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user