Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions src/agent_env/env/gateway/child_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Comment thread
sarah-chitty-1 marked this conversation as resolved.
Resolved
except Exception as e:
if not is_dead_session(e):
raise
Expand All @@ -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
Expand Down
9 changes: 7 additions & 2 deletions src/agent_env/env/gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion src/agent_env/env/gateway/triggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
59 changes: 34 additions & 25 deletions src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 &
}
since=$(date +%s)
existing=$(echo $(timeout 20 docker ps -aq --no-trunc 2>/dev/null))
for c in $existing; do
n=$(timeout 10 docker inspect -f '{{.Name}}' "$c" 2>/dev/null | sed 's#^/##')
Comment on lines +111 to +113

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Log limits lack names

The new log forwarder embeds its 20-second scan timeout and 10-second inspect timeout directly in shell commands. The repository requires magic numbers to be stored as class or instance variables with descriptive names. Give these limits named settings before merging so maintainers can find and understand them without reading the shell commands.

Rule Used: Store magic numbers as class or instance variables with descriptive names rather than using them inline in the code. (source)

Learned From
scaleapi/scaleapi#126388

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py
Line: 111-113

Comment:
**Log limits lack names**

The new log forwarder embeds its `20`-second scan timeout and `10`-second inspect timeout directly in shell commands. The repository requires magic numbers to be stored as class or instance variables with descriptive names. Give these limits named settings before merging so maintainers can find and understand them without reading the shell commands.

**Rule Used:** Store magic numbers as class or instance variables with descriptive names rather than using them inline in the code. ([source](https://app.greptile.com/-/switch-tenant?tenant=scale-ai&next=%2Fcustom-context%3Fmemory%3D002e0051-41ad-46c1-9098-47433c580150))

**Learned From**
[scaleapi/scaleapi#126388](https://github.com/scaleapi/scaleapi/pull/126388)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Cursor Fix in Claude Code Fix in Codex

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Same-second starts lose logs

existing includes containers that have been created but not started. If the first log follower exits before one starts, and the start happens in the same second as since, this check discards its only start event. That service's logs then stay missing from Modal until another restart.

Track whether a follower is still running rather than skipping every scanned ID. Add a same-second test; the current test puts start times five seconds ahead.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agent_env/providers/sandbox_providers/modal_vm_sandbox.py
Line: 120

Comment:
**Same-second starts lose logs**

`existing` includes containers that have been created but not started. If the first log follower exits before one starts, and the start happens in the same second as `since`, this check discards its only start event. That service's logs then stay missing from Modal until another restart.

Track whether a follower is still running rather than skipping every scanned ID. Add a same-second test; the current test puts start times five seconds ahead.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Cursor Fix in Claude Code Fix in Codex

follow "${n:-$c}" --since "$t" "$c"
done
since=$(date +%s); existing=""
sleep 1
done
) &
) </dev/null &
while true; do sleep 3600; done
'''
_KEEPALIVE_CMD = ("sh", "-c", _MAIN_SCRIPT)
Expand Down
109 changes: 109 additions & 0 deletions tst/unit/env/gateway/child_sessions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,3 +583,112 @@ 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_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()
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()
Loading
Loading