The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(process): give worker-spawned background processes a log, not a pipe
Teknium5a1916cc5cba
diff --git a/tests/gateway/test_managed_worker_background_output.py b/tests/gateway/test_managed_worker_background_output.pynew file mode 100644index 00000000000..6df29abbb87--- /dev/null+++ b/tests/gateway/test_managed_worker_background_output.py@@ -0,0 +1,134 @@+"""A background process a managed worker starts keeps its output past the worker's exit.++The worker is a per-turn interpreter. With a stdout pipe owned by its reader thread, the+child's first write after the worker exits raised SIGPIPE (``broken_pipe``) and its output+was gone; the next worker adopted only a PID. Under a worker the child writes to a+profile-scoped log and records its exit, so whoever adopts the checkpoint reads both.+"""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import re+import sqlite3+import subprocess+import sys+import textwrap+import threading++import pytest++ROOT = Path(__file__).resolve().parents[2]+COMMAND = 'sleep 2; echo FIRST_$((40+2)); sleep 1; echo SECOND_$((6*7)); (exit 7)'++[email protected]("posix")+def test_worker_spawned_process_output_and_exit_survive_the_spawner(tmp_path):+ home = tmp_path / 'home'+ home.mkdir()+ env = {k: v for k, v in os.environ.items() if k not in ('HERMES_HOME', 'PYTHONPATH')}+ env.update(HERMES_HOME=str(home), PYTHONPATH=str(ROOT))+ # The spawner marks itself a registered worker, starts the process and dies at once.+ spawner = textwrap.dedent(f'''+ import json, os+ from agent import runtime_session_store+ runtime_session_store._worker_process = True+ from tools.process_registry import process_registry+ session = process_registry.spawn_local({COMMAND!r}, cwd={str(tmp_path)!r})+ print(json.dumps(session.id), flush=True)+ os._exit(0)+ ''')+ out = subprocess.run([sys.executable, '-c', spawner], env=env, cwd=ROOT, capture_output=True, text=True, encoding='utf-8', timeout=60)+ session_id = json.loads(out.stdout.strip().splitlines()[-1])+ adopter = textwrap.dedent(f'''+ import json+ from tools.process_registry import ProcessRegistry+ registry = ProcessRegistry()+ registry.recover_from_checkpoint()+ print(json.dumps(registry.wait({session_id!r}, timeout=30)))+ ''')+ out = subprocess.run([sys.executable, '-c', adopter], env=env, cwd=ROOT, capture_output=True, text=True, encoding='utf-8', timeout=60)+ result = json.loads(out.stdout.strip().splitlines()[-1])+ assert result['status'] == 'exited', (result, out.stderr[-2000:])+ assert result['exit_code'] == 7 and result['output'] == 'FIRST_42\nSECOND_42\n', result+++class Model(BaseHTTPRequestHandler):+ """Turn one starts the background command; turn two waits on it by id."""+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages') or [{'role': 'system'}]+ last = messages[-1]+ if last['role'] == 'user' and last.get('content') == 'START':+ name, args = 'terminal', {'command': COMMAND, 'background': True}+ elif last['role'] == 'user' and last.get('content') == 'WAIT':+ proc = re.findall(r'proc_[0-9a-f]{12}', json.dumps(messages))[0]+ name, args = 'tool_call', {'calls': [{'name': 'process_manage',+ 'arguments': {'action': 'wait', 'session_id': proc, 'timeout': 30}}]}+ else:+ name, args = None, {}+ message = ({'role': 'assistant', 'content': None, 'tool_calls': [{'id': 'c%d' % len(messages), 'index': 0,+ 'type': 'function', 'function': {'name': name, 'arguments': json.dumps(args)}}]}+ if name else {'role': 'assistant', 'content': 'OK'})+ choice = {'index': 0, 'delta': message, 'finish_reason': 'tool_calls' if name else 'stop'}+ frame = {'id': 'bg', 'model': 'm', 'choices': [choice], 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}}+ if body.get('stream'):+ payload, kind = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode(), 'text/event-stream'+ else:+ choice['message'] = choice.pop('delta')+ payload, kind = json.dumps(frame).encode(), 'application/json'+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++[email protected]("linux")+def test_next_managed_turn_reads_the_previous_workers_background_output(tmp_path):+ from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False, 'managed_workers': True},+ 'model': {'provider': 'custom', 'default': 'm', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'approvals': {'mode': 'off'},+ 'platform_toolsets': {'cli': ['terminal']}}))+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(ROOT),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)++ def settled(request_id):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ return db.execute('SELECT status FROM session_admissions WHERE request_id=?', (request_id,)).fetchall() == [('terminal',)]++ async def exercise(desc):+ async with websocket(home, desc) as ws:+ created = await rpc(ws, 'session.create', request_id='bg', source='cli', cwd=str(home), model='m',+ provider='custom', base_url=url, api_key='loopback-only', toolsets=['terminal'],+ ignore_rules=True)+ sid = created['result']['session_id']+ for request_id, text in (('start', 'START'), ('wait', 'WAIT')):+ assert 'result' in await rpc(ws, 'prompt.submit', session_id=sid, input_id=request_id, text=text)+ async with asyncio.timeout(90):+ while not settled(request_id):+ await asyncio.sleep(.1)+ return (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']+ try:+ with daemon(ROOT, home, env, barrier=False) as (_owner, desc):+ messages = asyncio.run(exercise(desc))+ finally:+ peer.shutdown()+ peer.server_close()+ waited = json.loads([m['content'] for m in messages if m['role'] == 'tool'][-1])+ assert waited['status'] == 'exited' and waited['exit_code'] == 7, waited+ assert waited['output'] == 'FIRST_42\nSECOND_42\n', waiteddiff --git a/tools/process_registry.py b/tools/process_registry.pyindex 31ea2ca63e0..4e8af888773 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -34,6 +34,7 @@ from hermes_cli.config import get_hermes_homefrom tools.process_registry_notifications import format_process_notificationfrom tools.process_registry_checkpoint import ProcessCheckpointMixin+from tools.process_registry_output_log import ProcessOutputLogMixin, open_output_log, record_exit_command, worker_output_logfrom tools.process_registry_termination import ProcessTerminationMixinfrom tools.process_registry_results import load_completed_results, save_completed_resultfrom tools.process_registry_env_log import log_delta_command@@ -566,9 +567,8 @@ class ProcessSession:handoff_note: str = "" # why a subagent handed this process to its parent (rides the notice)persist_on_release: bool = False # opt out of agent-lifecycle cleanup (release()/turn-abandon kill# sweeps), per terminal(background=true, persist_on_release=true) (#41225)+ output_log: str = "" # file the process writes to (worker spawns; no pipe to lose)# Watcher/notification routing (persisted for crash recovery)- # systemd_unit: str = "" # transient scope unit name when spawned under systemd-run- # (#70716)watcher_platform: str = ""watcher_chat_id: str = ""watcher_user_id: str = ""@@ -654,7 +654,7 @@ _CHECKPOINT_FIELDS = ("started_at", "task_id", "owner_task_id", "session_key",*(f"watcher_{k}" for k in _WATCHER_ROUTE_KEYS), "watcher_interval","parent_session_id", "notify_on_complete", "completion_output_chars", "watch_patterns",- "heartbeat_seconds", "persist_on_release")+ "heartbeat_seconds", "persist_on_release", "output_log")_CHECKPOINT_DEFAULTS = {f.name: ([] if f.name == "watch_patterns" else f.default)for f in ProcessSession.__dataclass_fields__.values()@@ -669,7 +669,7 @@ _WSL_CHAIN_NOTE = ()-class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):+class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOutputLogMixin):"""In-memory registry of running and finished background processes.Thread-safe: accessed from executor threads (terminal_tool, process handlers),the gateway asyncio loop (watchers, reset checks) and the cleanup thread."""@@ -1002,8 +1002,8 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):A completion is not queued here: recovery has no waitable handle, so itnever collected an exit status."""- if session is None or session.exited or not session.detached or session.pid_scope != "host":- return session+ if session is None or session.exited or not session.detached or session.pid_scope != "host" or session.output_log:+ return session # a log-backed adoption's reader collects the recorded exit itselffate = self._detached_host_fate(session.pid, session.host_start_time)if fate == "running":return session@@ -1189,7 +1189,9 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):session = self._new_session(command, task_id, owner_task_id, session_key, _resolve_safe_cwd(cwd or os.getcwd()),persist_on_release=persist_on_release)pty_scope_attempted = False- if use_pty:+ # A worker's pipe or PTY dies with the worker (the child's next write is SIGPIPE): write to a log.+ log = worker_output_log(session.id)+ if use_pty and log is None:try:return self._spawn_local_pty(session, safe_command, env_vars)except ImportError:@@ -1207,7 +1209,8 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):# Pipe path (non-PTY or PTY fallback)._popen_kwargs = {"creationflags": windows_hide_flags()} if _IS_WINDOWS else {}unit_suffix = f"{session.id}-pipe-fallback" if pty_scope_attempted else session.id- spawn_argv = self._scope_argv(session, safe_command, unit_suffix, "Local")+ spawn_argv = self._scope_argv(session, record_exit_command(log, safe_command) if log else safe_command,+ unit_suffix, "Local")spawn_env = self._spawn_env(env_vars)if session.systemd_unit:spawn_env = systemd_user_bus_env(spawn_env)@@ -1216,15 +1219,20 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):# share the foreground process group and background spawns would stop the whole# session (observed as dead TUIs in state T). Cgroup isolation is unaffected —# the scope attaches to the invoked process, not the spawning session.- proc = subprocess.Popen(- spawn_argv, text=True, cwd=session.cwd, env=spawn_env, encoding="utf-8",- errors="replace", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,- start_new_session=True, **_popen_kwargs)- session.process = proc+ output = open_output_log(log) if log else subprocess.PIPE+ try:+ proc = subprocess.Popen(+ spawn_argv, text=True, cwd=session.cwd, env=spawn_env, encoding="utf-8",+ errors="replace", stdout=output, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,+ start_new_session=True, **_popen_kwargs)+ finally:+ if log:+ os.close(output)+ session.process, session.output_log = proc, str(log or "")session.pid = proc.pidsession.host_start_time = self._safe_host_start_time(session.pid)try:- self._track_started(session, self._reader_loop, f"proc-reader-{session.id}")+ self._track_started(session, self._log_reader_loop if log else self._reader_loop, f"proc-reader-{session.id}")except Exception:self._reap_untracked(session, proc)raise@@ -1312,10 +1320,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):end so EOF never arrives while it lives, which would park this thread and neverfire ``notify_on_complete``; on POSIX we ``select()`` and stop draining shortlyafter the direct child exits (mirrors ``environments/base.py::_wait_for_process``).- Windows pipes lack select(), so the lazy ``_reconcile_local_exit`` is the net.-- Windows pipes don't support select(); the blocking path is kept there and the lazy reconcile in- poll()/wait() remains the safety net. See #68915, #8340.+ Windows pipes lack select(), so the lazy ``_reconcile_local_exit`` is the net (#68915, #8340)."""# ``bash -lic`` without a tty writes its startup warnings one write() per line, so the# reader can wake between them; strip leading noise from every chunk until the@@ -1323,13 +1328,8 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):head_noise = True# A split multibyte UTF-8 char would become U+FFFD with stateless decoding; the# incremental decoder holds the partial sequence until the rest arrives.- decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")+ decoder = codecs.getincrementaldecoder("utf-8")(errors="replace") # (openclaw/openclaw#112325)- # Incremental decoder: raw pipe reads can split a multibyte UTF-8 character across two read1()- # chunks. A stateless per-chunk ``bytes.decode(errors="replace")`` turns both halves into U+FFFD- # mojibake. The incremental decoder holds the partial sequence until the continuation bytes arrive —- # same treatment the foreground path already has in- # ``tools/environments/base.py::_wait_for_process``. (Ported from openclaw/openclaw#112325.)def _append_chunk(chunk: str):nonlocal head_noiseif head_noise:@@ -2021,7 +2021,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin):# final drain is partial and must not suppress the full completion.if not finalizing:self._poll_observed.add(session_id)- if session.detached:+ if session.detached and not session.output_log:result.update(detached=True, note="Process recovered after restart -- output history unavailable")return resultdiff --git a/tools/process_registry_checkpoint.py b/tools/process_registry_checkpoint.pyindex d9e685293ef..700aab028f7 100644--- a/tools/process_registry_checkpoint.py+++ b/tools/process_registry_checkpoint.py@@ -54,6 +54,7 @@ class ProcessCheckpointMixin:ProcessSession, _CHECKPOINT_FIELDS, _checkpoint_path,_CHECKPOINT_DEFAULTS, _WATCHER_ROUTE_KEYS, _stop_systemd_unit,)+ from tools.process_registry_output_log import adoptable_logcheckpoint_path = _checkpoint_path()if not checkpoint_path.exists():@@ -85,6 +86,11 @@ class ProcessCheckpointMixin:# completion. A positive mismatch means the number was recycled:# do not adopt it and do not signal it.fate = self._detached_host_fate(pid, entry.get("host_start_time"))+ # A worker spawn's output log and recorded exit outlive both the spawner and the PID,+ # so its reader decides the outcome (a recycled PID is never signalled: fate != running).+ log = adoptable_log(entry.get("output_log"))+ if log:+ fate = "running"if fate == "reused":logger.info("Not recovering session %s: pid %d is alive but its "@@ -106,10 +112,15 @@ class ProcessCheckpointMixin:command=entry.get("command", "unknown"),owner_task_id=entry.get("owner_task_id", "") or entry.get("task_id", ""),started_at=entry.get("started_at", time.time()))- # detached: can't read output, but can report status + kill+ # detached: no Popen handle, but can report status + kill; a worker spawn's output log+ # (and recorded exit) outlives its spawner, so tail it from the start.+ fields["output_log"] = logsession = ProcessSession(id=entry["session_id"], detached=True, **fields)- with self._lock:- self._running[session.id] = session+ if session.output_log:+ self._track_started(session, self._log_reader_loop, f"proc-log-reader-{session.id}")+ else:+ with self._lock:+ self._running[session.id] = sessionrecovered += 1logger.info("Recovered detached process: %s (pid=%d)", session.command[:60], pid)# Re-enqueue watcher so gateway can resume notificationsdiff --git a/tools/process_registry_output_log.py b/tools/process_registry_output_log.pynew file mode 100644index 00000000000..193ffc8604c--- /dev/null+++ b/tools/process_registry_output_log.py@@ -0,0 +1,134 @@+"""File-backed output for background processes a registered worker starts.++A managed worker is a per-turn interpreter. A stdout pipe whose read end that worker's reader+thread owns closes when the worker exits, so the child's next write raises SIGPIPE+(``broken_pipe``) and everything it printed is gone. Under a worker the child writes to a+profile-scoped log instead and its shell records the exit status beside it (the contract the+env-backend wrapper already uses), so whichever interpreter adopts the checkpoint entry next+(the session's next worker, the owner at startup) tails the same file and collects the exit.+"""+import codecs+from contextlib import suppress+import logging+import os+from pathlib import Path+import time+from typing import Optional++from hermes_constants import get_hermes_home++logger = logging.getLogger("tools.process_registry")++_TAIL_SECONDS = 0.2+# After the process ended: an orphaned grandchild may keep appending; stop draining after this.+_FINAL_DRAIN_MAX_BYTES = 1 << 20+++def output_dir() -> Path:+ return get_hermes_home() / "logs" / "process-output"+++def worker_output_log(session_id: str) -> Optional[Path]:+ """The log a worker-spawned process writes to; None outside a registered worker."""+ from agent.runtime_session_store import is_worker_process+ if not is_worker_process():+ return None+ directory = output_dir()+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)+ from tools.process_registry_results import RESULT_RETENTION_SECONDS+ # Only a recorded exit retires a log: a quiet process can run longer than the retention.+ cutoff = time.time() - RESULT_RETENTION_SECONDS+ for exited in directory.glob("proc_*.exit"):+ with suppress(FileNotFoundError):+ if exited.stat().st_mtime < cutoff:+ exited.with_suffix(".log").unlink(missing_ok=True)+ exited.unlink()+ return directory / f"{session_id}.log"+++def adoptable_log(path) -> str:+ """A checkpointed log path, only when it names this profile's output directory."""+ log = Path(str(path or ""))+ return str(log) if path and log.parent == output_dir() and log.suffix == ".log" else ""+++def open_output_log(log: Path) -> int:+ """Owner-only append descriptor for the child's stdout+stderr (the parent closes its copy)."""+ return os.open(log, os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, "O_BINARY", 0), 0o600)+++def _exit_path(log) -> Path:+ return Path(log).with_suffix(".exit")+++def record_exit_command(log: Path, command: str) -> str:+ """Prefix ``command`` so the shell writes its exit status beside the log: an interpreter+ that adopts the process after the spawner exited has no Popen to wait on."""+ import shlex+ target = shlex.quote(_exit_path(log).as_posix())+ return f"__hermes_exit_file={target}; trap 'printf \"%s\\n\" \"$?\" > \"$__hermes_exit_file\"' EXIT\n{command}"+++def recorded_exit_code(log) -> Optional[int]:+ try:+ return int(_exit_path(log).read_text(encoding="utf-8-sig").strip())+ except (OSError, ValueError):+ return None+++class ProcessOutputLogMixin:+ """The subclass supplies ``_ingest_output``, ``_clean_shell_noise``, ``_finish_reader``,+ ``_finish_exited`` and ``_detached_host_fate``. See ProcessRegistry."""++ def _log_reader_loop(self, session) -> None:+ """Tail ``session.output_log`` until its process ends. The spawner decides the exit from+ its Popen; an adopter (no Popen) from the recorded status, else ``lost`` (-1)."""+ decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")+ proc = session.process+ # poll()/wait() reconcile asks this reader to finish instead of reading a pipe itself.+ session._reader_selectable = True++ head_noise = True++ def ingest(text: str) -> None:+ nonlocal head_noise+ if head_noise: # ``bash -lic`` startup warnings, as the pipe reader strips them+ text = self._clean_shell_noise(text)+ head_noise = not text.strip()+ self._ingest_output(session, text)++ def running() -> bool:+ if session._reader_finish_requested.is_set():+ return False+ if proc is not None:+ return proc.poll() is None+ return self._detached_host_fate(session.pid, session.host_start_time) == "running"+ try:+ with open(session.output_log, "rb") as stream:+ drained = 0+ while True:+ # Decided BEFORE the read: once the process is gone every byte it wrote is readable.+ alive = running()+ chunk = stream.read(65536)+ if chunk:+ if text := decoder.decode(chunk):+ ingest(text)+ drained += 0 if alive else len(chunk)+ if drained < _FINAL_DRAIN_MAX_BYTES:+ continue+ if not alive:+ break+ time.sleep(_TAIL_SECONDS)+ except OSError as exc:+ logger.warning("Process output log %s unreadable: %s", session.output_log, exc)+ if proc is not None:+ self._finish_reader(session, decoder, ingest, "Log", proc.wait, lambda: proc.returncode)+ return+ if tail := decoder.decode(b"", final=True):+ ingest(tail)+ code = recorded_exit_code(session.output_log)+ if code is None:+ # SIGKILL / exec past the trap: the spawner is gone and no status was recorded.+ self._finish_exited(session, -1, reason="lost", source="backend_lost")+ else:+ self._finish_exited(session, code)