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
+52 -6
View File
@@ -13,6 +13,7 @@ from machine_load.slots import slot_folder
# The command names of a shell claude starts for a Bash call.
SHELL_NAMES = frozenset({"bash", "dash", "sh", "zsh"})
COMMAND_CHARS = 300
OUTPUT_BYTES = 2000
# Scripts whose process below a shell shows work that may go quiet for long: run-heavy while it waits for a slot, and chunk-pr, which waits for a merge's approval and checks.
BUSY_TOOLS = frozenset({"chunk-pr", "run-heavy"})
@@ -28,19 +29,38 @@ class Shell:
written: float
# Whether a process below the shell runs one of BUSY_TOOLS or holds a heavy slot, a file of slot_folder that run-heavy leaves open in the command it runs.
runs_busy_tool: bool
# CPU seconds the shell and every process below it have used.
cpu: float = 0.0
# Each process below the shell, as `<pid> <state> <CPU seconds> s <command line>`, with the state letter /proc gives, such as S for sleeping.
processes: tuple[str, ...] = ()
# The last OUTPUT_BYTES of the file the shell's output goes to; empty where it goes to no file.
output: str = ""
def parent_and_start(pid: int) -> tuple[int, int, str] | None:
"""The parent pid, the start time in clock ticks since boot and the command name of a process; None where it is gone."""
def stat_of(pid: int) -> tuple[str, list[str]] | None:
"""A process's command name and the fields of /proc/<pid>/stat after it, from the state on; None where it is gone."""
try:
with open(f"/proc/{pid}/stat") as handle:
text = handle.read()
except OSError:
return None
# The name sits in parentheses and may hold spaces or parentheses itself, so split at the last one.
name = text[text.index("(") + 1 : text.rindex(")")]
fields = text[text.rindex(")") + 2 :].split()
return int(fields[1]), int(fields[19]), name
return text[text.index("(") + 1 : text.rindex(")")], text[text.rindex(")") + 2 :].split()
def parent_and_start(pid: int) -> tuple[int, int, str] | None:
"""The parent pid, the start time in clock ticks since boot and the command name of a process; None where it is gone."""
found = stat_of(pid)
return None if found is None else (int(found[1][1]), int(found[1][19]), found[0])
def cpu_and_state(pid: int) -> tuple[float, str]:
"""The CPU seconds a process has used, in user and kernel mode, and its state letter; none and `gone` where it is gone."""
found = stat_of(pid)
if found is None:
return 0.0, "gone"
fields = found[1]
return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK"), fields[0]
def children_of(pid: int) -> list[int]:
@@ -77,6 +97,31 @@ def output_written(pid: int, started: float) -> float:
return info.st_mtime if stat.S_ISREG(info.st_mode) else started
def output_tail(pid: int) -> str:
"""The last OUTPUT_BYTES of the file that pid's standard output goes to; empty where it goes to a pipe or a terminal."""
path = f"/proc/{pid}/fd/1"
try:
# Before the open, which can block on a pipe.
if not stat.S_ISREG(os.stat(path).st_mode):
return ""
with open(path, "rb") as handle:
handle.seek(max(0, os.fstat(handle.fileno()).st_size - OUTPUT_BYTES))
return handle.read().decode(errors="replace")
except OSError:
return ""
def tree_of(pid: int) -> tuple[float, tuple[str, ...]]:
"""The CPU seconds pid and every process below it have used, and each process below it as `Shell.processes` shows one."""
total = cpu_and_state(pid)[0]
shown = []
for each in descendants(pid):
cpu, state = cpu_and_state(each)
total += cpu
shown.append(f"{each} {state} {cpu:.1f} s {' '.join(argv_of(each))[:COMMAND_CHARS]}")
return total, tuple(shown)
def command_of(shell_argv: list[str]) -> str:
"""What a shell runs: the text of its command line after Claude Code's `eval '`, up to the last ` < /dev/null`, which a call that began in the foreground lacks; the whole line where it holds no `eval`."""
line = " ".join(shell_argv)
@@ -110,7 +155,8 @@ def shells_of(claude_pid: int) -> list[Shell]:
if found is None or found[2] not in SHELL_NAMES:
continue
started = booted + found[1] / ticks
shells.append(Shell(pid, started, command_of(argv_of(pid)), output_written(pid, started), runs_busy_tool(pid, slots)))
cpu, processes = tree_of(pid)
shells.append(Shell(pid, started, command_of(argv_of(pid)), output_written(pid, started), runs_busy_tool(pid, slots), cpu, processes, output_tail(pid)))
return shells
+16
View File
@@ -189,6 +189,22 @@ class ChildShells(unittest.TestCase):
self.assertEqual(self.shell_of(to_file).written, 1000)
self.assertEqual(self.shell_of(to_pipe).written, self.shell_of(to_pipe).started)
def test_reads_the_end_of_a_shells_output_file_and_nothing_from_a_pipe(self):
with tempfile.NamedTemporaryFile() as output:
output.write(b"x" * child_shells.OUTPUT_BYTES + b"last line\n")
output.flush()
to_file = self.started("sleep 60; true", stdout=output)
to_pipe = self.started("sleep 60; true", stdout=subprocess.PIPE)
self.assertEqual(self.shell_of(to_file).output, "x" * (child_shells.OUTPUT_BYTES - 10) + "last line\n")
self.assertEqual(self.shell_of(to_pipe).output, "")
def test_reads_each_process_below_a_shell_and_the_cpu_the_whole_tree_used(self):
busy = self.started("timeout 5 sh -c 'while :; do :; done'; true")
wait_until(lambda: self.shell_of(busy).cpu > 0.1)
processes = self.shell_of(busy).processes
self.assertEqual([line.split(" ", 4)[4] for line in processes], ["timeout 5 sh -c while :; do :; done", "sh -c while :; do :; done"])
self.assertEqual(processes[1].split(" ")[1], "R")
def test_stops_a_shell_and_the_process_it_started_and_no_other(self):
shell = self.started("sleep 60; true")
other = subprocess.Popen(["sleep", "60"])