From 2aaadad6562a2df33cfde52857e1683188bac2ab Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Fri, 20 Nov 2026 19:45:34 -0800 Subject: [PATCH] [FD-5916] fix(agents): a clocked agent's container exits when its server dies Before the clock work the A2A server was the agent container's main process, so when it died the container exited and the run failed fast. The clocked claude-code and opencode images run root's supervisord as PID 1 with [program:agent] autorestart=true, so a crashed server was restarted in place: the dead server's CLI kept writing, and the new server had lost its env MCP servers, config, peers and running tasks, so prompt_agent polled "Task not found" until its timeout. Each image's root.conf now never restarts the server (autorestart=false, startretries=0) and adds [eventlistener:agent-exit], a POSIX sh listener on PROCESS_STATE_EXITED and PROCESS_STATE_FATAL that sends SIGTERM to supervisord when the program is "agent". supervisord then stops the follower and the egress proxy and exits, and the container with it. The follower and the proxy keep their own restart policy. supervisord exits 0 however it stops. The unit test pins it per clocked image: the server's autorestart and startretries, the follower's and the proxy's restart, and the listener run as supervisord runs it under a stand-in parent that counts the SIGTERMs it gets. Co-Authored-By: Claude Opus 5.5 --- .../agents/agents/claude-code/root.conf | 15 +++- .../agents/agents/opencode/root.conf | 15 +++- tst/unit/agents/test_agent_clock_images.py | 70 +++++++++++++++++-- 3 files changed, 91 insertions(+), 9 deletions(-) diff --git a/src/agent_env/agents/agents/claude-code/root.conf b/src/agent_env/agents/agents/claude-code/root.conf index af730a2d9..48289cf84 100644 --- a/src/agent_env/agents/agents/claude-code/root.conf +++ b/src/agent_env/agents/agents/claude-code/root.conf @@ -46,13 +46,14 @@ stdout_logfile=/var/log/agentenv-root/egress.log environment=HOME="/nonexistent",USER="agentenv-egress",LOGNAME="agentenv-egress",AGENTENV_EGRESS_PRIVATE="allow" ; uvicorn itself, not entrypoint.sh: the marker holds for the process it's given to alone, and a shell that execs -; uvicorn would hand uvicorn an environment without it. +; uvicorn would hand uvicorn an environment without it. Never restarted: see [eventlistener:agent-exit]. [program:agent] command=/usr/local/bin/python3 -m uvicorn a2a_server:app --host 0.0.0.0 --port %(ENV_A2A_PORT)s user=agent directory=/app priority=10 -autorestart=true +autorestart=false +startretries=0 stopasgroup=true killasgroup=true stopwaitsecs=30 @@ -60,3 +61,13 @@ redirect_stderr=true stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 environment=HOME="/home/agent",USER="agent",LOGNAME="agent",AGENTENV_REAL_TIME="1",AGENTENV_EGRESS_PROXY="http://127.0.0.1:3128",NODE_EXTRA_CA_CERTS="/etc/agentenv/ca.pem",SSL_CERT_FILE="/etc/agentenv/ca-bundle.pem",REQUESTS_CA_BUNDLE="/etc/agentenv/ca-bundle.pem" + +; The server's exit, for any reason, stops supervisord and with it the container, as when the server was the +; container's main process: one restarted in place would have lost the env's MCP servers, its config, its peers and its +; running tasks, while the CLI the dead one started went on writing. The follower and the proxy restart in place. +; supervisord exits 0 however it stops, so the container's exit status doesn't tell a crash from a stop; its log does. +[eventlistener:agent-exit] +command=/bin/sh -c 'while echo READY && read -r header; do body=$(head -c "${header##*len:}"); case " $body " in *" processname:agent "*) echo "the A2A server exited ($body): stopping the container" >&2; kill -TERM "$PPID";; esac; printf "RESULT 2\nOK"; done' +events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 diff --git a/src/agent_env/agents/agents/opencode/root.conf b/src/agent_env/agents/agents/opencode/root.conf index a88ad91dd..929d7df74 100644 --- a/src/agent_env/agents/agents/opencode/root.conf +++ b/src/agent_env/agents/agents/opencode/root.conf @@ -46,13 +46,14 @@ stdout_logfile=/var/log/agentenv-root/egress.log environment=HOME="/nonexistent",USER="agentenv-egress",LOGNAME="agentenv-egress",AGENTENV_EGRESS_PRIVATE="allow" ; uvicorn itself, not entrypoint.sh: the marker holds for the process it's given to alone, and a shell that execs -; uvicorn would hand uvicorn an environment without it. +; uvicorn would hand uvicorn an environment without it. Never restarted: see [eventlistener:agent-exit]. [program:agent] command=/usr/local/bin/python3 -m uvicorn a2a_server:app --host 0.0.0.0 --port %(ENV_A2A_PORT)s --timeout-graceful-shutdown 5 user=agent directory=/app priority=10 -autorestart=true +autorestart=false +startretries=0 stopasgroup=true killasgroup=true stopwaitsecs=30 @@ -60,3 +61,13 @@ redirect_stderr=true stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 environment=HOME="/data",USER="agent",LOGNAME="agent",AGENTENV_REAL_TIME="1",AGENTENV_EGRESS_PROXY="http://127.0.0.1:3128",NODE_EXTRA_CA_CERTS="/etc/agentenv/ca.pem",SSL_CERT_FILE="/etc/agentenv/ca-bundle.pem",REQUESTS_CA_BUNDLE="/etc/agentenv/ca-bundle.pem" + +; The server's exit, for any reason, stops supervisord and with it the container, as when the server was the +; container's main process: one restarted in place would have lost the env's MCP servers, its config, its peers and its +; running tasks, while the CLI the dead one started went on writing. The follower and the proxy restart in place. +; supervisord exits 0 however it stops, so the container's exit status doesn't tell a crash from a stop; its log does. +[eventlistener:agent-exit] +command=/bin/sh -c 'while echo READY && read -r header; do body=$(head -c "${header##*len:}"); case " $body " in *" processname:agent "*) echo "the A2A server exited ($body): stopping the container" >&2; kill -TERM "$PPID";; esac; printf "RESULT 2\nOK"; done' +events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL +stderr_logfile=/dev/stderr +stderr_logfile_maxbytes=0 diff --git a/tst/unit/agents/test_agent_clock_images.py b/tst/unit/agents/test_agent_clock_images.py index 971dd1d80..e0eaa9eae 100644 --- a/tst/unit/agents/test_agent_clock_images.py +++ b/tst/unit/agents/test_agent_clock_images.py @@ -2,14 +2,20 @@ clock takes the computer bases' clock library and egress proxy from agent-env's one copy, whose libfaketime patch has the init guard; runs the follower and the proxy, each as its own user, and the A2A server as the agent's user on real time, under root's supervisord; preloads agent-env's libfaketime for the agent's user alone; starts as another user as -it did before; and its bridge takes ``clock_armed`` and ``egress_env`` from the one shared ``agent_egress``, in a folder -only agent images take, which its image copies beside it.""" +it did before; stops when the A2A server exits, as the image did when the server was its main process, while the +follower and the proxy restart in place; and its bridge takes ``clock_armed`` and ``egress_env`` from the one shared +``agent_egress``, in a folder only agent images take, which its image copies beside it.""" from __future__ import annotations import ast +import configparser +import json import posixpath import re +import shlex +import subprocess +import sys import tomllib from pathlib import Path @@ -57,10 +63,15 @@ def test_the_libfaketime_every_clocked_image_builds_has_the_init_guard(): assert "pthread_once(&initialized_once_control, ftpl_really_init_guarded);" in patch +def _conf(agent: str) -> configparser.RawConfigParser: + """The image's root.conf as supervisord reads it, with its inline comments.""" + conf = configparser.RawConfigParser(inline_comment_prefixes=(";", "#")) + conf.read_string((AGENTS_DIR / agent / "root.conf").read_text()) + return conf + + def _program(agent: str, name: str) -> dict[str, str]: - conf = (AGENTS_DIR / agent / "root.conf").read_text() - section = re.search(rf"^\[program:{name}\]\n(.*?)(?=^\[|\Z)", conf, re.MULTILINE | re.DOTALL).group(1) - return dict(line.split("=", 1) for line in section.splitlines() if "=" in line and not line.startswith(";")) + return dict(_conf(agent)[f"program:{name}"]) @pytest.mark.parametrize("agent", CLOCKED) @@ -74,6 +85,55 @@ def test_the_follower_and_the_proxy_run_as_their_own_users_and_the_a2a_server_as assert f'AGENTENV_EGRESS_PROXY="{PROXY}"' in server["environment"] +@pytest.mark.parametrize("agent", CLOCKED) +def test_the_a2a_server_is_never_restarted_and_the_follower_and_the_proxy_are(agent): + """A server restarted in place would have lost the env's MCP servers, its config, its peers and its running tasks.""" + assert (_program(agent, "agent")["autorestart"], _program(agent, "agent")["startretries"]) == ("false", "0") + assert _program(agent, "clock")["autorestart"] == _program(agent, "egress")["autorestart"] == "true" + + +# What supervisord sends a listener: each event's header line, then its payload of len bytes. +LISTENER_HOST = r""" +import json, signal, subprocess, sys +argv, events = json.loads(sys.argv[1]), json.loads(sys.argv[2]) +terminated = [] +signal.signal(signal.SIGTERM, lambda *_: terminated.append(1)) +listener = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) +after = [] +for serial, (name, payload) in enumerate(events): + assert listener.stdout.readline() == b"READY\n" + body = payload.encode() + listener.stdin.write(f"ver:3.0 server:supervisor serial:{serial} pool:p poolserial:{serial} eventname:{name} " + f"len:{len(body)}\n".encode() + body) + listener.stdin.flush() + assert listener.stdout.readline() == b"RESULT 2\n" and listener.stdout.read(2) == b"OK" + after.append(len(terminated)) +listener.stdin.close() +print(json.dumps({"terminated_after": after, "stderr": listener.stderr.read().decode(), "exit": listener.wait()})) +""" + + +@pytest.mark.parametrize("agent", CLOCKED) +def test_the_a2a_servers_exit_stops_supervisord_and_the_followers_or_the_proxys_doesnt(agent): + """The listener, run as supervisord runs it, under a stand-in for supervisord that counts the SIGTERMs it gets.""" + [section] = [name for name in _conf(agent).sections() if name.startswith("eventlistener:")] + listener = _conf(agent)[section] + assert set(listener["events"].split(",")) == {"PROCESS_STATE_EXITED", "PROCESS_STATE_FATAL"} + assert "%" not in listener["command"] + events = [("PROCESS_STATE_EXITED", "processname:clock groupname:clock from_state:RUNNING expected:0 pid:7"), + ("PROCESS_STATE_FATAL", "processname:egress groupname:egress from_state:BACKOFF"), + ("PROCESS_STATE_EXITED", "processname:agent-exit groupname:agent-exit from_state:RUNNING expected:1 pid:8"), + ("PROCESS_STATE_EXITED", "processname:agent groupname:agent from_state:RUNNING expected:0 pid:9"), + ("PROCESS_STATE_FATAL", "processname:agent groupname:agent from_state:BACKOFF")] + + host = subprocess.run([sys.executable, "-I", "-c", LISTENER_HOST, json.dumps(shlex.split(listener["command"])), + json.dumps(events)], capture_output=True, text=True, timeout=30, check=True) + + result = json.loads(host.stdout) + assert result["terminated_after"] == [0, 0, 0, 1, 2] + assert result["stderr"].count("the A2A server exited") == 2 and result["exit"] == 0 + + @pytest.mark.parametrize("agent", CLOCKED) def test_the_agents_proxy_reaches_private_networks_where_its_model_endpoint_may_be_and_a_computers_doesnt(agent): # The agent's processes reach those directly anyway; its model endpoint, over TLS, goes through the proxy.