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
+93
View File
@@ -0,0 +1,93 @@
"""The shells a running claude has started, read from /proc (Linux), and how to stop one."""
import dataclasses
import os
import signal
import stat
# The command names of a shell claude starts for a Bash call.
SHELL_NAMES = frozenset({"bash", "dash", "sh", "zsh"})
# How much of a shell's command line a Shell keeps.
COMMAND_CHARS = 200
@dataclasses.dataclass(frozen=True)
class Shell:
pid: int
# Epoch seconds at which the shell started.
started: float
command: str
# Epoch seconds of the last write to the file the shell's output goes to; its start where the output goes to no file.
written: float
# Whether the shell or one of its descendants is run-heavy, which holds a slot of the machine's heavy work or waits for one.
holds_slot: bool
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."""
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
def children_of(pid: int) -> list[int]:
return [int(entry) for entry in os.listdir("/proc") if entry.isdigit() and (found := parent_and_start(int(entry))) and found[0] == pid]
def command_of(pid: int) -> str:
try:
with open(f"/proc/{pid}/cmdline", "rb") as handle:
return handle.read().replace(b"\0", b" ").decode(errors="replace").strip()
except OSError:
return ""
def descendants(pid: int) -> list[int]:
"""Every process below pid, nearest first."""
found = children_of(pid)
for child in list(found):
found += descendants(child)
return found
def boot_time() -> float:
with open("/proc/stat") as handle:
return next(float(line.split()[1]) for line in handle if line.startswith("btime"))
def output_written(pid: int, started: float) -> float:
"""When the file that pid's standard output goes to was last written; started where that is a pipe or a terminal, whose writes leave no time."""
try:
info = os.stat(f"/proc/{pid}/fd/1")
except OSError:
return started
return info.st_mtime if stat.S_ISREG(info.st_mode) else started
def shells_of(claude_pid: int) -> list[Shell]:
"""The shells that are children of claude_pid."""
booted = boot_time()
ticks = os.sysconf("SC_CLK_TCK")
shells = []
for pid in children_of(claude_pid):
found = parent_and_start(pid)
if found is None or found[2] not in SHELL_NAMES:
continue
started = booted + found[1] / ticks
below = [pid, *descendants(pid)]
shells.append(Shell(pid, started, command_of(pid)[:COMMAND_CHARS], output_written(pid, started), any("run-heavy" in command_of(each) for each in below)))
return shells
def stop(shell: Shell) -> None:
"""Ends the shell and everything below it, so the loop it ran doesn't outlive it."""
for pid in [*reversed(descendants(shell.pid)), shell.pid]:
try:
os.kill(pid, signal.SIGTERM)
except OSError:
pass
+36 -4
View File
@@ -5,6 +5,7 @@ A change here, such as to how input reads a line, changes every tool that runs o
import dataclasses
import os
import pathlib
import select
import signal
import subprocess
import sys
@@ -13,6 +14,7 @@ import time
import typing
from notifier.notify import Backend, BACKENDS, notify
from loop_effects import child_shells
from failure import Failure
from git_cli import git_repo
from machine_load.memory import Memory, read_memory
@@ -25,7 +27,17 @@ PYTHON_TIMEOUT = 600
class Streaming(typing.Protocol):
"""A started claude whose stream-json lines arrive as it works."""
def lines(self) -> typing.Iterable[str]: ...
def lines(self, idle: float) -> typing.Iterable[str | None]:
"""Each line as it arrives, and None whenever idle seconds pass without one."""
...
def shells(self) -> list[child_shells.Shell]:
"""The shells that are children of the claude."""
...
def stop(self, shell: child_shells.Shell) -> None:
"""Ends the shell and everything below it."""
...
def wait(self) -> int: ...
@@ -59,11 +71,31 @@ class Effects:
class StreamingClaude:
def __init__(self, args: list[str], cwd: str, env: dict[str, str]) -> None:
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, env={**os.environ, **env}, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
self.proc = subprocess.Popen(["claude", *args], cwd=cwd, env={**os.environ, **env}, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, bufsize=0)
def lines(self) -> typing.Iterable[str]:
def lines(self, idle: float) -> typing.Iterable[str | None]:
# Reads the pipe's file descriptor itself, since select cannot see what a buffered reader holds, and a thread blocked in a read keeps the pipe from closing when a Ctrl-C ends the loop.
pending = b""
with self.proc:
yield from self.proc.stdout or ()
fd = self.proc.stdout.fileno() if self.proc.stdout else -1
while True:
if not select.select([fd], [], [], idle)[0]:
yield None
continue
chunk = os.read(fd, 65536)
if not chunk:
break
*complete, pending = (pending + chunk).split(b"\n")
for line in complete:
yield line.decode("utf-8", errors="replace") + "\n"
if pending:
yield pending.decode("utf-8", errors="replace")
def shells(self) -> list[child_shells.Shell]:
return child_shells.shells_of(self.proc.pid)
def stop(self, shell: child_shells.Shell) -> None:
child_shells.stop(shell)
def wait(self) -> int:
return self.proc.wait()
+23
View File
@@ -4,6 +4,7 @@ import io
import os
import pathlib
import signal
import subprocess
import sys
import tempfile
import time
@@ -12,6 +13,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_effects import child_shells
from loop_effects.effects import run_python, say, system_effects
NOW = 1790000000
@@ -134,3 +136,24 @@ class PythonEffect(unittest.TestCase):
done = run_python(["-c", "pass"], gone, 60)
self.assertEqual(done.returncode, 1)
self.assertIn(gone, done.stderr)
class ChildShells(unittest.TestCase):
def test_reads_a_child_shell_with_its_command_and_a_heavy_slot_and_stops_it_with_what_it_started(self):
quiet = subprocess.Popen(["bash", "-c", "sleep 60; true"])
heavy = subprocess.Popen(["bash", "-c", "sleep 60; true # run-heavy"])
other = subprocess.Popen(["sleep", "60"])
try:
time.sleep(0.3)
shells = {shell.pid: shell for shell in child_shells.shells_of(os.getpid())}
self.assertEqual(sorted(shells), sorted([quiet.pid, heavy.pid]))
self.assertEqual(shells[quiet.pid].command, "bash -c sleep 60; true")
self.assertEqual((shells[quiet.pid].holds_slot, shells[heavy.pid].holds_slot), (False, True))
self.assertLess(abs(shells[quiet.pid].started - time.time()), 5)
child_shells.stop(shells[quiet.pid])
self.assertEqual(quiet.wait(timeout=5), -signal.SIGTERM)
self.assertIsNone(other.poll())
finally:
for proc in (quiet, heavy, other):
proc.kill()
proc.wait()