diff --git a/src/agent_env/env/gateway/child_sessions.py b/src/agent_env/env/gateway/child_sessions.py index 12b6dc6c7..70eab1c10 100644 --- a/src/agent_env/env/gateway/child_sessions.py +++ b/src/agent_env/env/gateway/child_sessions.py @@ -10,7 +10,8 @@ A call that never reached the child (the child rejected the session, or its stream had closed) is retried once on a fresh session. A call the transport lost in flight may already have written, so its session is retired: every call -still on it fails with CONNECTION_CLOSED at once, it is closed in the background, and the call is not retried. A +still on it fails with CONNECTION_CLOSED at once, it is closed in the background, and the call is not retried. A call +that times out retires its session the same way, so a stuck stream doesn't hold every later call to that child. A session whose ``close`` is set is never handed to a new call. Nothing here touches another child's session. Each session is held open by an owner task of its own: mcp's client contexts are anyio task groups, exited only by @@ -81,7 +82,9 @@ async def call(self, url: str, tool_name: str, arguments: dict, meta: dict | Non child.""" child = await self.ensure(url) try: - return await asyncio.wait_for(self._call_on(child, tool_name, arguments, meta), timeout=timeout) + return await self._call_or_retire(child, tool_name, arguments, meta, timeout) + except TimeoutError: + raise except Exception as e: if not is_dead_session(e): raise @@ -92,7 +95,20 @@ async def call(self, url: str, tool_name: str, arguments: dict, meta: dict | Non await self.replace(child) logger.warning(f"child session to {url} is dead ({e!r}), reconnecting...") child = await self.ensure(url) + return await self._call_or_retire(child, tool_name, arguments, meta, timeout) + + async def _call_or_retire(self, child: ChildSession, tool_name: str, arguments: dict, meta: dict | None, + timeout: float) -> CallToolResult: + """``tool_name`` on ``child``, within ``timeout``. A call that outlives it says the session (or the child + behind it) stopped answering. Left current, it would hand every later call to the same stuck stream, each + waiting out its own timeout, so it is retired: calls still on it fail now, and the next call opens a fresh + session (FD-7164). The timed-out call itself is not retried: it may have written.""" + try: return await asyncio.wait_for(self._call_on(child, tool_name, arguments, meta), timeout=timeout) + except TimeoutError: + logger.warning(f"{tool_name} on {child.url} timed out after {timeout}s; retiring its session") + self.retire_soon(child) + raise async def ensure(self, url: str) -> ChildSession: """The current session to the child at ``url``, opened on first need, and again once the last one was retired diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 5605a5834..091332b45 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -159,6 +159,9 @@ class Gateway: """Gateway that aggregates MCP tools and REST proxies for website backends.""" TOOL_CALL_TIMEOUT_S = 600.0 + # The trigger engine's own child calls (world actions, state checks): a world event is a short write or read, and + # one stuck on a child must fail in minutes, not hold the next one behind it (FD-7164). + TRIGGER_TOOL_CALL_TIMEOUT_S = 120.0 STARTUP_DISCOVERY_TIMEOUT_S = 60.0 # startup discovery past it fails open, like a failed one; uvicorn must come up BARRIER_READ_AHEAD_MAX_BYTES = 8 * 1024 * 1024 # a larger sized body held by a barrier streams, its window to the last byte TRIGGER_BARRIER_TIMEOUT_S = 30.0 # a barrier may ask for less; past it the call is answered anyway @@ -1258,7 +1261,8 @@ async def _close_child_sessions(self) -> None: await self._sessions.close() async def _call_child_tool(self, server_url: str, tool_name: str, arguments: dict, *, - caller: Caller | None = None, report: bool) -> CallToolResult: + caller: Caller | None = None, report: bool, + timeout: float | None = None) -> CallToolResult: """Every child tools/call (MCP proxy, /step, trigger engine, deferred calls), with the caller's `_meta` stamp (none for an unattributed trigger action), on its child's session (see child_sessions). Discovery is not redone on a reconnect; the registered proxies look their child up by URL. The deferred calls a result declares are taken @@ -1268,7 +1272,8 @@ async def _call_child_tool(self, server_url: str, tool_name: str, arguments: dic meta = caller.meta() if caller is not None else None role = caller.role if caller is not None else DEFAULT_ROLE self._drive(role, tool_name) - result = await self._sessions.call(server_url, tool_name, arguments, meta, timeout=self.TOOL_CALL_TIMEOUT_S) + result = await self._sessions.call(server_url, tool_name, arguments, meta, + timeout=self.TOOL_CALL_TIMEOUT_S if timeout is None else timeout) return self._deferred.take(result, server_url, role, report=report) async def _ensure_tools_discovered(self) -> None: diff --git a/src/agent_env/env/gateway/triggers.py b/src/agent_env/env/gateway/triggers.py index 47f70dc9d..edb9169bb 100644 --- a/src/agent_env/env/gateway/triggers.py +++ b/src/agent_env/env/gateway/triggers.py @@ -1465,7 +1465,8 @@ async def _internal_call(self, tool_name: str, arguments: dict, role: str | None text = result if isinstance(result, str) else json.dumps(result, default=str) return CallToolResult(content=[TextContent(type="text", text=text)], isError=False) caller = Caller(role=role) if role is not None else None - return await gw._call_child_tool(server_url, tool_name, arguments, caller=caller, report=False) + return await gw._call_child_tool(server_url, tool_name, arguments, caller=caller, report=False, + timeout=gw.TRIGGER_TOOL_CALL_TIMEOUT_S) async def _fire(self, tid: str, trig: dict, ctx: dict, since: float, ticket: dict) -> None: """Run the actions for one provoking call, then drain any calls queued while firing (repeat diff --git a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py index 0382c3994..6b8cfb44c 100644 --- a/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py +++ b/src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py @@ -83,38 +83,47 @@ # The sandbox MAIN process. Two decoupled parts, both for robustness: # 1. A best-effort log forwarder run as a *child* of this process — NOT a separate `exec`. # Modal reaps an exec'd process tree when the exec call returns (that killed an earlier -# nohup'd forwarder); a child of the everlasting main process is not. It polls -# `docker ps` and, per container, streams `docker logs -f` (name-prefixed, `sed -u` -# unbuffered) to THIS process's stdout. Because the forwarder is a child it inherits -# that stdout, which Modal captures into the dashboard — so logs reach Modal with no -# intermediate file. There is therefore no second on-disk copy: Docker's own json-file -# logs (what `docker logs` reads) are the single on-disk copy, and they are size-capped -# at dockerd start (see _ensure_dockerd_running) so they can't fill the disk. Uses -# `docker ps -aq` (not `-q`) so containers that have already exited are also followed: -# `docker logs` persists after exit, and `docker logs -f` on an exited container just -# dumps its logs and returns. That keeps startup/crash logs of a short-lived or failed -# service (often the ones you need) instead of dropping them. New containers (compose -# services / the agent-api container) are picked up by the poll loop as they appear. +# nohup'd forwarder); a child of the everlasting main process is not. Per container it +# streams `docker logs -f` (name-prefixed, `sed -u` unbuffered) to THIS process's stdout, +# which the child inherits and Modal captures into the dashboard — so logs reach Modal with +# no intermediate file. Docker's own json-file logs (what `docker logs` reads) are the single +# on-disk copy, size-capped at dockerd start (see _ensure_dockerd_running). +# It waits for dockerd, follows the containers that already exist (`docker ps -a`: an +# exited one's logs are dumped once, which keeps a failed service's crash output), then +# follows every container *start* from `docker events`, with `--since` the start time. A +# follower ends when its container stops, so following on each start is what catches: +# compose creating every service before starting it, `restart:` policies, recreated +# containers, and short-lived ones (their logs outlive them). The earlier form polled +# `docker ps -a` and followed each container id once: at boot compose had created but not +# yet started all but the first service, those followers exited at once, and only the +# servicedb's logs ever reached Modal (FD-7164). A start event in the same second as the +# first scan, for a container the scan already followed, is skipped so it isn't doubled. # 2. A keepalive that never exits, so liveness is fully decoupled from logging: if the # forwarder child dies, this loop keeps the sandbox alive — equivalent to the previous # `sleep infinity` main process. Logging can never take the env down. _MAIN_SCRIPT = r''' ( - seen="" + until docker info >/dev/null 2>&1; do sleep 1; done + follow() { + sh -c 'docker logs -f --timestamps "$@" 2>&1 | sed -u "s/^/[$0] /"' "$@" /dev/null)) + for c in $existing; do + n=$(timeout 10 docker inspect -f '{{.Name}}' "$c" 2>/dev/null | sed 's#^/##') + follow "${n:-$c}" --tail 200 "$c" + done while true; do - for c in $(docker ps -aq 2>/dev/null); do - case " $seen " in - *" $c "*) ;; - *) - seen="$seen $c" - n=$(docker inspect -f '{{.Name}}' "$c" 2>/dev/null | sed 's#^/##') - ( docker logs -f --tail 200 --timestamps "$c" 2>&1 | sed -u "s/^/[$n] /" ) & - ;; - esac - done - sleep 3 + docker events --since "$since" --filter type=container --filter event=start \ + --format '{{.Actor.ID}} {{.Time}} {{index .Actor.Attributes "name"}}' 2>/dev/null | + while read -r c t n; do + if [ "$t" -le "$since" ]; then case " $existing " in *" $c "*) continue ;; esac; fi + follow "${n:-$c}" --since "$t" "$c" + done + since=$(date +%s); existing="" + sleep 1 done -) & +) lines flush immediately - assert ") &" in _MAIN_SCRIPT # forwarder backgrounded -> keepalive is the foreground + assert ") keepalive is the foreground assert "/var/log/agg.log" not in _MAIN_SCRIPT # no spool file -> no extra disk copy assert "tail -F" not in _MAIN_SCRIPT # not tailing a file anymore # (2) a keepalive that never exits, so a forwarder crash can't take the env down @@ -355,6 +355,84 @@ def test_main_script_streams_logs_to_stdout_and_is_a_bulletproof_keepalive(): assert "sleep 3600" in _MAIN_SCRIPT +_FAKE_DOCKER = r"""#!/bin/sh +# docker stand-in. `info` fails until $W/ready exists. `ps -aq` lists $W/ids (created or running). `logs -f `, like +# docker's, ends at once for a container that isn't running (it has no logs yet) and otherwise prints a line and +# follows. `events` streams $W/events, one start per line: " ". +case "$1" in + info) [ -f "$W/ready" ] ;; + ps) cat "$W/ids" 2>/dev/null ;; + inspect) echo "/name-$4" ;; + logs) for a; do last=$a; done + grep -qx "$last" "$W/running" 2>/dev/null || exit 0 + echo "line from $last"; exec sleep 600 ;; + events) touch "$W/events"; exec tail -n +1 -f "$W/events" ;; +esac +""" + + +def test_main_script_forwarder_follows_every_container_start(tmp_path): + # FD-7164: compose creates every service before it starts them, so at boot the earlier forwarder (one follower per + # container id, the first time `docker ps -a` listed it) followed containers that weren't running yet; those + # followers ended at once and were never retried, and only the servicedb's logs reached Modal. The forwarder now + # waits for dockerd, follows what exists, then follows each container *start*: services started later and + # containers that restart are followed too, and a replayed start for one it already follows isn't doubled. + import os + import shutil + import signal + import subprocess + import time + + from agent_env.providers.sandbox_providers.modal_vm_sandbox import _MAIN_SCRIPT + + if not shutil.which("timeout"): + pytest.skip("needs coreutils `timeout` (the sandbox VM has it)") + (tmp_path / "docker").write_text(_FAKE_DOCKER) + (tmp_path / "docker").chmod(0o755) + env = dict(os.environ, PATH=f"{tmp_path}:{os.environ['PATH']}", W=str(tmp_path)) + out = open(tmp_path / "out.txt", "w") + proc = subprocess.Popen(["sh", "-c", _MAIN_SCRIPT], env=env, stdout=out, stderr=subprocess.STDOUT, + start_new_session=True) + + def start(c): + with open(tmp_path / "running", "a") as f: + f.write(f"{c}\n") + with open(tmp_path / "events", "a") as f: + f.write(f"{c} {int(time.time()) + 5} name-{c}\n") + + def wait_for(counts): + deadline, text = time.time() + 20, "" + while time.time() < deadline: + text = (tmp_path / "out.txt").read_text() + if all(text.count(f"[name-{c}] line from {c}") >= n for c, n in counts.items()): + break + time.sleep(0.3) + return text + + try: + # compose has created three services and started only the servicedb; dockerd isn't up yet + (tmp_path / "ids").write_text("servicedb\ngateway\npennyfold\n") + (tmp_path / "running").write_text("servicedb\n") + (tmp_path / "events").write_text("servicedb 0 name-servicedb\n") # its start, replayed by `docker events` + time.sleep(2) + assert "line from" not in (tmp_path / "out.txt").read_text() + (tmp_path / "ready").touch() + wait_for({"servicedb": 1}) + start("gateway") + start("pennyfold") + wait_for({"gateway": 1, "pennyfold": 1}) + start("gateway") # a restart: its follower ended with the old run, so the new run is followed again + text = wait_for({"gateway": 2, "pennyfold": 1}) + time.sleep(1) + text = (tmp_path / "out.txt").read_text() + assert text.count("[name-servicedb] line from servicedb") == 1, text + assert text.count("[name-gateway] line from gateway") == 2, text + assert text.count("[name-pennyfold] line from pennyfold") == 1, text + finally: + os.killpg(proc.pid, signal.SIGKILL) + out.close() + + @pytest.mark.asyncio async def test_setup_raises_with_dockerd_log_on_timeout(): s = _sandbox()