From b907f8a9863b3cd05146b125a1791b38ca0ba6ef Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 11:39:36 -0800 Subject: [PATCH 1/3] fix(gateway): retire a child session whose call times out, and time trigger calls out at 120 s (FD-7164) A child call that timed out left its session current, so every later call to that child queued on the same stuck stream and waited out its own timeout. In an always-on run the trigger engine's world actions and state checks then failed one 600 s timeout at a time for four hours: no world event happened after the first hang. - ChildSessions.call retires the session on a timeout: calls still on it fail with CONNECTION_CLOSED now, the next call opens a fresh session. The timed-out call isn't retried (it may have written). - The trigger engine's own child calls time out at TRIGGER_TOOL_CALL_TIMEOUT_S (120 s), not the 600 s agent limit. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/child_sessions.py | 11 ++- src/agent_env/env/gateway/gateway.py | 9 ++- src/agent_env/env/gateway/triggers.py | 3 +- tst/unit/env/gateway/child_sessions_test.py | 86 +++++++++++++++++++++ 4 files changed, 105 insertions(+), 4 deletions(-) diff --git a/src/agent_env/env/gateway/child_sessions.py b/src/agent_env/env/gateway/child_sessions.py index 12b6dc6c7..c2b90d077 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 @@ -82,6 +83,14 @@ async def call(self, url: str, tool_name: str, arguments: dict, meta: dict | Non child = await self.ensure(url) try: return await asyncio.wait_for(self._call_on(child, tool_name, arguments, meta), timeout=timeout) + except TimeoutError: + # A call that outlives its timeout 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. + logger.warning(f"{tool_name} on {url} timed out after {timeout}s; retiring its session") + self.retire_soon(child) + raise except Exception as e: if not is_dead_session(e): raise 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/tst/unit/env/gateway/child_sessions_test.py b/tst/unit/env/gateway/child_sessions_test.py index 5083bcbad..efc702002 100644 --- a/tst/unit/env/gateway/child_sessions_test.py +++ b/tst/unit/env/gateway/child_sessions_test.py @@ -583,3 +583,89 @@ async def held(name, arguments, *args, meta=None, **kwargs): opener.gate.set() await opening await gw._close_child_sessions() + + +class _HangingSession(_FakeSession): + """A session whose first call never answers (a stuck stream); later calls answer at once.""" + + def __init__(self): + super().__init__() + self.stuck = asyncio.Event() # never set + + async def call_tool(self, name, arguments, *args, meta=None, **kwargs): + self.calls.append(name) + if len(self.calls) == 1: + await self.stuck.wait() + return _result() + + +@pytest.mark.asyncio +async def test_a_call_that_times_out_retires_its_session_and_the_next_call_reopens(monkeypatch): + # FD-7164: a child call that hung kept its session current, so every later call to that child (the trigger + # engine's world actions among them) waited out its own timeout on the same stuck stream, for hours. + sessions = [_HangingSession(), _FakeSession()] + opener = _Opener(sessions[0]) + gw = _gateway(opener) + monkeypatch.setattr(gw, "TOOL_CALL_TIMEOUT_S", 0.05) + try: + await gw._ensure_child_sessions() + first_owner = _owner(gw) + with pytest.raises(TimeoutError): + await gw._call_child_tool(URL, "svc_thing", {}, report=True) + await asyncio.gather(*gw._sessions.retirements) + assert first_owner.done() and URL not in gw._sessions.current + opener.session = sessions[1] + assert not (await gw._call_child_tool(URL, "svc_thing", {}, report=True)).isError # a fresh session answers + assert opener.opened == 2 and sessions[0].calls == ["svc_thing"] and sessions[1].calls == ["svc_thing"] + finally: + await gw._close_child_sessions() + + +@pytest.mark.asyncio +async def test_a_timed_out_call_fails_the_calls_waiting_on_the_same_session_at_once(monkeypatch): + session = _HangingSession() + gate = asyncio.Event() + + async def slow_second(name, arguments, *args, meta=None, **kwargs): + session.calls.append(name) + if len(session.calls) == 1: + await session.stuck.wait() + await gate.wait() # the second call is still in flight when the first times out + return _result() + + session.call_tool = slow_second # type: ignore[method-assign] + gw = _gateway(_Opener(session)) + monkeypatch.setattr(gw, "TOOL_CALL_TIMEOUT_S", 0.05) + try: + await gw._ensure_child_sessions() + first = asyncio.ensure_future(gw._call_child_tool(URL, "svc_thing", {}, report=True)) + await asyncio.sleep(0.01) + second = asyncio.ensure_future(gw._call_child_tool(URL, "svc_thing", {}, report=True, + timeout=30.0)) + with pytest.raises(TimeoutError): + await first + with pytest.raises(McpError, match="Connection closed"): + await asyncio.wait_for(second, timeout=2.0) # not its own 30 s + finally: + gate.set() + await gw._close_child_sessions() + + +@pytest.mark.asyncio +async def test_the_trigger_engine_s_calls_use_the_shorter_trigger_timeout(): + gw = _gateway(_Opener(_FakeSession())) + seen: list[float] = [] + original = gw._sessions.call + + async def call(url, tool_name, arguments, meta, *, timeout): + seen.append(timeout) + return await original(url, tool_name, arguments, meta, timeout=timeout) + + gw._sessions.call = call # type: ignore[method-assign] + try: + await gw._call_child_tool(URL, "svc_thing", {}, report=True) + await gw._trigger_engine._internal_call("svc_thing", {}) + assert seen == [gw.TOOL_CALL_TIMEOUT_S, gw.TRIGGER_TOOL_CALL_TIMEOUT_S] + assert gw.TRIGGER_TOOL_CALL_TIMEOUT_S < gw.TOOL_CALL_TIMEOUT_S + finally: + await gw._close_child_sessions() From 8b4725b6c96c74f0fab42f997ae6ef01523bbba5 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 13:30:00 -0800 Subject: [PATCH 2/3] Modal VM log forwarder: follow every container start, not each id once At boot compose creates every service before starting it. The forwarder polled `docker ps -a` and started one `docker logs -f` per container id the first time it saw it; for a container not yet running that follower ends at once and was never retried, so only the servicedb's logs reached Modal (FD-7164). Restarted or recreated containers were lost the same way. The forwarder now waits for dockerd, follows the containers that exist, then follows each container start from `docker events` with `--since` the start time. A replayed start for a container the first scan already follows is skipped. Verified on a Modal VM boot of a 41-container multi env: all 41 containers' logs in the dashboard (was 1). Co-Authored-By: Claude Opus 5.5 --- .../sandbox_providers/modal_vm_sandbox.py | 59 +++++++------ .../modal_vm_sandbox_test.py | 84 ++++++++++++++++++- 2 files changed, 115 insertions(+), 28 deletions(-) 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() From 26813111366b491d12d890a1f4cd6fdb5a68ac93 Mon Sep 17 00:00:00 2001 From: Sarah Chitty Date: Wed, 2 Dec 2026 13:32:43 -0800 Subject: [PATCH 3/3] fix(gateway): retire the replacement session too when its retry times out A call retried on a fresh session (the first was dead before the call reached the child) timed out without retiring that session, so it stayed current for the next call to wait on. Both attempts now go through one helper that retires the session on a timeout. Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/child_sessions.py | 21 ++++++++++++------- tst/unit/env/gateway/child_sessions_test.py | 23 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/agent_env/env/gateway/child_sessions.py b/src/agent_env/env/gateway/child_sessions.py index c2b90d077..70eab1c10 100644 --- a/src/agent_env/env/gateway/child_sessions.py +++ b/src/agent_env/env/gateway/child_sessions.py @@ -82,14 +82,8 @@ 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: - # A call that outlives its timeout 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. - logger.warning(f"{tool_name} on {url} timed out after {timeout}s; retiring its session") - self.retire_soon(child) raise except Exception as e: if not is_dead_session(e): @@ -101,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/tst/unit/env/gateway/child_sessions_test.py b/tst/unit/env/gateway/child_sessions_test.py index efc702002..ce760b796 100644 --- a/tst/unit/env/gateway/child_sessions_test.py +++ b/tst/unit/env/gateway/child_sessions_test.py @@ -621,6 +621,29 @@ async def test_a_call_that_times_out_retires_its_session_and_the_next_call_reope await gw._close_child_sessions() +@pytest.mark.asyncio +async def test_a_retry_that_times_out_on_the_replacement_session_retires_that_session_too(monkeypatch): + # The first session is dead before the call reaches the child, so the call is retried on a replacement; when + # that one hangs, it is retired as well, not left current for the next call to wait on. + dead, hanging, good = _FakeSession(), _HangingSession(), _FakeSession() + dead.failures.append(anyio.ClosedResourceError()) + opener = _Opener(dead) + gw = _gateway(opener) + monkeypatch.setattr(gw, "TOOL_CALL_TIMEOUT_S", 0.05) + try: + await gw._ensure_child_sessions() + opener.session = hanging + with pytest.raises(TimeoutError): + await gw._call_child_tool(URL, "svc_thing", {}, report=True) + await asyncio.gather(*gw._sessions.retirements) + assert URL not in gw._sessions.current + opener.session = good + assert not (await gw._call_child_tool(URL, "svc_thing", {}, report=True)).isError + assert opener.opened == 3 and hanging.calls == ["svc_thing"] and good.calls == ["svc_thing"] + finally: + await gw._close_child_sessions() + + @pytest.mark.asyncio async def test_a_timed_out_call_fails_the_calls_waiting_on_the_same_session_at_once(monkeypatch): session = _HangingSession()