diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 358b6dd40..6f985840c 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -218,6 +218,19 @@ extension's, and `client.invoke_extension(base_url, card, uri, params, method=.. its HTTP verb. Without `method`, `invoke_extension` calls the first method listed; an extension with several methods, such as a gateway's `urn:agentenv:clock/v1`, should always be called by name. +An extension call makes one connection attempt by default. Wrap a call in +`client.retry_extension_connections()` to retry a transient connection failure before sending. + +```python +with client.retry_extension_connections(): + state = await client.invoke_extension(url, card, "urn:agentenv:clock/v1", {}, method="state") +``` + +TCP and TLS share the connection budget from `timeout`, including waits of 0.5 and 1 second if +there is time for a second or third attempt. Once the request starts sending, read and write +errors propagate with HTTPX's usual inactivity timeouts. The framework opts in when setting up +the environment clock and tool access. + An extension with several methods is served by giving each handler an `op`. Handlers sharing a URI merge into one card entry, each method under `params.methods.` with its own verb and endpoint, by default `/agentenv/ext//`, where `` is the URN's name without diff --git a/packages/agentenv-protocol/pyproject.toml b/packages/agentenv-protocol/pyproject.toml index 5d3ab9717..a0af7affb 100644 --- a/packages/agentenv-protocol/pyproject.toml +++ b/packages/agentenv-protocol/pyproject.toml @@ -73,6 +73,7 @@ dev = [ "regex>=2023.12.25", "pytest>=9.0", "pytest-asyncio>=0.23.0", + "trio>=0.24", "mcp>=1.25,<2", "fastmcp>=3.4,<4", # the standalone-fastmcp mount path "Pillow>=10.4", # the computer extra's frame crops and encodings diff --git a/packages/agentenv-protocol/src/agentenv_protocol/_connect.py b/packages/agentenv-protocol/src/agentenv_protocol/_connect.py new file mode 100644 index 000000000..234afbc79 --- /dev/null +++ b/packages/agentenv-protocol/src/agentenv_protocol/_connect.py @@ -0,0 +1,66 @@ +"""Bound connection attempts for an opted-in HTTPX extension call.""" + +import asyncio +from importlib import import_module +from math import inf, isfinite + +import httpx + +try: + import sniffio +except ImportError: + sniffio = None + + +async def send(client: httpx.AsyncClient, request: httpx.Request) -> httpx.Response: + # Match HTTPX's active backend, including a Trio guest task running on an asyncio loop. + trio = import_module("trio") if sniffio is not None and sniffio.current_async_library() == "trio" else None + if trio is None: + now, sleep = asyncio.get_running_loop().time, asyncio.sleep + else: + now, sleep = trio.current_time, trio.sleep + + connect_timeout = request.extensions["timeout"]["connect"] + deadline = inf if connect_timeout is None else now() + connect_timeout + sent = False + extensions = request.extensions + previous = extensions.get("trace") + + async def trace(event, info): + nonlocal sent, stream + if event.endswith((".connect_tcp.started", ".start_tls.started")) and not sent and isfinite(attempt_deadline): + # TCP and TLS share one attempt's budget, including a TLS handshake through a CONNECT proxy. + info["timeout"] = max(0, attempt_deadline - now()) + elif event.endswith((".connect_tcp.complete", ".start_tls.complete")): + stream = info["return_value"] + elif event.endswith(".start_tls.failed") and stream is not None and not isinstance(info["exception"], Exception): + # httpcore hasn't taken ownership of the handshake socket when the caller cancels it. + if trio is None: + await asyncio.shield(stream.aclose()) + else: + with trio.CancelScope(shield=True): + await stream.aclose() + elif event.endswith(".send_request_headers.started") and info["request"].method != b"CONNECT": + sent = True + if previous is not None: + await previous(event, info) + + request.extensions = {**extensions, "trace": trace} + try: + delays = (0.5, 1.0, None) + for attempt, delay in enumerate(delays): + stream = None + started = now() + remaining = max(0, deadline - started) + share = remaining / (len(delays) - attempt) + attempt_deadline = started + share if delay is not None and share + delay < remaining else deadline + try: + return await client.send(request) + except (httpx.ConnectError, httpx.ConnectTimeout) as exc: + if sent or exc.request is not request or delay is None or now() + delay >= deadline: + raise + await sleep(delay) + if now() >= deadline: + raise + finally: + request.extensions = extensions diff --git a/packages/agentenv-protocol/src/agentenv_protocol/client.py b/packages/agentenv-protocol/src/agentenv_protocol/client.py index 0d76ad4aa..505af9fe3 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/client.py @@ -13,12 +13,14 @@ from .manifest import INTERFACE_MANIFEST_PATH from .transfers import WriteNamespaceGrant +from . import _connect from .types import CONTROL_TOKEN_HEADER, INTAKE_EXTENSION_URI, MCP_PATH, MCP_TRANSPORT, METHOD_ADD, METHOD_GET, METHOD_RESET, RPC_PATH, WELL_KNOWN_PATH, AddDataResponse, GetDataResponse, Part, ResetDataResponse logger = logging.getLogger(__name__) #: The headers that carry the control token of each env address the running code is granted, by address. _GRANTS: ContextVar[dict[str, dict[str, str]]] = ContextVar("agentenv_control_grants", default={}) +_RETRY_EXTENSION_CONNECTIONS = ContextVar("agentenv_retry_extension_connections", default=False) class ExtensionCallError(httpx.HTTPStatusError): @@ -338,6 +340,16 @@ async def get_interface_manifest(base_url: str, interface: str, endpoint: str = return response.json() +@contextlib.contextmanager +def retry_extension_connections() -> Iterator[None]: + """Allow up to three connection attempts for extension calls made in this context, before sending the request.""" + token = _RETRY_EXTENSION_CONNECTIONS.set(True) + try: + yield + finally: + _RETRY_EXTENSION_CONNECTIONS.reset(token) + + async def invoke_extension(base_url: str, card: dict, uri: str, params: dict | None = None, timeout: int = 30, verify: bool = True, *, method: str | None = None, headers: dict[str, str] | None = None): """Invoke a card extension via its advertised REST endpoint. @@ -360,7 +372,11 @@ async def invoke_extension(base_url: str, card: dict, uri: str, params: dict | N url = f"{base_url.rstrip('/')}{op['endpoint']}" sent = request_headers(url, headers) async with httpx.AsyncClient(verify=verify) as client: - if op["method"] == "GET": + if _RETRY_EXTENSION_CONNECTIONS.get(): + arguments = {"params": params or {}} if op["method"] == "GET" else {"json": params or {}} + request = client.build_request(op["method"], url, headers=sent, timeout=timeout, **arguments) + response = await _connect.send(client, request) + elif op["method"] == "GET": response = await client.get(url, params=params or {}, timeout=timeout, headers=sent) else: response = await client.request(op["method"], url, json=params or {}, timeout=timeout, headers=sent) diff --git a/packages/agentenv-protocol/tests/test_connect_retries.py b/packages/agentenv-protocol/tests/test_connect_retries.py new file mode 100644 index 000000000..cb97ac8f4 --- /dev/null +++ b/packages/agentenv-protocol/tests/test_connect_retries.py @@ -0,0 +1,185 @@ +"""Opted-in extension calls, through HTTPX's real request and redirect handling.""" + +import asyncio +from contextlib import nullcontext + +import httpcore +import httpx +import pytest +import trio +from httpcore._backends.auto import AutoBackend +from trio.testing import MockClock + +from agentenv_protocol import ExtensionCallError, ToolSession, client + + +_URL = "http://env.test" +_URI = "urn:example:setup/v1" +_CARD = {"capabilities": {"extensions": [{"uri": _URI, "params": {"methods": { + "set": {"method": "POST", "endpoint": "/set"}, "get": {"method": "GET", "endpoint": "/get"}, +}}}]}} + + +async def extension(method="set", timeout=5): + return await client.invoke_extension(_URL, _CARD, _URI, {"value": 1}, timeout=timeout, method=method) + + +def mock_http(monkeypatch, handle, *, redirects=False): + real = httpx.AsyncClient + + def make_client(**kwargs): + kwargs.setdefault("follow_redirects", redirects) + return real(transport=httpx.MockTransport(handle), **kwargs) + + monkeypatch.setattr(httpx, "AsyncClient", make_client) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("method", ["get", "set"]) +async def test_only_opted_in_extensions_retry(monkeypatch, method): + attempts, received = [], [] + + def handle(request): + attempts.append(request) + if len(attempts) == 1: + raise httpx.ConnectTimeout("before sending") + received.append(request) + return httpx.Response(200, json={"ok": True}) + + mock_http(monkeypatch, handle) + with pytest.raises(httpx.ConnectTimeout): + await extension(method) + assert len(attempts) == 1 and not received + attempts.clear() + with client.retry_extension_connections(): + assert await extension(method) == {"ok": True} + assert len(attempts) == 2 + [request] = received + if method == "get": + assert request.method == "GET" and request.url.params["value"] == "1" + else: + assert request.method == "POST" and request.content + attempts.clear() + with pytest.raises(httpx.ConnectTimeout): + await extension(method) + assert len(attempts) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("route", ["data", "card", "manifest", "tool"]) +async def test_other_clients_still_make_one_attempt_in_the_retry_context(monkeypatch, route): + hosts = [] + + async def refuse(self, host, **kwargs): + hosts.append(host) + raise httpcore.ConnectError("connection refused") + + monkeypatch.setenv("no_proxy", "*") + monkeypatch.setattr(AutoBackend, "connect_tcp", refuse) + with client.retry_extension_connections(), pytest.raises(httpx.ConnectError): + if route == "data": + await client.add_data(_URL, []) + elif route == "card": + await client.get_card(_URL) + elif route == "manifest": + await client.get_interface_manifest(_URL, "items") + else: + async with ToolSession(mcp_url=_URL + "/mcp"): + pytest.fail("MCP initialization should fail") + assert hosts == ["env.test"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("timeout, expected", [(5, 3), (0.25, 1)]) +async def test_exhaustion_returns_the_last_connection_error(monkeypatch, timeout, expected): + started = [] + + def refuse(request): + started.append(asyncio.get_running_loop().time()) + raise httpx.ConnectError(f"attempt {len(started)}") + + mock_http(monkeypatch, refuse) + with client.retry_extension_connections(), pytest.raises(httpx.ConnectError, match=f"attempt {expected}") as caught: + await extension(timeout=timeout) + assert len(started) == expected and caught.value.request.url.path == "/set" + if expected == 3: + assert started[1] - started[0] >= 0.49 and started[2] - started[1] >= 0.99 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error", [httpx.ReadTimeout, httpx.WriteTimeout, httpx.PoolTimeout, ExtensionCallError]) +async def test_other_errors_propagate_after_one_attempt(monkeypatch, error): + calls = [] + + def handle(request): + calls.append(request) + if error is ExtensionCallError: + return httpx.Response(503) + raise error("interrupted") + + mock_http(monkeypatch, handle) + with client.retry_extension_connections(), pytest.raises(error): + await extension() + assert len(calls) == 1 + + +@pytest.mark.asyncio +async def test_a_failed_redirect_target_does_not_replay_the_first_hop(monkeypatch): + paths = [] + + def handle(request): + paths.append(request.url.path) + if request.url.path == "/set": + return httpx.Response(307, headers={"Location": "/next"}) + raise httpx.ConnectError("redirect target unavailable") + + mock_http(monkeypatch, handle, redirects=True) + with client.retry_extension_connections(), pytest.raises(httpx.ConnectError): + await extension() + assert paths == ["/set", "/next"] + + +@pytest.mark.asyncio +async def test_cancelling_one_opted_in_task_leaves_a_sibling_on_one_attempt(monkeypatch): + failed = asyncio.Event() + attempts = [] + + def refuse(request): + attempts.append(request) + failed.set() + raise httpx.ConnectError("refused") + + mock_http(monkeypatch, refuse) + with client.retry_extension_connections(): + task = asyncio.create_task(extension()) + await failed.wait() + with pytest.raises(httpx.ConnectError): + await extension() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert len(attempts) == 2 + + +@pytest.mark.parametrize("opt_in", [False, True]) +def test_native_trio_uses_its_own_clock_for_backoff(monkeypatch, opt_in): + attempts = [] + + async def connect(self, host, **kwargs): + attempts.append(trio.current_time()) + if len(attempts) == 1: + raise httpcore.ConnectError("connection refused") + return httpcore.AsyncMockStream([b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"]) + + async def run(): + with client.retry_extension_connections() if opt_in else nullcontext(): + if opt_in: + assert await extension() == {} + else: + with pytest.raises(httpx.ConnectError): + await extension() + + monkeypatch.setenv("no_proxy", "*") + monkeypatch.setattr(AutoBackend, "connect_tcp", connect) + trio.run(run, clock=MockClock(autojump_threshold=0)) + assert attempts == ([0, 0.5] if opt_in else [0]) diff --git a/packages/agentenv-protocol/tests/test_transport_timeouts.py b/packages/agentenv-protocol/tests/test_transport_timeouts.py new file mode 100644 index 000000000..1e4920319 --- /dev/null +++ b/packages/agentenv-protocol/tests/test_transport_timeouts.py @@ -0,0 +1,146 @@ +"""Exercise HTTPX's TCP, TLS and read timers against a loopback peer.""" + +import asyncio +import sys +from contextlib import asynccontextmanager +from textwrap import dedent + +import anyio +import httpx +import pytest + +from agentenv_protocol import client + + +_CARD = {"capabilities": {"extensions": [{"uri": "urn:example:setup", "params": {"endpoint": "/setup"}}]}} + + +async def call(url, timeout): + with client.retry_extension_connections(): + return await client.invoke_extension(url, _CARD, "urn:example:setup", {}, timeout=timeout) + + +@asynccontextmanager +async def listen(handler): + writers, tasks = [], [] + + def accept(reader, writer): + writers.append(writer) + tasks.append(asyncio.create_task(handler(reader, writer))) + + async with await asyncio.start_server(accept, "127.0.0.1", 0) as server: + try: + yield f"127.0.0.1:{server.sockets[0].getsockname()[1]}" + finally: + for writer in writers: + writer.close() + await asyncio.gather(*tasks) + + +@pytest.mark.asyncio +async def test_asyncio_extension_without_sniffio(monkeypatch): + monkeypatch.setenv("no_proxy", "*") + probe = dedent(""" + import asyncio + import sys + + sys.modules["sniffio"] = None + try: + import anyio + import httpx + except ModuleNotFoundError as exc: + if exc.name == "sniffio": + sys.exit(77) + raise + + from agentenv_protocol import client + card = {"capabilities": {"extensions": [{"uri": "urn:example:setup", "params": {"endpoint": "/setup"}}]}} + with client.retry_extension_connections(): + result = asyncio.run(client.invoke_extension(sys.argv[1], card, "urn:example:setup", {}, timeout=3)) + assert result == {"name": "items"} + """) + + async def reply(reader, writer): + await reader.readuntil(b"\r\n\r\n") + writer.write(b'HTTP/1.1 200 OK\r\nContent-Length: 16\r\n\r\n{"name":"items"}') + await writer.drain() + + async with listen(reply) as address: + child = await asyncio.create_subprocess_exec(sys.executable, "-c", probe, f"http://{address}", + stderr=asyncio.subprocess.PIPE) + _, stderr = await child.communicate() + if child.returncode == 77: + pytest.skip("the installed AnyIO or HTTPX version requires sniffio") + assert child.returncode == 0, stderr.decode() + + +@pytest.mark.asyncio +async def test_stalled_tcp_connect_leaves_time_to_retry(monkeypatch): + monkeypatch.setenv("no_proxy", "*") + connect_tcp = anyio.connect_tcp + attempts, requests = [], [] + + async def stall_first(*args, **kwargs): + attempts.append(None) + if len(attempts) == 1: + await asyncio.Event().wait() + return await connect_tcp(*args, **kwargs) + + async def reply(reader, writer): + requests.append(await reader.readuntil(b"\r\n\r\n")) + writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}") + await writer.drain() + + monkeypatch.setattr(anyio, "connect_tcp", stall_first) + async with listen(reply) as address: + assert await call(f"http://{address}", timeout=2) == {} + assert len(attempts) == 2 and len(requests) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cancel", [False, True]) +async def test_stalled_tls_closes_each_connection(monkeypatch, cancel): + monkeypatch.setenv("no_proxy", "*") + hellos, closed = asyncio.Event(), [] + + async def hold(reader, writer): + peer_closed = asyncio.Event() + closed.append(peer_closed) + assert await reader.read(4096) + hellos.set() + await reader.read() + peer_closed.set() + + async with listen(hold) as address: + task = asyncio.create_task(call(f"https://{address}", timeout=1.5)) + if cancel: + await asyncio.wait_for(hellos.wait(), 2) + task.cancel() + with pytest.raises(asyncio.CancelledError if cancel else httpx.ConnectTimeout): + await task + assert len(closed) == (1 if cancel else 2) + await asyncio.wait_for(asyncio.gather(*(peer.wait() for peer in closed)), 1) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("progress", [False, True]) +async def test_buffered_reply_keeps_its_read_inactivity_timeout(monkeypatch, progress): + monkeypatch.setenv("no_proxy", "*") + + async def reply(reader, writer): + await reader.readuntil(b"\r\n\r\n") + writer.write(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n{") + if progress: + for piece in (b" ", b" ", b" ", b"}"): + await asyncio.sleep(0.1) + writer.write(piece) + await writer.drain() + else: + await reader.read() + + async with listen(reply) as address: + if progress: + assert await call(f"http://{address}", timeout=0.3) == {} + else: + with pytest.raises(httpx.ReadTimeout): + await call(f"http://{address}", timeout=0.3) diff --git a/pyproject.toml b/pyproject.toml index c30a8adf7..5183b517e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -172,6 +172,7 @@ dev = [ "websockets>=15", # the gateway's WebSocket relay to a website; outside its container only the tests import it "pytest>=9.0", "pytest-asyncio>=0.23.0", + "trio>=0.24", # the protocol's native Trio client tests "pytest-dependency>=0.6.0", "pytest-socket>=0.7.0", "pytest-timeout>=2.3.0", diff --git a/src/agent_env/task_step/task_steps/modify_env_tool_access.py b/src/agent_env/task_step/task_steps/modify_env_tool_access.py index f45e5db09..37448d804 100644 --- a/src/agent_env/task_step/task_steps/modify_env_tool_access.py +++ b/src/agent_env/task_step/task_steps/modify_env_tool_access.py @@ -5,6 +5,8 @@ import logging from typing import ClassVar, Optional +from agentenv_protocol import client as protocol_v1 + from agent_env.env.gateway import TOOL_DISABLE_ACTION, TOOL_ENABLE_ACTION from agent_env.env.gateway.constants import EXT_DISABLE_TOOL_URI, EXT_ENABLE_TOOL_URI from agent_env.task_step.context import StepContextError, TaskStepContext @@ -68,7 +70,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: deployed = bound_deployment(context, self.env_id, env_step_id=self.env_step_id, step_id=self.id) if deployed is None: raise StepContextError(f"Env '{self.env_id}' not found in context.deployed_envs") - body = await deployed.invoke(_TOOL_ACCESS_URIS[self.action], self.action, {"role": self.role, "tools": self.tools}) + with protocol_v1.retry_extension_connections(): + body = await deployed.invoke(_TOOL_ACCESS_URIS[self.action], self.action, {"role": self.role, "tools": self.tools}) logger.info(f"{self.action} role={self.role!r} tools={self.tools} on env={self.env_id}: {body}") context.metadata.setdefault("tool_access_changes", []).append({ "step_id": self.id, diff --git a/src/agent_env/task_step/task_steps/set_env_clock_rate.py b/src/agent_env/task_step/task_steps/set_env_clock_rate.py index c969ebbfa..001979659 100644 --- a/src/agent_env/task_step/task_steps/set_env_clock_rate.py +++ b/src/agent_env/task_step/task_steps/set_env_clock_rate.py @@ -12,6 +12,7 @@ from typing import ClassVar, Optional import httpx +from agentenv_protocol import client as protocol_v1 from agent_env.entity.refs import EntityRef from agent_env.env.gateway.constants import EXT_CLOCK_URI @@ -80,9 +81,10 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: if deployed is None: raise StepContextError(f"Env '{self.env_id}' not found in context.deployed_envs") try: - state = await deployed.invoke(EXT_CLOCK_URI, "set_rate", - {"virtual_seconds_per_real_second": self.virtual_seconds_per_real_second}, - timeout=self.timeout_seconds) + with protocol_v1.retry_extension_connections(): + state = await deployed.invoke(EXT_CLOCK_URI, "set_rate", + {"virtual_seconds_per_real_second": self.virtual_seconds_per_real_second}, + timeout=self.timeout_seconds) except httpx.HTTPStatusError as e: raise RuntimeError(f"clock rate change failed (HTTP {e.response.status_code}): {_gateway_error(e.response)}") from e context.metadata.setdefault("clock_configurations", []).append({ diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index f14876926..046f5f75b 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -157,10 +157,11 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: if deployed is None: raise StepContextError(f"Env '{self.env_id}' not found in context.deployed_envs") try: - await deployed.invoke(EXT_CLOCK_URI, "set_time", - {"virtual_time": self.armed_virtual_time, "virtual_seconds_per_real_second": self.virtual_seconds_per_real_second, - **({"time_zone": self.timezone} if self.timezone else {})}, - timeout=self.timeout_seconds) + with protocol_v1.retry_extension_connections(): + await deployed.invoke(EXT_CLOCK_URI, "set_time", + {"virtual_time": self.armed_virtual_time, "virtual_seconds_per_real_second": self.virtual_seconds_per_real_second, + **({"time_zone": self.timezone} if self.timezone else {})}, + timeout=self.timeout_seconds) except httpx.HTTPStatusError as e: raise RuntimeError(f"clock arm failed (HTTP {e.response.status_code}): {e.response.text}") from e except EnvCapabilityUnsupported as e: @@ -170,7 +171,8 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: raise StepContextError(f"env '{self.env_id}' has no clock to arm: its card offers no {EXT_CLOCK_URI} " "set_time, which a gateway serves. A computer deployed alone follows no clock; " "deploy it in a multi env, whose gateway it follows") from e - state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=self.timeout_seconds) + with protocol_v1.retry_extension_connections(): + state = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=self.timeout_seconds) env_get_time_url = state.get("env_get_time_url") if self.timezone is not None and state.get("time_zone") != self.timezone: logger.warning(f"sync_env_clock env={self.env_id}: its gateway's clock didn't take time zone " @@ -244,8 +246,7 @@ async def _sync_one(self, deployed, gateway_url: str, service: str, env_get_time raise StepContextError(f"{service} advertises {EXT_CLOCK_URI} but its sync_time takes no timezone; " f"rebuild its image or drop timezone={self.timezone!r} from the task") params["timezone"] = self.timezone - result = await protocol_v1.invoke_extension(base_url, card, EXT_CLOCK_URI, - params=params, - timeout=self.timeout_seconds, - headers=deployed.control_headers) + with protocol_v1.retry_extension_connections(): + result = await protocol_v1.invoke_extension(base_url, card, EXT_CLOCK_URI, params=params, + timeout=self.timeout_seconds, headers=deployed.control_headers) return {"synced": True, "result": result} diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index a615101bc..aef9a8437 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -8,6 +8,7 @@ from agent_env.env.gateway.constants import EXT_CLOCK_URI, WELL_KNOWN_PATH from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_steps import sync_env_clock as mod +from agent_env.task_step.task_steps.set_env_clock_rate import SetEnvClockRateTaskStep from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep, resolve_virtual_time T0 = "2026-01-01T00:00:00Z" @@ -94,7 +95,7 @@ async def test_sync_one_skips_or_raises_for_a_child_env_missing_from_the_stored_ @pytest.mark.asyncio async def test_execute_syncs_each_child_env_through_the_stored_card(monkeypatch): - sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}, fail_first_connection=True) monkeypatch.setattr("agent_env.env.env.Env.get", lambda *a, **k: SimpleNamespace(environment_name="email")) context = TaskStepContext(deployed_envs=[_carded(await _composed_card({"mcp-email": [_CLOCK_EXT]}))]) @@ -108,6 +109,15 @@ async def test_execute_syncs_each_child_env_through_the_stored_card(monkeypatch) assert [s["service"] for s in context.metadata["clock_configurations"][0]["synced"]] == ["email"] +@pytest.mark.asyncio +async def test_clock_rate_change_retries_before_sending(monkeypatch): + sent = _mock_http(monkeypatch, fail_first_connection=True) + context = TaskStepContext(deployed_envs=[_carded(await _composed_card({}))]) + step = SetEnvClockRateTaskStep(id="rate", version=None, env_id="e1", virtual_seconds_per_real_second=2) + await step.execute(context) + assert [(r.method, str(r.url)) for r in sent] == [("PUT", f"{_CARD}/clock/set-rate")] + + @pytest.mark.asyncio async def test_execute_keeps_the_arm_failure_message(monkeypatch): _mock_http(monkeypatch, set_time_status=409) @@ -286,13 +296,17 @@ def _carded(card: dict) -> DeployedEnv: sandbox_id="sb-1", environment_card_url=f"{_CARD}{WELL_KNOWN_PATH}", environment_card=card) -def _mock_http(monkeypatch, state: dict | None = None, set_time_status: int = 200): +def _mock_http(monkeypatch, state: dict | None = None, set_time_status: int = 200, *, fail_first_connection: bool = False): """Record every request: `/clock/state` answers `state`, `/clock/set-time` `set_time_status`, anything else an empty object.""" import httpx sent, real = [], httpx.AsyncClient + refused = set() def handle(request: httpx.Request) -> httpx.Response: + if fail_first_connection and request.url.path not in refused: + refused.add(request.url.path) + raise httpx.ConnectTimeout("connection timed out before sending") sent.append(request) if request.url.path.endswith("/clock/set-time"): return httpx.Response(set_time_status, json={}) diff --git a/tst/unit/task_step/test_modify_env_tool_access.py b/tst/unit/task_step/test_modify_env_tool_access.py index 450ef5a66..620884d9f 100644 --- a/tst/unit/task_step/test_modify_env_tool_access.py +++ b/tst/unit/task_step/test_modify_env_tool_access.py @@ -20,7 +20,7 @@ @pytest.mark.asyncio @pytest.mark.parametrize("action", ["disable", "enable"]) async def test_posts_the_action_as_the_card_declares_it_and_records_the_role_state(monkeypatch, action): - sent = _mock_gateway(monkeypatch, {"ok": True, "disabled": ["slack_send"], "allowed": []}) + sent = _mock_gateway(monkeypatch, {"ok": True, "disabled": ["slack_send"], "allowed": []}, fail_first_connection=True) ctx = TaskStepContext(deployed_envs=[_record()], metadata={}) out = await _step(action).execute(ctx) @@ -63,11 +63,15 @@ def _record(extensions: list = GATEWAY_EXTENSIONS) -> DeployedEnv: environment_card={"name": "gw", "capabilities": {"extensions": extensions}}) -def _mock_gateway(monkeypatch, body: dict, status: int = 200) -> list[httpx.Request]: +def _mock_gateway(monkeypatch, body: dict, status: int = 200, *, fail_first_connection: bool = False) -> list[httpx.Request]: """Answer every request the protocol client sends with `body`; return the requests.""" sent, real = [], httpx.AsyncClient def handle(request: httpx.Request) -> httpx.Response: + nonlocal fail_first_connection + if fail_first_connection: + fail_first_connection = False + raise httpx.ConnectError("connection refused before sending") sent.append(request) return httpx.Response(status, json=body) diff --git a/uv.lock b/uv.lock index 82b2adec9..7d705781b 100644 --- a/uv.lock +++ b/uv.lock @@ -135,6 +135,7 @@ dev = [ { name = "tensorlake" }, { name = "tomli-w" }, { name = "transformers" }, + { name = "trio" }, { name = "urllib3" }, { name = "vercel-sandbox" }, { name = "websockets" }, @@ -278,6 +279,7 @@ requires-dist = [ { name = "transformers", marker = "extra == 'skyrl'", specifier = ">=5" }, { name = "transformers", marker = "extra == 'trl'", specifier = ">=5.2" }, { name = "transformers", marker = "extra == 'verl'", specifier = ">=5" }, + { name = "trio", marker = "extra == 'dev'", specifier = ">=0.24" }, { name = "tzdata", specifier = ">=2024.1" }, { name = "urllib3", marker = "extra == 'boat'", specifier = ">=2.1.0,<3" }, { name = "uvicorn", specifier = ">=0.47" }, @@ -332,6 +334,7 @@ dev = [ { name = "pytest-asyncio" }, { name = "python-multipart" }, { name = "regex" }, + { name = "trio" }, { name = "websockets" }, { name = "zstandard" }, ] @@ -376,6 +379,7 @@ requires-dist = [ { name = "regex", marker = "extra == 'agent'", specifier = ">=2023.12.25" }, { name = "regex", marker = "extra == 'dev'", specifier = ">=2023.12.25" }, { name = "starlette", specifier = ">=0.37" }, + { name = "trio", marker = "extra == 'dev'", specifier = ">=0.24" }, { name = "uvicorn", marker = "extra == 'agent'", specifier = ">=0.30" }, { name = "uvicorn", marker = "extra == 'app'", specifier = ">=0.30" }, { name = "uvicorn", marker = "extra == 'computer'", specifier = ">=0.30" }, @@ -4699,6 +4703,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/70/cf/f691388c4a9bc4af7dcc1648c4b40845869908b517d7c0009d005c7d1fa1/orjson-3.13.0-cp315-cp315-win_arm64.whl", hash = "sha256:f5c05a8fee59309f537590a1ff12d3c1009c485e96a50a9ac60dd085c09d0fc0", size = 126260, upload-time = "2026-10-07T14:09:23.928Z" }, ] +[[package]] +name = "outcome" +version = "1.3.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/df/77698abfac98571e65ffeb0c1fba8ffd692ab8458d617a0eed7d9a8d38f2/outcome-1.3.0.post0.tar.gz", hash = "sha256:9dcf02e65f2971b80047b377468e72a268e15c0af3cf1238e6ff14f7f91143b8", size = 21060, upload-time = "2023-10-26T04:26:04.361Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/55/8b/5ab7257531a5d830fc8000c476e63c935488d74609b50f9384a643ec0a62/outcome-1.3.0.post0-py2.py3-none-any.whl", hash = "sha256:e771c5ce06d1415e356078d3bdd68523f284b4ce5419828922b6871e65eda82b", size = 10692, upload-time = "2023-10-26T04:26:02.532Z" }, +] + [[package]] name = "packaging" version = "26.2" @@ -7179,6 +7195,23 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/73/fa/fb638d54bffff44700c8d487608c1f2872823e606fbd043b3c29c93236cf/transformers-5.21.0-py3-none-any.whl", hash = "sha256:8803a8712932aa3441c1e8bb340e66d5e3eca079fe65d9b717ede2f3ead01c79", size = 12978463, upload-time = "2026-10-26T18:17:23.647Z" }, ] +[[package]] +name = "trio" +version = "0.35.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "cffi", marker = "implementation_name != 'pypy' and os_name == 'nt'" }, + { name = "idna" }, + { name = "outcome" }, + { name = "sniffio" }, + { name = "sortedcontainers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9c/e2/1db4e79abb730bbf048c1024a622b0e1e895f5b0e18c59f3f6b3e4b296ef/trio-0.35.0.tar.gz", hash = "sha256:7efb295c78a0ecd1235c5759e620b5da564ca80d2efcb0055423588547248b96", size = 609525, upload-time = "2026-10-31T23:36:55.506Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/c6/77f116686de6b1bb4159ef70d476ef75576ad7819d4eeb783f6efb40f380/trio-0.35.0-py3-none-any.whl", hash = "sha256:9a062a029487c1bdbcc1b2543b729a0bde857ce478b1512c84f391f628e0c5c9", size = 513178, upload-time = "2026-10-31T23:36:53.705Z" }, +] + [[package]] name = "truststore" version = "0.10.5"