From 20f488c2d6aa287ce1f269761e3309ae7b5b3c5c Mon Sep 17 00:00:00 2001 From: morningducke <70541786+morningducke@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:21:30 +0300 Subject: [PATCH 1/7] fix(protocol): retry connection establishment within the request deadline --- packages/agentenv-protocol/README.md | 8 +- packages/agentenv-protocol/pyproject.toml | 1 + .../src/agentenv_protocol/_connect.py | 37 +++ .../src/agentenv_protocol/client.py | 13 +- .../src/agentenv_protocol/tool_client.py | 8 +- .../agentenv-protocol/tests/test_client.py | 134 ++++------ .../tests/test_connect_retries.py | 235 ++++++++++++++++++ .../task_step/test_apply_server_config.py | 36 +-- uv.lock | 3 + 9 files changed, 358 insertions(+), 117 deletions(-) create mode 100644 packages/agentenv-protocol/src/agentenv_protocol/_connect.py create mode 100644 packages/agentenv-protocol/tests/test_connect_retries.py diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 358b6dd40..66ef6960b 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -438,9 +438,11 @@ async with ToolSession(mcp_url=mcp_url, role="alice@example.com") as session: call, and a stateless server has no session to lose, so neither restart raises anything. - `httpx.TransportError` means the connection failed, and `TimeoutError` that a request outlived `timeout` (600 s by default, the gateway's own limit on a tool call). - - `ToolSession` retries nothing. A call that raised may still have run on the server, or may yet run: a request - stalled on a bad link can arrive after the client has given up. So after any failed call the env's state is - unknown; read it back (`data/get`) or end the episode. + - MCP POSTs, data-plane RPCs, card and manifest lookups, and extension calls make up to three attempts to + connect, waiting 0.5 and 1 second after a connection failure. The request timeout covers all attempts, + waits and the reply. A data-plane call that exhausts this total budget raises `httpx.TimeoutException`. + After sending, a failed call may still have run on the server. The client propagates read and write errors + and HTTP error responses. Read the state back with `data/get` or end the episode before trying again. - **Tools:** `list_tools()` returns the tools the role may use as `EnvironmentTool`, the type a card's `capabilities.tools` holds. Each `inputSchema` is the JSON Schema a model API takes as the tool's parameters. diff --git a/packages/agentenv-protocol/pyproject.toml b/packages/agentenv-protocol/pyproject.toml index 5d3ab9717..b6f9882c6 100644 --- a/packages/agentenv-protocol/pyproject.toml +++ b/packages/agentenv-protocol/pyproject.toml @@ -22,6 +22,7 @@ classifiers = [ "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [ + "anyio>=3.6.2", "pydantic>=2.11", "starlette>=0.37", "httpx>=0.27", 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..f137826a0 --- /dev/null +++ b/packages/agentenv-protocol/src/agentenv_protocol/_connect.py @@ -0,0 +1,37 @@ +"""Retry connections before the first request reaches the environment.""" + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any + +import anyio +import httpx + + +@asynccontextmanager +async def open_response(client: httpx.AsyncClient, request: httpx.Request) -> AsyncIterator[httpx.Response]: + for delay in (0.5, 1.0): + try: + response = await client.send(request, stream=True) + break + except (httpx.ConnectError, httpx.ConnectTimeout) as exc: + # HTTPX attaches the failing hop's request. A redirect means the original was sent. + if exc.request is not request or anyio.current_time() + delay >= anyio.current_effective_deadline(): + raise + await anyio.sleep(delay) + else: + response = await client.send(request, stream=True) + try: + yield response + finally: + with anyio.CancelScope(shield=True): + await response.aclose() + + +async def request(client: httpx.AsyncClient, method: str, url: str, *, timeout: float, **kwargs: Any) -> httpx.Response: + outgoing = client.build_request(method, url, timeout=timeout, **kwargs) + with anyio.move_on_after(timeout): + async with open_response(client, outgoing) as response: + await response.aread() + return response + raise httpx.TimeoutException(f"{method} did not finish within {timeout}s", request=outgoing) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/client.py b/packages/agentenv-protocol/src/agentenv_protocol/client.py index 0d76ad4aa..dca790900 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/client.py @@ -11,6 +11,7 @@ import httpx +from . import _connect from .manifest import INTERFACE_MANIFEST_PATH from .transfers import WriteNamespaceGrant 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 @@ -87,7 +88,7 @@ async def _rpc(base_url: str, method: str, params: dict, timeout: int, verify: b request = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params} url = f"{base_url.rstrip('/')}{RPC_PATH}" async with httpx.AsyncClient(verify=verify) as client: - response = await client.post(url, json=request, timeout=timeout, headers=request_headers(url, headers)) + response = await _connect.request(client, "POST", url, json=request, timeout=timeout, headers=request_headers(url, headers)) response.raise_for_status() body = response.json() if "error" in body: @@ -122,7 +123,7 @@ async def get_data( async def get_card(base_url: str, timeout: int = 10, verify: bool = True) -> dict: async with httpx.AsyncClient(verify=verify) as client: - response = await client.get(f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout) + response = await _connect.request(client, "GET", f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout) response.raise_for_status() return response.json() @@ -333,7 +334,7 @@ async def get_interface_manifest(base_url: str, interface: str, endpoint: str = """ url = f"{base_url.rstrip('/')}{endpoint}/{interface}" async with httpx.AsyncClient(verify=verify) as client: - response = await client.get(url, timeout=timeout, headers=request_headers(url, headers)) + response = await _connect.request(client, "GET", url, timeout=timeout, headers=request_headers(url, headers)) response.raise_for_status() return response.json() @@ -360,10 +361,8 @@ 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": - 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) + arguments = {"params": params or {}} if op["method"] == "GET" else {"json": params or {}} + response = await _connect.request(client, op["method"], url, timeout=timeout, headers=sent, **arguments) if response.status_code >= 400: raise ExtensionCallError(response) return response.json() diff --git a/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py b/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py index 77cfab019..c017f19ad 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py @@ -13,6 +13,7 @@ import httpx from pydantic import BaseModel, Field, field_validator +from ._connect import open_response from .tool_context import ROLE_HEADER from .types import PROTOCOL_VERSION, EnvironmentTool @@ -46,7 +47,7 @@ def text(self) -> str: class ToolSession: """One MCP session on an env's ``mcp_url``. Use it on the event loop that opened it, and after any failed call treat - the env's state as unknown: nothing is retried, and a call that raised may still run on the server.""" + the env's state as unknown. A connection can be retried before sending. A call that reached the server may still run.""" def __init__(self, *, mcp_url: str, role: str | None = None, headers: dict[str, str] | None = None, timeout: float = 600.0) -> None: @@ -132,8 +133,9 @@ async def _deadline(self, method: str, exchange: Any) -> Any: raise TimeoutError(f"{method} did not finish within {self.timeout}s") from e async def _exchange(self, message: dict) -> dict: - async with self._open_client().stream("POST", self.mcp_url, json=message, - headers=self._session_headers()) as response: + client = self._open_client() + request = client.build_request("POST", self.mcp_url, json=message, headers=self._session_headers()) + async with open_response(client, request) as response: await self._raise_for_status(response, message["method"]) if "id" not in message: return {} diff --git a/packages/agentenv-protocol/tests/test_client.py b/packages/agentenv-protocol/tests/test_client.py index 3c6d3c570..5e13b7ad8 100644 --- a/packages/agentenv-protocol/tests/test_client.py +++ b/packages/agentenv-protocol/tests/test_client.py @@ -2,8 +2,10 @@ from __future__ import annotations +import json import re -from unittest.mock import AsyncMock, MagicMock, patch +from contextlib import contextmanager +from unittest.mock import patch import httpx import pytest @@ -13,108 +15,88 @@ _BASE = "http://gw/svc/mcp-items" -def _resp(json_value, status: int = 200) -> MagicMock: - r = MagicMock() - r.status_code = status - r.json = MagicMock(return_value=json_value) - if status >= 400: - err = httpx.HTTPStatusError("err", request=MagicMock(), response=MagicMock(status_code=status)) - r.raise_for_status = MagicMock(side_effect=err) - else: - r.raise_for_status = MagicMock() - return r +@contextmanager +def _serve(response: httpx.Response | httpx.ConnectError): + requests = [] + def handle(request): + requests.append(request) + if isinstance(response, httpx.ConnectError): + raise response + return response -def _client(resp: MagicMock) -> MagicMock: - client = MagicMock() - client.post = AsyncMock(return_value=resp) - client.get = AsyncMock(return_value=resp) - client.request = AsyncMock(return_value=resp) - client.__aenter__ = AsyncMock(return_value=client) - client.__aexit__ = AsyncMock(return_value=False) - return client - - -def _patch(client: MagicMock): - return patch("agentenv_protocol.client.httpx.AsyncClient", return_value=client) + transport = httpx.MockTransport(handle) + client = httpx.AsyncClient(transport=transport) + with patch("agentenv_protocol.client.httpx.AsyncClient", return_value=client): + yield requests @pytest.mark.asyncio async def test_reset_data_posts_rpc(): - client = _client(_resp({"jsonrpc": "2.0", "id": 1, "result": {}})) - with _patch(client): + with _serve(httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {}})) as requests: assert (await protocol_v1.reset_data(_BASE)).model_dump() == {} - assert client.post.call_args.args[0] == f"{_BASE}/agentenv" - assert client.post.call_args.kwargs["json"]["method"] == "data/reset" + assert [(r.method, str(r.url)) for r in requests] == [("POST", f"{_BASE}/agentenv")] + assert json.loads(requests[0].content)["method"] == "data/reset" @pytest.mark.asyncio async def test_add_data_posts_parts(): - client = _client(_resp({"jsonrpc": "2.0", "id": 1, "result": {}})) - with _patch(client): + with _serve(httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {}})) as requests: assert (await protocol_v1.add_data(_BASE, [DataPart(data={"items": ["a"]})])).model_dump() == {} - sent = client.post.call_args.kwargs["json"] - assert client.post.call_args.args[0] == f"{_BASE}/agentenv" + sent = json.loads(requests[0].content) + assert [(r.method, str(r.url)) for r in requests] == [("POST", f"{_BASE}/agentenv")] assert sent["method"] == "data/add" assert sent["params"] == {"parts": [{"kind": "data", "data": {"items": ["a"]}}]} @pytest.mark.asyncio async def test_get_data_posts_rpc(): - client = _client(_resp({"jsonrpc": "2.0", "id": 1, "result": {"parts": [{"kind": "data", "data": {"items": []}}]}})) - with _patch(client): + with _serve(httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {"parts": [{"kind": "data", "data": {"items": []}}]}})) as requests: assert (await protocol_v1.get_data(_BASE)).parts[0].data == {"items": []} - assert client.post.call_args.args[0] == f"{_BASE}/agentenv" - assert client.post.call_args.kwargs["json"]["method"] == "data/get" + assert [(r.method, str(r.url)) for r in requests] == [("POST", f"{_BASE}/agentenv")] + assert json.loads(requests[0].content)["method"] == "data/get" @pytest.mark.asyncio async def test_get_card_gets_well_known(): - client = _client(_resp({"name": "items"})) - with _patch(client): + with _serve(httpx.Response(200, json={"name": "items"})) as requests: assert await protocol_v1.get_card(_BASE) == {"name": "items"} - assert client.get.call_args.args[0] == f"{_BASE}/.well-known/agent-env.json" + assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/.well-known/agent-env.json")] @pytest.mark.asyncio async def test_rpc_and_card_strip_trailing_slashes_from_base_url(): base_with_slash = f"{_BASE}/" - client = _client(_resp({"jsonrpc": "2.0", "id": 1, "result": {}})) - with _patch(client): + with _serve(httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {}})) as requests: await protocol_v1.reset_data(base_with_slash) - assert client.post.call_args.args[0] == f"{_BASE}/agentenv" + assert [(r.method, str(r.url)) for r in requests] == [("POST", f"{_BASE}/agentenv")] - client = _client(_resp({"name": "items"})) - with _patch(client): + with _serve(httpx.Response(200, json={"name": "items"})) as requests: await protocol_v1.get_card(base_with_slash) - assert client.get.call_args.args[0] == f"{_BASE}/.well-known/agent-env.json" + assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/.well-known/agent-env.json")] @pytest.mark.asyncio async def test_supports_v1_true_on_card(): - with _patch(_client(_resp({"name": "items"}))): + with _serve(httpx.Response(200, json={"name": "items"})): assert await protocol_v1.supports_v1(_BASE) is True @pytest.mark.asyncio async def test_supports_v1_false_on_404(): - with _patch(_client(_resp(None, status=404))): + with _serve(httpx.Response(404)): assert await protocol_v1.supports_v1(_BASE) is False @pytest.mark.asyncio async def test_supports_v1_false_on_500(): - with _patch(_client(_resp(None, status=500))): + with _serve(httpx.Response(500)): assert await protocol_v1.supports_v1(_BASE) is False @pytest.mark.asyncio async def test_supports_v1_false_on_connect_error(): - client = MagicMock() - client.get = AsyncMock(side_effect=httpx.ConnectError("boom")) - client.__aenter__ = AsyncMock(return_value=client) - client.__aexit__ = AsyncMock(return_value=False) - with _patch(client): + with _serve(httpx.ConnectError("boom")): assert await protocol_v1.supports_v1(_BASE) is False @@ -288,29 +270,26 @@ def test_find_extension_ignores_children(): @pytest.mark.asyncio async def test_invoke_extension_posts_to_advertised_endpoint(): - client = _client(_resp({"tool_name": "list_items", "error_rate": 0.75})) - with _patch(client): + with _serve(httpx.Response(200, json={"tool_name": "list_items", "error_rate": 0.75})) as requests: result = await protocol_v1.invoke_extension( _BASE, _CARD_SET_ERRORS, "urn:agentenv:set-errors/v1", {"tool_name": "list_items", "error_rate": 0.75}, ) assert result == {"tool_name": "list_items", "error_rate": 0.75} - args, kwargs = client.request.call_args - assert args[0] == "POST" and args[1] == f"{_BASE}/agentenv/ext/set_errors" - assert kwargs["json"] == {"tool_name": "list_items", "error_rate": 0.75} + request, = requests + assert (request.method, str(request.url)) == ("POST", f"{_BASE}/agentenv/ext/set_errors") + assert json.loads(request.content) == {"tool_name": "list_items", "error_rate": 0.75} @pytest.mark.asyncio async def test_invoke_extension_strips_trailing_slashes_from_base_url(): base_with_slash = f"{_BASE}/" - client = _client(_resp({"tool_name": "list_items", "error_rate": 0.75})) - with _patch(client): + with _serve(httpx.Response(200, json={"tool_name": "list_items", "error_rate": 0.75})) as requests: await protocol_v1.invoke_extension( base_with_slash, _CARD_SET_ERRORS, "urn:agentenv:set-errors/v1", {"tool_name": "list_items", "error_rate": 0.75}, ) - args, _ = client.request.call_args - assert args[1] == f"{_BASE}/agentenv/ext/set_errors" + assert [str(r.url) for r in requests] == [f"{_BASE}/agentenv/ext/set_errors"] @pytest.mark.asyncio @@ -319,11 +298,10 @@ async def test_invoke_extension_get_uses_query_params(): "uri": "urn:agentenv:ping/v1", "params": {"endpoint": "/agentenv/ext/ping", "methods": {"ping": {"method": "GET", "request": {}}}}, }]}} - client = _client(_resp({"pong": True})) - with _patch(client): + with _serve(httpx.Response(200, json={"pong": True})) as requests: result = await protocol_v1.invoke_extension(_BASE, card, "urn:agentenv:ping/v1") assert result == {"pong": True} - assert client.get.call_args.args[0] == f"{_BASE}/agentenv/ext/ping" + assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/agentenv/ext/ping")] def _error_response(status: int, **kwargs) -> httpx.Response: @@ -343,7 +321,7 @@ def _error_response(status: int, **kwargs) -> httpx.Response: (_error_response(404, json=["not", "an", "object"]), (None, "Not Found", False, "unknown", None)), ]) async def test_invoke_extension_raises_the_error_fields_it_was_sent(response, fields): - with _patch(_client(response)), pytest.raises(ExtensionCallError) as raised: + with _serve(response), pytest.raises(ExtensionCallError) as raised: await protocol_v1.invoke_extension(_BASE, _CARD_SET_ERRORS, "urn:agentenv:set-errors/v1", {}) error = raised.value assert (error.code, error.detail, error.retryable, error.applied, error.hint) == fields @@ -398,41 +376,35 @@ def test_find_extension_method_unknown_method_or_uri_returns_none(): @pytest.mark.asyncio async def test_invoke_extension_calls_the_named_method(): - client = _client(_resp({"virtual_time": "2026-01-01T00:00:00Z"})) - with _patch(client): + with _serve(httpx.Response(200, json={"virtual_time": "2026-01-01T00:00:00Z"})) as requests: await protocol_v1.invoke_extension( _BASE, _CARD_CLOCK, "urn:agentenv:clock/v1", {"time": "2026-01-01T00:00:00Z"}, method="set_time", ) - args, kwargs = client.request.call_args - assert args[0] == "PUT" and args[1] == f"{_BASE}/clock/set-time" - assert kwargs["json"] == {"time": "2026-01-01T00:00:00Z"} + request, = requests + assert (request.method, str(request.url)) == ("PUT", f"{_BASE}/clock/set-time") + assert json.loads(request.content) == {"time": "2026-01-01T00:00:00Z"} @pytest.mark.asyncio async def test_invoke_extension_named_get_method_uses_query_params(): - client = _client(_resp({"frozen": False})) - with _patch(client): + with _serve(httpx.Response(200, json={"frozen": False})) as requests: assert await protocol_v1.invoke_extension(_BASE, _CARD_CLOCK, "urn:agentenv:clock/v1", method="state") == {"frozen": False} - assert client.get.call_args.args[0] == f"{_BASE}/clock/state" + assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/clock/state")] @pytest.mark.asyncio async def test_invoke_extension_without_a_method_calls_the_first_listed(): - client = _client(_resp({})) - with _patch(client): + with _serve(httpx.Response(200, json={})) as requests: await protocol_v1.invoke_extension(_BASE, _CARD_CLOCK, "urn:agentenv:clock/v1") - assert client.get.call_args.args[0] == f"{_BASE}/clock/time" - client.request.assert_not_called() + assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/clock/time")] @pytest.mark.asyncio async def test_invoke_extension_unknown_method_raises_without_calling(): - client = _client(_resp({})) offered = "does not advertise method 'sync_time' (advertises: get_time, set_time, state)" - with _patch(client), pytest.raises(ValueError, match=re.escape(offered)): + with _serve(httpx.Response(200, json={})) as requests, pytest.raises(ValueError, match=re.escape(offered)): await protocol_v1.invoke_extension(_BASE, _CARD_CLOCK, "urn:agentenv:clock/v1", method="sync_time") - client.get.assert_not_called() - client.request.assert_not_called() + assert not requests @pytest.mark.asyncio 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..ead8a4b9b --- /dev/null +++ b/packages/agentenv-protocol/tests/test_connect_retries.py @@ -0,0 +1,235 @@ +"""Drive the protocol clients through HTTPX, injecting failures at the TCP boundary.""" + +import asyncio +import json + +import httpcore +import httpx +import pytest +from anyio.lowlevel import checkpoint +from httpcore._backends.auto import AutoBackend + +from agentenv_protocol import ExtensionCallError, ToolSession, ToolSessionError, client + + +_URL = "http://env.test" +_CARD = {"capabilities": {"extensions": [{"uri": "urn:test", "params": {"methods": { + "set": {"method": "POST", "endpoint": "/set"}, "get": {"method": "GET", "endpoint": "/get"}, +}}}]}} + + +async def call(route, timeout=5): + if route == "rpc": + return await client.add_data(_URL, [], timeout=timeout) + if route == "card": + return await client.get_card(_URL, timeout=timeout) + if route == "manifest": + return await client.get_interface_manifest(_URL, "items", timeout=timeout) + if route == "tool": + async with ToolSession(mcp_url=_URL + "/mcp", timeout=timeout) as session: + return await session.call_tool("sample") + return await client.invoke_extension(_URL, _CARD, "urn:test", {"value": 1}, method=route, timeout=timeout) + + +class Wire: + def __init__(self): + self.attempts = 0 + self.requests = [] + self.closed = 0 + self.on_connect = None + self.read_error = self.write_error = None + self.status = 200 + self.redirect = False + + async def connect(self, host): + self.attempts += 1 + if self.on_connect: + await self.on_connect(self.attempts) + if host == "redirect.test": + raise httpcore.ConnectError("redirect target unavailable") + return Stream(self) + + +class Stream(httpcore.AsyncMockStream): + def __init__(self, wire): + super().__init__([]) + self.wire = wire + self.data = bytearray() + + async def write(self, buffer, timeout=None): + self.data.extend(buffer) + if self.wire.write_error: + raise self.wire.write_error("interrupted write") + + async def read(self, max_bytes, timeout=None): + headers, body = self.data.split(b"\r\n\r\n", 1) + message = json.loads(body or b"{}") + path = headers.split(b" ", 2)[1].decode() + method = message.get("method", "") + self.wire.requests.append((path, method)) + if self.wire.read_error: + raise self.wire.read_error("interrupted read") + if self.wire.redirect: + return b"HTTP/1.1 307 Temporary Redirect\r\nLocation: http://redirect.test/mcp\r\nContent-Length: 0\r\n\r\n" + data = json.dumps({"jsonrpc": "2.0", "id": message.get("id"), "result": {}}).encode() + status = self.wire.status + if method == "notifications/initialized" and status == 200: + status, data = 202, b"" + return (f"HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {len(data)}\r\n" + "Connection: close\r\n\r\n").encode() + data + + async def aclose(self): + self.wire.closed += 1 + await super().aclose() + + +@pytest.fixture +def wire(monkeypatch): + wire = Wire() + monkeypatch.setenv("no_proxy", "*") + + async def connect_tcp(self, host, **kwargs): + return await wire.connect(host) + + monkeypatch.setattr(AutoBackend, "connect_tcp", connect_tcp) + return wire + + +@pytest.mark.asyncio +@pytest.mark.parametrize("route", ["rpc", "card", "manifest", "set", "get", "tool"]) +async def test_connection_timeout_recovers_before_the_request_is_sent(wire, route): + failed_attempt = 3 if route == "tool" else 1 + + async def fail_once(attempt): + if attempt == failed_attempt: + raise httpcore.ConnectTimeout("before sending") + + wire.on_connect = fail_once + await call(route) + assert wire.attempts == failed_attempt + 1 + assert len(wire.requests) == failed_attempt + assert wire.closed == len(wire.requests) + if route == "tool": + assert [method for _, method in wire.requests] == ["initialize", "notifications/initialized", "tools/call"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error", [httpcore.ConnectError, httpcore.ConnectTimeout]) +async def test_failed_connections_stop_after_three_attempts(wire, error): + started = [] + + async def fail(attempt): + started.append(asyncio.get_running_loop().time()) + raise error(f"attempt {attempt}") + + wire.on_connect = fail + with pytest.raises(getattr(httpx, error.__name__), match="attempt 3") as caught: + await call("rpc") + assert caught.value.request.url.path == "/agentenv" + assert wire.attempts == 3 and wire.requests == [] + assert started[1] - started[0] >= 0.49 + assert started[2] - started[1] >= 0.99 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("route", ["rpc", "card", "manifest", "set", "get", "tool"]) +async def test_retried_call_uses_the_original_deadline(wire, route): + async def connect(attempt): + if attempt == 1: + await asyncio.sleep(0.45) + raise httpcore.ConnectError("first attempt") + await asyncio.sleep(0.65) + + wire.on_connect = connect + with pytest.raises(TimeoutError if route == "tool" else httpx.TimeoutException): + await call(route, timeout=1.4) + assert wire.attempts == 2 and wire.requests == [] + + +@pytest.mark.asyncio +async def test_first_attempt_can_use_up_the_backoff_budget(wire): + async def slow_failure(attempt): + await asyncio.sleep(0.2) + raise httpcore.ConnectError("before sending") + + wire.on_connect = slow_failure + with pytest.raises(httpx.ConnectError, match="before sending"): + await call("rpc", timeout=0.6) + assert wire.attempts == 1 and wire.requests == [] + + +@pytest.mark.asyncio +async def test_cancellation_during_backoff_propagates(wire): + failed = asyncio.Event() + + async def connect(attempt): + failed.set() + raise httpcore.ConnectError("before sending") + + wire.on_connect = connect + task = asyncio.create_task(call("rpc")) + await failed.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert wire.attempts == 1 and wire.requests == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("route", ["rpc", "set", "tool"]) +@pytest.mark.parametrize("failure", ["read", "write", "http"]) +async def test_ambiguous_failures_and_http_responses_are_not_retried(wire, route, failure): + if failure == "read": + wire.read_error, expected = httpcore.ReadTimeout, httpx.ReadTimeout + elif failure == "write": + wire.write_error, expected = httpcore.WriteTimeout, httpx.WriteTimeout + else: + wire.status = 503 + expected = {"rpc": httpx.HTTPStatusError, "set": ExtensionCallError, "tool": ToolSessionError}[route] + with pytest.raises(expected): + await call(route) + assert wire.attempts == 1 + assert wire.closed == 1 + + +@pytest.mark.asyncio +async def test_failure_connecting_to_a_redirect_never_resends_the_original_post(wire): + wire.redirect = True + with pytest.raises(httpx.ConnectError) as caught: + await call("tool") + assert caught.value.request.url.host == "redirect.test" + assert wire.requests == [("/mcp", "initialize")] + assert wire.attempts == 2 and wire.closed == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("route", ["rpc", "tool"]) +async def test_deadline_closes_an_incomplete_response_after_retry(monkeypatch, route): + attempts = 0 + closed = [] + + class Body(httpx.AsyncByteStream): + async def __aiter__(self): + yield b"data: " + await asyncio.sleep(5) + + async def aclose(self): + await checkpoint() + closed.append(True) + + def handle(request): + nonlocal attempts + attempts += 1 + if attempts == 1: + raise httpx.ConnectTimeout("first attempt", request=request) + return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=Body()) + + transport = httpx.MockTransport(handle) + + async def send(self, request): + return await transport.handle_async_request(request) + + monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", send) + with pytest.raises(TimeoutError if route == "tool" else httpx.TimeoutException): + await call(route, timeout=0.7) + assert attempts == 2 and closed == [True] diff --git a/tst/unit/task_step/test_apply_server_config.py b/tst/unit/task_step/test_apply_server_config.py index 9df2a67ec..a04ba2b41 100644 --- a/tst/unit/task_step/test_apply_server_config.py +++ b/tst/unit/task_step/test_apply_server_config.py @@ -99,19 +99,16 @@ async def request(self, method, url, *, json=None, timeout=None, headers=None): self.post_calls.append((url, json)) return _resp(200, url, {"ok": True, "echo": json}) - # invoke_extension uses client.get for GET verbs and client.request otherwise; - # our extensions are POST, so request() handles them. - async def __aenter__(self): - return self - - async def __aexit__(self, *a): - return False - def _patch_httpx(gateway: _MockGateway): - """Patch httpx.AsyncClient(...) so both get_card and invoke_extension talk to - our in-memory gateway. AsyncClient is a context manager, so return the mock.""" - return patch("httpx.AsyncClient", return_value=gateway) + async def handle(request): + url = str(request.url) + if request.method == "GET": + return await gateway.get(url) + return await gateway.request(request.method, url, json=json.loads(request.content)) + + real = httpx.AsyncClient + return patch("httpx.AsyncClient", lambda **kwargs: real(transport=httpx.MockTransport(handle), **kwargs)) @pytest.mark.asyncio @@ -857,20 +854,13 @@ async def test_a_multi_envs_computer_is_configured_at_its_own_address_with_its_o child_envs={"desktop": dataclasses.asdict(computer)}) sent = [] - class Client: - async def request(self, method, url, *, json=None, timeout=None, headers=None): - sent.append((url, headers)) - return _resp(200, url, {"ok": True}) - - async def __aenter__(self): - return self - - async def __aexit__(self, *a): - return False + def handle(request): + sent.append((str(request.url), request.headers.get("Authorization"))) + return httpx.Response(200, json={"ok": True}) step = _step(directives=[{"service": service, "uri": _SET_ERRORS_URI, "args": {"tool_name": "t", "error_rate": 0.5}}]) - with patch("httpx.AsyncClient", return_value=Client()), \ + with patch("httpx.AsyncClient", return_value=httpx.AsyncClient(transport=httpx.MockTransport(handle))), \ patch("agent_env.env.env.Env.get", return_value=SimpleNamespace(mcp_server_envs=[], website_envs=[])): await step.execute(TaskStepContext(deployed_envs=[record])) - assert sent == [("https://desk.example/agentenv/ext/set_errors", computer.control_headers)] + assert sent == [("https://desk.example/agentenv/ext/set_errors", computer.control_headers["Authorization"])] diff --git a/uv.lock b/uv.lock index 82b2adec9..306584b4d 100644 --- a/uv.lock +++ b/uv.lock @@ -292,6 +292,8 @@ name = "agentenv-framework-protocol" version = "0.1.636" source = { editable = "packages/agentenv-protocol" } dependencies = [ + { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13.14'" }, + { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13.14'" }, { name = "httpx" }, { name = "pydantic" }, { name = "starlette" }, @@ -351,6 +353,7 @@ x11 = [ requires-dist = [ { name = "a2a-sdk", extras = ["http-server"], marker = "extra == 'agent'", specifier = ">=0.3.26,<0.4" }, { name = "a2a-sdk", extras = ["http-server"], marker = "extra == 'dev'", specifier = ">=0.3.26,<0.4" }, + { name = "anyio", specifier = ">=3.6.2" }, { name = "av", marker = "extra == 'computer'", specifier = ">=17" }, { name = "av", marker = "extra == 'dev'", specifier = ">=17" }, { name = "brotli", marker = "extra == 'app'", specifier = ">=1.2" }, From dc5b7e5c2b8852147db6cb486ff3ec002e37b9da Mon Sep 17 00:00:00 2001 From: morningducke <70541786+morningducke@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:41:56 +0300 Subject: [PATCH 2/7] test(protocol): exercise trigger and snapshot callers at the HTTP boundary --- .../task_step/test_prompt_agent_triggers.py | 112 ++++++++++-------- tst/unit/task_step/test_snapshot_env.py | 3 +- 2 files changed, 62 insertions(+), 53 deletions(-) diff --git a/tst/unit/task_step/test_prompt_agent_triggers.py b/tst/unit/task_step/test_prompt_agent_triggers.py index 0d33d5b9a..b87e9eeb4 100644 --- a/tst/unit/task_step/test_prompt_agent_triggers.py +++ b/tst/unit/task_step/test_prompt_agent_triggers.py @@ -41,19 +41,27 @@ def _resp(status: int, body: dict, method: str = "GET") -> httpx.Response: return httpx.Response(status, json=body, request=httpx.Request(method, "http://x")) +def _serve_get(handler): + async def handle(transport, request): + assert request.method == "GET" + return await handler(request) + + return patch.object(httpx.AsyncHTTPTransport, "handle_async_request", handle) + + # ---- _read_env_triggers ----------------------------------------------------- @pytest.mark.asyncio async def test_snapshot_shape_multi_env(): sent = [] - async def fake_get(self, url, timeout, params=None, headers=None): - sent.append((url, params, timeout)) + async def fake_get(request): + sent.append((str(request.url), dict(request.url.params), request.extensions["timeout"]["read"])) return _resp(200, {"triggers": [{"id": "v6-rate", "status": "fired"}, {"id": "v6-accept", "status": "armed"}]}) ctx = _ctx(_env("env-a", "http://gw-a"), _env("env-b", "http://gw-b")) - with patch.object(httpx.AsyncClient, "get", fake_get): + with _serve_get(fake_get): snap = await _step()._read_env_triggers(ctx) assert snap == {"env-a": {"v6-rate": "fired", "v6-accept": "armed"}, @@ -63,11 +71,11 @@ async def fake_get(self, url, timeout, params=None, headers=None): @pytest.mark.asyncio async def test_an_env_whose_card_offers_no_triggers_state_reads_as_empty_with_no_request(): - async def fake_get(self, url, timeout, params=None, headers=None): + async def fake_get(request): raise AssertionError("no request for an env whose card offers no triggers state") ctx = _ctx(_env("env-x", "http://gw-x", EXT_CLOCK_URI)) - with patch.object(httpx.AsyncClient, "get", fake_get): + with _serve_get(fake_get): snap = await _step()._read_env_triggers(ctx) assert snap == {"env-x": {}} @@ -75,11 +83,11 @@ async def fake_get(self, url, timeout, params=None, headers=None): @pytest.mark.asyncio async def test_a_404_from_an_advertised_triggers_state_fails_closed(): - async def fake_get(self, url, timeout, params=None, headers=None): + async def fake_get(request): return _resp(404, {}) ctx = _ctx(_env("env-x", "http://gw-x")) - with patch.object(httpx.AsyncClient, "get", fake_get), \ + with _serve_get(fake_get), \ patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): with pytest.raises(RuntimeError, match="fail-closed: could not read /triggers/state for env 'env-x'"): await _step()._read_env_triggers(ctx) @@ -87,28 +95,28 @@ async def fake_get(self, url, timeout, params=None, headers=None): @pytest.mark.asyncio async def test_fail_closed_raises_on_persistent_error(): - async def fake_get(self, url, timeout, params=None, headers=None): + async def fake_get(request): raise httpx.ConnectError("gateway down") ctx = _ctx(_env("env-x", "http://gw-x")) - with patch.object(httpx.AsyncClient, "get", fake_get), \ + with _serve_get(fake_get), \ patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): with pytest.raises(RuntimeError, match="fail-closed: could not read /triggers/state for env 'env-x'"): await _step()._read_env_triggers(ctx) @pytest.mark.asyncio -async def test_retries_then_succeeds(): +async def test_retries_a_failed_trigger_state_read_then_succeeds(): calls = {"n": 0} - async def fake_get(self, url, timeout, params=None, headers=None): + async def fake_get(request): calls["n"] += 1 if calls["n"] == 1: - raise httpx.ConnectError("transient") + raise httpx.ReadTimeout("transient") return _resp(200, {"triggers": [{"id": "t", "status": "fired"}]}) ctx = _ctx(_env("env-x", "http://gw-x")) - with patch.object(httpx.AsyncClient, "get", fake_get), \ + with _serve_get(fake_get), \ patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): snap = await _step()._read_env_triggers(ctx) @@ -119,13 +127,13 @@ async def fake_get(self, url, timeout, params=None, headers=None): async def test_triggers_state_is_read_at_the_stored_cards_address(): sent = [] - async def fake_get(self, url, timeout, params=None, headers=None): - sent.append(url) + async def fake_get(request): + sent.append(str(request.url)) return _resp(200, {"triggers": []}) env = _env("env-x", "http://gw-x") env.environment_card_url = f"https://sandbox.example/sb-1{WELL_KNOWN_PATH}" - with patch.object(httpx.AsyncClient, "get", fake_get): + with _serve_get(fake_get): await _step()._read_env_triggers(_ctx(env)) assert sent == ["https://sandbox.example/sb-1/triggers/state"] @@ -220,8 +228,8 @@ def _patched_store(store=None, *, key_prefix=""): async def test_capture_uploads_state_and_records_summary(): calls = {"n": 0} - async def fake_get(self, url, timeout, params=None, headers=None): - if url.endswith("/clock/state"): + async def fake_get(request): + if request.url.path.endswith("/clock/state"): return _resp(200, _CLOCK) calls["n"] += 1 return _resp(200, _STATE) @@ -233,7 +241,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) assert len(store.puts) == 1 @@ -256,8 +264,8 @@ async def fake_get(self, url, timeout, params=None, headers=None): @pytest.mark.asyncio async def test_capture_is_kept_under_the_fixture_prefix(): - async def fake_get(self, url, timeout, params=None, headers=None): - return _resp(200, _CLOCK if url.endswith("/clock/state") else _STATE) + async def fake_get(request): + return _resp(200, _CLOCK if request.url.path.endswith("/clock/state") else _STATE) ctx = TaskStepContext( deployed_envs=[_env("env-a", "http://gw-a")], deployed_agents=[], instance_id="inst-1", @@ -265,7 +273,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store(key_prefix="fx/") - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) assert store.puts[0]["key"].startswith("fx/env_trigger_state/instance_id=inst-1/env-a-") @@ -274,8 +282,8 @@ async def fake_get(self, url, timeout, params=None, headers=None): @pytest.mark.asyncio async def test_capture_records_clock_context_and_per_trigger_detail(): """A recurrence reads "armed" forever, so only fire_count shows it fired.""" - async def fake_get(self, url, timeout, params=None, headers=None): - return _resp(200, _CLOCK if url.endswith("/clock/state") else _CLOCK_STATE) + async def fake_get(request): + return _resp(200, _CLOCK if request.url.path.endswith("/clock/state") else _CLOCK_STATE) ctx = TaskStepContext( deployed_envs=[_env("env-a", "http://gw-a")], deployed_agents=[], instance_id="inst-1", @@ -283,7 +291,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["beat"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) import json as _json @@ -313,8 +321,8 @@ async def test_capture_distinguishes_a_failed_coupling_from_one_that_never_fired "failure_count": 2, "last_failure_at": "2026-06-01T12:00:00Z"}, ]} - async def fake_get(self, url, timeout, params=None, headers=None): - return _resp(200, _CLOCK if url.endswith("/clock/state") else failed) + async def fake_get(request): + return _resp(200, _CLOCK if request.url.path.endswith("/clock/state") else failed) ctx = TaskStepContext( deployed_envs=[_env("env-a", "http://gw-a")], deployed_agents=[], instance_id="inst-1", @@ -323,7 +331,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) rows = ctx.metadata["env_trigger_state"]["env-a"]["triggers"] @@ -343,8 +351,8 @@ async def test_capture_does_not_wait_on_a_firing_recurring_clock_trigger(): "status": "firing", "fire_count": 3, "next_mark": "2026-06-03T00:00:00Z"}]} calls = {"n": 0} - async def fake_get(self, url, timeout, params=None, headers=None): - if url.endswith("/clock/state"): + async def fake_get(request): + if request.url.path.endswith("/clock/state"): return _resp(200, _CLOCK) calls["n"] += 1 return _resp(200, firing) @@ -355,7 +363,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["beat"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch, \ + with _serve_get(fake_get), cfg_patch, \ patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): await _capture_step()._persist_env_trigger_state(ctx) @@ -366,8 +374,8 @@ async def fake_get(self, url, timeout, params=None, headers=None): @pytest.mark.asyncio async def test_capture_tolerates_a_gateway_without_clock_state(): """An unreachable clock state: capture still succeeds, clock recorded as None.""" - async def fake_get(self, url, timeout, params=None, headers=None): - if url.endswith("/clock/state"): + async def fake_get(request): + if request.url.path.endswith("/clock/state"): raise httpx.ConnectError("no clock route") return _resp(200, _STATE) @@ -377,7 +385,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) import json as _json @@ -397,8 +405,8 @@ async def fake_get(self, url, timeout, params=None, headers=None): async def test_capture_records_no_clock_with_no_request_when_the_card_offers_no_clock_state(): sent = [] - async def fake_get(self, url, timeout, params=None, headers=None): - sent.append(url) + async def fake_get(request): + sent.append(str(request.url)) return _resp(200, _STATE) ctx = TaskStepContext( @@ -407,7 +415,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) import json as _json @@ -419,9 +427,9 @@ async def fake_get(self, url, timeout, params=None, headers=None): async def test_capture_reads_triggers_and_clock_at_the_stored_cards_address(): sent = [] - async def fake_get(self, url, timeout, params=None, headers=None): - sent.append((url, timeout)) - return _resp(200, _CLOCK if url.endswith("/clock/state") else _STATE) + async def fake_get(request): + sent.append((str(request.url), request.extensions["timeout"]["read"])) + return _resp(200, _CLOCK if request.url.path.endswith("/clock/state") else _STATE) env = _env("env-a", "http://gw-a") env.environment_card_url = f"https://sandbox.example/sb-1{WELL_KNOWN_PATH}" @@ -431,7 +439,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) assert sent == [("https://sandbox.example/sb-1/triggers/state", 15), ("https://sandbox.example/sb-1/clock/state", 5)] @@ -488,13 +496,13 @@ def test_settle_poll_does_not_wait_out_a_delay_or_working_hours(): async def test_capture_noop_without_registrations(): calls = {"n": 0} - async def fake_get(self, url, timeout, params=None, headers=None): + async def fake_get(request): calls["n"] += 1 return _resp(200, _STATE) ctx = _ctx(_env("env-a", "http://gw-a")) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) assert calls["n"] == 0 and store.puts == [] and "env_trigger_state" not in ctx.metadata @@ -502,7 +510,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): @pytest.mark.asyncio async def test_capture_fail_open_records_error(): - async def fake_get(self, url, timeout, params=None, headers=None): + async def fake_get(request): raise httpx.ConnectError("gateway gone") ctx = TaskStepContext( @@ -511,7 +519,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch, \ + with _serve_get(fake_get), cfg_patch, \ patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): await _capture_step()._persist_env_trigger_state(ctx) @@ -526,8 +534,8 @@ async def test_capture_grace_polls_until_settled(): responses = [firing, _STATE] calls = {"n": 0} - async def fake_get(self, url, timeout, params=None, headers=None): - if url.endswith("/clock/state"): + async def fake_get(request): + if request.url.path.endswith("/clock/state"): return _resp(200, _CLOCK) body = responses[min(calls["n"], len(responses) - 1)] calls["n"] += 1 @@ -539,7 +547,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch, \ + with _serve_get(fake_get), cfg_patch, \ patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): await _capture_step()._persist_env_trigger_state(ctx) @@ -549,7 +557,7 @@ async def fake_get(self, url, timeout, params=None, headers=None): @pytest.mark.asyncio async def test_capture_budget_bounds_total_time(): - async def hanging_get(self, url, timeout): + async def hanging_get(request): await asyncio.sleep(999) ctx = TaskStepContext( @@ -560,7 +568,7 @@ async def hanging_get(self, url, timeout): {"step_id": "reg-2", "env_id": "env-b", "added": ["t2"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with patch.object(httpx.AsyncClient, "get", hanging_get), cfg_patch, \ + with _serve_get(hanging_get), cfg_patch, \ patch.object(PromptAgentTaskStep, "_CAPTURE_BUDGET_SECONDS", 0.05): await _capture_step()._persist_env_trigger_state(ctx) @@ -572,7 +580,7 @@ async def hanging_get(self, url, timeout): @pytest.mark.asyncio async def test_capture_put_failure_keeps_inline_summary(): - async def fake_get(self, url, timeout, params=None, headers=None): + async def fake_get(request): return _resp(200, _STATE) class _FailingStore(_FakeStore): @@ -585,7 +593,7 @@ def put(self, *args, **kwargs): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) _, cfg_patch = _patched_store(_FailingStore()) - with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: + with _serve_get(fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) entry = ctx.metadata["env_trigger_state"]["env-a"] diff --git a/tst/unit/task_step/test_snapshot_env.py b/tst/unit/task_step/test_snapshot_env.py index cf75fb7ca..cff5e26ab 100644 --- a/tst/unit/task_step/test_snapshot_env.py +++ b/tst/unit/task_step/test_snapshot_env.py @@ -1557,7 +1557,8 @@ async def test_export_of_a_website_whose_card_read_fails_raises_rather_than_skip with pytest.raises(httpx.HTTPError): await SnapshotEnvTaskStep._export_environment_to_file("https://gw-1", "shop", str(tmp_path / "out"), 30, mcp=False) - assert [str(r.url) for r in sent] == [f"https://gw-1/svc/shop{WELL_KNOWN_PATH}"] + attempts = 3 if isinstance(card_response, httpx.ConnectError) else 1 + assert [str(r.url) for r in sent] == [f"https://gw-1/svc/shop{WELL_KNOWN_PATH}"] * attempts @pytest.mark.asyncio From c704deffaba9c44f6680827dbe81bf262a60fc84 Mon Sep 17 00:00:00 2001 From: morningducke <70541786+morningducke@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:54:30 +0300 Subject: [PATCH 3/7] test(protocol): scope mocked trigger delays to the prompt step --- .../task_step/test_prompt_agent_triggers.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/tst/unit/task_step/test_prompt_agent_triggers.py b/tst/unit/task_step/test_prompt_agent_triggers.py index b87e9eeb4..40de8df87 100644 --- a/tst/unit/task_step/test_prompt_agent_triggers.py +++ b/tst/unit/task_step/test_prompt_agent_triggers.py @@ -5,6 +5,7 @@ from __future__ import annotations import asyncio +from types import SimpleNamespace from unittest.mock import AsyncMock, patch import httpx @@ -49,6 +50,12 @@ async def handle(transport, request): return patch.object(httpx.AsyncHTTPTransport, "handle_async_request", handle) +def _skip_prompt_waits(): + prompt_asyncio = SimpleNamespace(**vars(asyncio)) + prompt_asyncio.sleep = AsyncMock() + return patch("agent_env.task_step.task_steps.prompt_agent.asyncio", prompt_asyncio) + + # ---- _read_env_triggers ----------------------------------------------------- @pytest.mark.asyncio @@ -88,7 +95,7 @@ async def fake_get(request): ctx = _ctx(_env("env-x", "http://gw-x")) with _serve_get(fake_get), \ - patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): + _skip_prompt_waits(): with pytest.raises(RuntimeError, match="fail-closed: could not read /triggers/state for env 'env-x'"): await _step()._read_env_triggers(ctx) @@ -100,7 +107,7 @@ async def fake_get(request): ctx = _ctx(_env("env-x", "http://gw-x")) with _serve_get(fake_get), \ - patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): + _skip_prompt_waits(): with pytest.raises(RuntimeError, match="fail-closed: could not read /triggers/state for env 'env-x'"): await _step()._read_env_triggers(ctx) @@ -117,7 +124,7 @@ async def fake_get(request): ctx = _ctx(_env("env-x", "http://gw-x")) with _serve_get(fake_get), \ - patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): + _skip_prompt_waits(): snap = await _step()._read_env_triggers(ctx) assert snap == {"env-x": {"t": "fired"}} and calls["n"] == 2 @@ -364,7 +371,7 @@ async def fake_get(request): store, cfg_patch = _patched_store() with _serve_get(fake_get), cfg_patch, \ - patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): + _skip_prompt_waits(): await _capture_step()._persist_env_trigger_state(ctx) assert calls["n"] == 1, "a recurring clock trigger must not trigger the settle poll" @@ -520,7 +527,7 @@ async def fake_get(request): store, cfg_patch = _patched_store() with _serve_get(fake_get), cfg_patch, \ - patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): + _skip_prompt_waits(): await _capture_step()._persist_env_trigger_state(ctx) entry = ctx.metadata["env_trigger_state"]["env-a"] @@ -548,7 +555,7 @@ async def fake_get(request): store, cfg_patch = _patched_store() with _serve_get(fake_get), cfg_patch, \ - patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): + _skip_prompt_waits(): await _capture_step()._persist_env_trigger_state(ctx) assert calls["n"] == 2 From 97c307d229a9fe4c91a103db86c3b80f5f38e47e Mon Sep 17 00:00:00 2001 From: morningducke <70541786+morningducke@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:14:26 +0300 Subject: [PATCH 4/7] fix(protocol): bound connection attempts and preserve read timeouts --- packages/agentenv-protocol/README.md | 16 ++- packages/agentenv-protocol/pyproject.toml | 2 + .../src/agentenv_protocol/_connect.py | 73 +++++++++++--- .../src/agentenv_protocol/client.py | 32 +++--- .../src/agentenv_protocol/tool_client.py | 6 +- .../tests/test_connect_retries.py | 46 +++++++-- .../tests/test_transport_timeouts.py | 99 +++++++++++++++++++ pyproject.toml | 1 + uv.lock | 35 +++++++ 9 files changed, 269 insertions(+), 41 deletions(-) create mode 100644 packages/agentenv-protocol/tests/test_transport_timeouts.py diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index 66ef6960b..c137aff55 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -218,6 +218,14 @@ 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. +Data-plane RPCs, card and manifest lookups, and extension calls retry TCP or TLS connection failures +before sending the request. Up to three attempts share the connection budget from `timeout`, including +backoffs of 0.5 and 1 second when time permits. After connecting, `timeout` keeps its HTTPX meaning +for each read and write. A transfer can continue while it makes progress. For a wall-clock limit +across retries and the entire reply, pass `total_timeout` in seconds, for example +`await client.add_data(url, parts, timeout=30, total_timeout=120)`. Expiring that limit raises +`httpx.TimeoutException`. Read and write errors retain their HTTPX exception types. + 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 @@ -438,11 +446,9 @@ async with ToolSession(mcp_url=mcp_url, role="alice@example.com") as session: call, and a stateless server has no session to lose, so neither restart raises anything. - `httpx.TransportError` means the connection failed, and `TimeoutError` that a request outlived `timeout` (600 s by default, the gateway's own limit on a tool call). - - MCP POSTs, data-plane RPCs, card and manifest lookups, and extension calls make up to three attempts to - connect, waiting 0.5 and 1 second after a connection failure. The request timeout covers all attempts, - waits and the reply. A data-plane call that exhausts this total budget raises `httpx.TimeoutException`. - After sending, a failed call may still have run on the server. The client propagates read and write errors - and HTTP error responses. Read the state back with `data/get` or end the episode before trying again. + - MCP POSTs use the same connection retries. The session's `timeout` covers attempts, waits and the + reply to each MCP request. After sending, a failed call may still have run on the server. Read the + state back with `data/get` or end the episode before trying again. - **Tools:** `list_tools()` returns the tools the role may use as `EnvironmentTool`, the type a card's `capabilities.tools` holds. Each `inputSchema` is the JSON Schema a model API takes as the tool's parameters. diff --git a/packages/agentenv-protocol/pyproject.toml b/packages/agentenv-protocol/pyproject.toml index b6f9882c6..42d285a36 100644 --- a/packages/agentenv-protocol/pyproject.toml +++ b/packages/agentenv-protocol/pyproject.toml @@ -24,6 +24,7 @@ classifiers = [ dependencies = [ "anyio>=3.6.2", "pydantic>=2.11", + "sniffio>=1.1", "starlette>=0.37", "httpx>=0.27", ] @@ -74,6 +75,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 index f137826a0..4613ff2b8 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/_connect.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/_connect.py @@ -1,37 +1,88 @@ """Retry connections before the first request reaches the environment.""" from collections.abc import AsyncIterator -from contextlib import asynccontextmanager +from contextlib import asynccontextmanager, nullcontext +from importlib import import_module +from math import inf, isfinite from typing import Any import anyio import httpx +import sniffio + + +def _runtime(): + # HTTPX uses native Trio when called from Trio. AnyIO 3's Trio adapter requires older Trio versions. + return import_module("trio") if sniffio.current_async_library() == "trio" else anyio + + +async def _send_attempt(client: httpx.AsyncClient, request: httpx.Request, deadline: float, runtime) -> httpx.Response: + extensions = request.extensions + previous = extensions.get("trace") + stream = None + + async def trace(event, info): + nonlocal deadline, stream + if event.endswith((".connect_tcp.started", ".start_tls.started")) and isfinite(deadline): + # httpcore passes these arguments to each handshake. TCP and TLS share this attempt's budget. + info["timeout"] = max(0, deadline - runtime.current_time()) + 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): + # Cancellation can interrupt TLS before the pool takes ownership of the socket. + with runtime.CancelScope(shield=True): + await stream.aclose() + elif event.endswith(".send_request_headers.started") and info["request"].method != b"CONNECT": + # A followed redirect has its own connection. Only the original hop is eligible for retry. + deadline = inf + if previous is not None: + await previous(event, info) + + request.extensions = {**extensions, "trace": trace} + try: + return await client.send(request, stream=True) + finally: + request.extensions = extensions @asynccontextmanager async def open_response(client: httpx.AsyncClient, request: httpx.Request) -> AsyncIterator[httpx.Response]: - for delay in (0.5, 1.0): + runtime = _runtime() + timeout = request.extensions["timeout"]["connect"] + deadline = runtime.current_effective_deadline() + if timeout is not None: + deadline = min(deadline, runtime.current_time() + timeout) + + delays = (0.5, 1.0, None) + for attempt, delay in enumerate(delays): + now = runtime.current_time() + remaining = max(0, deadline - now) + share = remaining / (len(delays) - attempt) + attempt_deadline = deadline + if delay is not None and share + delay < remaining: + attempt_deadline = now + share try: - response = await client.send(request, stream=True) + response = await _send_attempt(client, request, attempt_deadline, runtime) break except (httpx.ConnectError, httpx.ConnectTimeout) as exc: # HTTPX attaches the failing hop's request. A redirect means the original was sent. - if exc.request is not request or anyio.current_time() + delay >= anyio.current_effective_deadline(): + if exc.request is not request or delay is None or runtime.current_time() + delay >= deadline: + raise + await runtime.sleep(delay) + if runtime.current_time() >= deadline: raise - await anyio.sleep(delay) - else: - response = await client.send(request, stream=True) try: yield response finally: - with anyio.CancelScope(shield=True): + with runtime.CancelScope(shield=True): await response.aclose() -async def request(client: httpx.AsyncClient, method: str, url: str, *, timeout: float, **kwargs: Any) -> httpx.Response: +async def request(client: httpx.AsyncClient, method: str, url: str, *, timeout: float, total_timeout: float | None, + **kwargs: Any) -> httpx.Response: outgoing = client.build_request(method, url, timeout=timeout, **kwargs) - with anyio.move_on_after(timeout): + with (_runtime().move_on_after(total_timeout) if total_timeout is not None else nullcontext()): async with open_response(client, outgoing) as response: await response.aread() return response - raise httpx.TimeoutException(f"{method} did not finish within {timeout}s", request=outgoing) + raise httpx.TimeoutException(f"{method} did not finish within {total_timeout}s", request=outgoing) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/client.py b/packages/agentenv-protocol/src/agentenv_protocol/client.py index dca790900..9ad2af862 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/client.py @@ -84,11 +84,12 @@ def granted_headers(url: str, grants: dict[str | None, dict[str, str]]) -> dict[ async def _rpc(base_url: str, method: str, params: dict, timeout: int, verify: bool, - headers: dict[str, str] | None) -> dict: + headers: dict[str, str] | None, total_timeout: float | None) -> dict: request = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params} url = f"{base_url.rstrip('/')}{RPC_PATH}" async with httpx.AsyncClient(verify=verify) as client: - response = await _connect.request(client, "POST", url, json=request, timeout=timeout, headers=request_headers(url, headers)) + response = await _connect.request(client, "POST", url, json=request, timeout=timeout, total_timeout=total_timeout, + headers=request_headers(url, headers)) response.raise_for_status() body = response.json() if "error" in body: @@ -98,19 +99,19 @@ async def _rpc(base_url: str, method: str, params: dict, timeout: int, verify: b async def reset_data(base_url: str, timeout: int = 30, verify: bool = True, *, - headers: dict[str, str] | None = None) -> ResetDataResponse: - return ResetDataResponse.model_validate(await _rpc(base_url, METHOD_RESET, {}, timeout, verify, headers)) + headers: dict[str, str] | None = None, total_timeout: float | None = None) -> ResetDataResponse: + return ResetDataResponse.model_validate(await _rpc(base_url, METHOD_RESET, {}, timeout, verify, headers, total_timeout)) async def add_data(base_url: str, parts: list[Part], timeout: int = 120, verify: bool = True, *, - headers: dict[str, str] | None = None) -> AddDataResponse: + headers: dict[str, str] | None = None, total_timeout: float | None = None) -> AddDataResponse: params = {"parts": [p.model_dump(mode="json", exclude_none=True) for p in parts]} - return AddDataResponse.model_validate(await _rpc(base_url, METHOD_ADD, params, timeout, verify, headers)) + return AddDataResponse.model_validate(await _rpc(base_url, METHOD_ADD, params, timeout, verify, headers, total_timeout)) async def get_data( base_url: str, timeout: int = 30, verify: bool = True, *, write_namespace: WriteNamespaceGrant | None = None, - paths: list[str] | None = None, headers: dict[str, str] | None = None, + paths: list[str] | None = None, headers: dict[str, str] | None = None, total_timeout: float | None = None, ) -> GetDataResponse: """`data/get`. A server advertising `DATA_OBJECTS_EXTENSION_URI` may be handed `write_namespace` to upload its export under; `uploaded_object_path` reads from the answer where it did. `paths` names what a computer @@ -118,12 +119,13 @@ async def get_data( params = {} if write_namespace is None else {"write_namespace": write_namespace.model_dump(mode="json", exclude_none=True)} if paths is not None: params["paths"] = paths - return GetDataResponse.model_validate(await _rpc(base_url, METHOD_GET, params, timeout, verify, headers)) + return GetDataResponse.model_validate(await _rpc(base_url, METHOD_GET, params, timeout, verify, headers, total_timeout)) -async def get_card(base_url: str, timeout: int = 10, verify: bool = True) -> dict: +async def get_card(base_url: str, timeout: int = 10, verify: bool = True, *, total_timeout: float | None = None) -> dict: async with httpx.AsyncClient(verify=verify) as client: - response = await _connect.request(client, "GET", f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout) + response = await _connect.request(client, "GET", f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout, + total_timeout=total_timeout) response.raise_for_status() return response.json() @@ -323,7 +325,7 @@ def find_child(card: dict, name: str) -> dict | None: async def get_interface_manifest(base_url: str, interface: str, endpoint: str = INTERFACE_MANIFEST_PATH, timeout: int = 30, verify: bool = True, *, - headers: dict[str, str] | None = None): + headers: dict[str, str] | None = None, total_timeout: float | None = None): """Fetch one interface's manifest from a server's manifest index endpoint. ``endpoint`` is the index path — pass the one advertised on the card under @@ -334,13 +336,14 @@ async def get_interface_manifest(base_url: str, interface: str, endpoint: str = """ url = f"{base_url.rstrip('/')}{endpoint}/{interface}" async with httpx.AsyncClient(verify=verify) as client: - response = await _connect.request(client, "GET", url, timeout=timeout, headers=request_headers(url, headers)) + response = await _connect.request(client, "GET", url, timeout=timeout, total_timeout=total_timeout, + headers=request_headers(url, headers)) response.raise_for_status() return response.json() 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): + headers: dict[str, str] | None = None, total_timeout: float | None = None): """Invoke a card extension via its advertised REST endpoint. Reads the endpoint and HTTP verb of the extension method named `method` from the card, so the @@ -362,7 +365,8 @@ async def invoke_extension(base_url: str, card: dict, uri: str, params: dict | N sent = request_headers(url, headers) async with httpx.AsyncClient(verify=verify) as client: arguments = {"params": params or {}} if op["method"] == "GET" else {"json": params or {}} - response = await _connect.request(client, op["method"], url, timeout=timeout, headers=sent, **arguments) + response = await _connect.request(client, op["method"], url, timeout=timeout, total_timeout=total_timeout, + headers=sent, **arguments) if response.status_code >= 400: raise ExtensionCallError(response) return response.json() diff --git a/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py b/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py index c017f19ad..5669a01af 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py @@ -10,6 +10,7 @@ from collections.abc import AsyncIterator from typing import Any +import anyio import httpx from pydantic import BaseModel, Field, field_validator @@ -128,8 +129,9 @@ async def _request(self, method: str, params: dict[str, Any]) -> dict: async def _deadline(self, method: str, exchange: Any) -> Any: try: - return await asyncio.wait_for(exchange, self.timeout) - except asyncio.TimeoutError as e: + with anyio.fail_after(self.timeout): + return await exchange + except TimeoutError as e: raise TimeoutError(f"{method} did not finish within {self.timeout}s") from e async def _exchange(self, message: dict) -> dict: diff --git a/packages/agentenv-protocol/tests/test_connect_retries.py b/packages/agentenv-protocol/tests/test_connect_retries.py index ead8a4b9b..000fe55d4 100644 --- a/packages/agentenv-protocol/tests/test_connect_retries.py +++ b/packages/agentenv-protocol/tests/test_connect_retries.py @@ -6,8 +6,10 @@ import httpcore import httpx import pytest +import trio from anyio.lowlevel import checkpoint from httpcore._backends.auto import AutoBackend +from trio.testing import MockClock from agentenv_protocol import ExtensionCallError, ToolSession, ToolSessionError, client @@ -18,17 +20,22 @@ }}}]}} -async def call(route, timeout=5): +async def call(route, timeout=5, *, total_timeout=None): + budgets = {"timeout": timeout, "total_timeout": total_timeout} if route == "rpc": - return await client.add_data(_URL, [], timeout=timeout) + return await client.add_data(_URL, [], **budgets) + if route == "reset": + return await client.reset_data(_URL, **budgets) + if route == "data": + return await client.get_data(_URL, **budgets) if route == "card": - return await client.get_card(_URL, timeout=timeout) + return await client.get_card(_URL, **budgets) if route == "manifest": - return await client.get_interface_manifest(_URL, "items", timeout=timeout) + return await client.get_interface_manifest(_URL, "items", **budgets) if route == "tool": async with ToolSession(mcp_url=_URL + "/mcp", timeout=timeout) as session: return await session.call_tool("sample") - return await client.invoke_extension(_URL, _CARD, "urn:test", {"value": 1}, method=route, timeout=timeout) + return await client.invoke_extension(_URL, _CARD, "urn:test", {"value": 1}, method=route, **budgets) class Wire: @@ -132,8 +139,8 @@ async def fail(attempt): @pytest.mark.asyncio -@pytest.mark.parametrize("route", ["rpc", "card", "manifest", "set", "get", "tool"]) -async def test_retried_call_uses_the_original_deadline(wire, route): +@pytest.mark.parametrize("route", ["rpc", "reset", "data", "card", "manifest", "set", "get", "tool"]) +async def test_retried_call_uses_the_whole_call_deadline(wire, route): async def connect(attempt): if attempt == 1: await asyncio.sleep(0.45) @@ -142,7 +149,7 @@ async def connect(attempt): wire.on_connect = connect with pytest.raises(TimeoutError if route == "tool" else httpx.TimeoutException): - await call(route, timeout=1.4) + await call(route, timeout=1.4, total_timeout=1.4) assert wire.attempts == 2 and wire.requests == [] @@ -158,6 +165,27 @@ async def slow_failure(attempt): assert wire.attempts == 1 and wire.requests == [] +@pytest.mark.asyncio +async def test_tool_session_preserves_refusal_when_backoff_cannot_fit(wire): + async def refuse(attempt): + raise httpcore.ConnectError("connection refused") + + wire.on_connect = refuse + with pytest.raises(httpx.ConnectError, match="connection refused"): + await call("tool", timeout=0.25) + assert wire.attempts == 1 and wire.requests == [] + + +def test_retry_runs_on_native_trio(wire): + async def fail_once(attempt): + if attempt == 1: + raise httpcore.ConnectError("connection refused") + + wire.on_connect = fail_once + trio.run(call, "card", clock=MockClock(autojump_threshold=0)) + assert wire.attempts == 2 and len(wire.requests) == 1 + + @pytest.mark.asyncio async def test_cancellation_during_backoff_propagates(wire): failed = asyncio.Event() @@ -231,5 +259,5 @@ async def send(self, request): monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", send) with pytest.raises(TimeoutError if route == "tool" else httpx.TimeoutException): - await call(route, timeout=0.7) + await call(route, timeout=0.7, total_timeout=0.7) assert attempts == 2 and closed == [True] 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..3c28f2d94 --- /dev/null +++ b/packages/agentenv-protocol/tests/test_transport_timeouts.py @@ -0,0 +1,99 @@ +"""Exercise HTTPX's TCP, TLS and read timers against a loopback peer.""" + +import asyncio +from contextlib import asynccontextmanager + +import anyio +import httpx +import pytest + +from agentenv_protocol import client + + +@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_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 client.get_card(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: + call = asyncio.create_task(client.get_card(f"https://{address}", timeout=1.5)) + if cancel: + await asyncio.wait_for(hellos.wait(), 2) + call.cancel() + with pytest.raises(asyncio.CancelledError if cancel else httpx.ConnectTimeout): + await call + 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 client.get_card(f"http://{address}", timeout=0.3) == {} + else: + with pytest.raises(httpx.ReadTimeout): + await client.get_card(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/uv.lock b/uv.lock index 306584b4d..d47f8a77d 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" }, @@ -296,6 +298,7 @@ dependencies = [ { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13.14'" }, { name = "httpx" }, { name = "pydantic" }, + { name = "sniffio" }, { name = "starlette" }, ] @@ -334,6 +337,7 @@ dev = [ { name = "pytest-asyncio" }, { name = "python-multipart" }, { name = "regex" }, + { name = "trio" }, { name = "websockets" }, { name = "zstandard" }, ] @@ -378,7 +382,9 @@ requires-dist = [ { name = "python-xlib", marker = "extra == 'x11'", specifier = ">=0.33,<0.34" }, { name = "regex", marker = "extra == 'agent'", specifier = ">=2023.12.25" }, { name = "regex", marker = "extra == 'dev'", specifier = ">=2023.12.25" }, + { name = "sniffio", specifier = ">=1.1" }, { 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" }, @@ -4702,6 +4708,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" @@ -7182,6 +7200,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" From dda2abd57ccde559b4794a4f6237a017d5698ec4 Mon Sep 17 00:00:00 2001 From: morningducke <70541786+morningducke@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:41:24 +0300 Subject: [PATCH 5/7] fix(protocol): support asyncio clients without sniffio --- packages/agentenv-protocol/pyproject.toml | 1 - .../src/agentenv_protocol/_connect.py | 12 +++++-- .../tests/test_transport_timeouts.py | 36 +++++++++++++++++++ uv.lock | 2 -- 4 files changed, 45 insertions(+), 6 deletions(-) diff --git a/packages/agentenv-protocol/pyproject.toml b/packages/agentenv-protocol/pyproject.toml index 42d285a36..48858287a 100644 --- a/packages/agentenv-protocol/pyproject.toml +++ b/packages/agentenv-protocol/pyproject.toml @@ -24,7 +24,6 @@ classifiers = [ dependencies = [ "anyio>=3.6.2", "pydantic>=2.11", - "sniffio>=1.1", "starlette>=0.37", "httpx>=0.27", ] diff --git a/packages/agentenv-protocol/src/agentenv_protocol/_connect.py b/packages/agentenv-protocol/src/agentenv_protocol/_connect.py index 4613ff2b8..2f95ca7b3 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/_connect.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/_connect.py @@ -8,12 +8,18 @@ import anyio import httpx -import sniffio + +try: + import sniffio +except ImportError: + sniffio = None def _runtime(): - # HTTPX uses native Trio when called from Trio. AnyIO 3's Trio adapter requires older Trio versions. - return import_module("trio") if sniffio.current_async_library() == "trio" else anyio + # Trio installs sniffio; asyncio-only HTTPX installations can omit it. + if sniffio is not None and sniffio.current_async_library() == "trio": + return import_module("trio") + return anyio async def _send_attempt(client: httpx.AsyncClient, request: httpx.Request, deadline: float, runtime) -> httpx.Response: diff --git a/packages/agentenv-protocol/tests/test_transport_timeouts.py b/packages/agentenv-protocol/tests/test_transport_timeouts.py index 3c28f2d94..04b114f93 100644 --- a/packages/agentenv-protocol/tests/test_transport_timeouts.py +++ b/packages/agentenv-protocol/tests/test_transport_timeouts.py @@ -1,7 +1,9 @@ """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 @@ -27,6 +29,40 @@ def accept(reader, writer): await asyncio.gather(*tasks) +@pytest.mark.asyncio +async def test_asyncio_card_lookup_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 + assert asyncio.run(client.get_card(sys.argv[1], timeout=3)) == {"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", "*") diff --git a/uv.lock b/uv.lock index d47f8a77d..86cafe030 100644 --- a/uv.lock +++ b/uv.lock @@ -298,7 +298,6 @@ dependencies = [ { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13.14'" }, { name = "httpx" }, { name = "pydantic" }, - { name = "sniffio" }, { name = "starlette" }, ] @@ -382,7 +381,6 @@ requires-dist = [ { name = "python-xlib", marker = "extra == 'x11'", specifier = ">=0.33,<0.34" }, { name = "regex", marker = "extra == 'agent'", specifier = ">=2023.12.25" }, { name = "regex", marker = "extra == 'dev'", specifier = ">=2023.12.25" }, - { name = "sniffio", specifier = ">=1.1" }, { name = "starlette", specifier = ">=0.37" }, { name = "trio", marker = "extra == 'dev'", specifier = ">=0.24" }, { name = "uvicorn", marker = "extra == 'agent'", specifier = ">=0.30" }, From baf777cc5af880d894d4600c896aa3aae00bedd8 Mon Sep 17 00:00:00 2001 From: morningducke <70541786+morningducke@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:57:03 +0300 Subject: [PATCH 6/7] feat(protocol): make extension connection retries opt-in --- packages/agentenv-protocol/README.md | 25 +- packages/agentenv-protocol/pyproject.toml | 1 - .../src/agentenv_protocol/_connect.py | 104 ++---- .../src/agentenv_protocol/client.py | 53 +-- .../src/agentenv_protocol/tool_client.py | 14 +- .../agentenv-protocol/tests/test_client.py | 134 ++++--- .../tests/test_connect_retries.py | 333 +++++++----------- .../tests/test_transport_timeouts.py | 27 +- .../task_steps/modify_env_tool_access.py | 5 +- .../task_steps/set_env_clock_rate.py | 8 +- .../task_step/task_steps/sync_env_clock.py | 19 +- tst/unit/task_step/sync_env_clock_test.py | 18 +- .../task_step/test_apply_server_config.py | 36 +- .../task_step/test_modify_env_tool_access.py | 8 +- .../task_step/test_prompt_agent_triggers.py | 131 +++---- tst/unit/task_step/test_snapshot_env.py | 3 +- uv.lock | 3 - 17 files changed, 441 insertions(+), 481 deletions(-) diff --git a/packages/agentenv-protocol/README.md b/packages/agentenv-protocol/README.md index c137aff55..6f985840c 100644 --- a/packages/agentenv-protocol/README.md +++ b/packages/agentenv-protocol/README.md @@ -218,13 +218,18 @@ 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. -Data-plane RPCs, card and manifest lookups, and extension calls retry TCP or TLS connection failures -before sending the request. Up to three attempts share the connection budget from `timeout`, including -backoffs of 0.5 and 1 second when time permits. After connecting, `timeout` keeps its HTTPX meaning -for each read and write. A transfer can continue while it makes progress. For a wall-clock limit -across retries and the entire reply, pass `total_timeout` in seconds, for example -`await client.add_data(url, parts, timeout=30, total_timeout=120)`. Expiring that limit raises -`httpx.TimeoutException`. Read and write errors retain their HTTPX exception types. +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, @@ -446,9 +451,9 @@ async with ToolSession(mcp_url=mcp_url, role="alice@example.com") as session: call, and a stateless server has no session to lose, so neither restart raises anything. - `httpx.TransportError` means the connection failed, and `TimeoutError` that a request outlived `timeout` (600 s by default, the gateway's own limit on a tool call). - - MCP POSTs use the same connection retries. The session's `timeout` covers attempts, waits and the - reply to each MCP request. After sending, a failed call may still have run on the server. Read the - state back with `data/get` or end the episode before trying again. + - `ToolSession` retries nothing. A call that raised may still have run on the server, or may yet run: a request + stalled on a bad link can arrive after the client has given up. So after any failed call the env's state is + unknown; read it back (`data/get`) or end the episode. - **Tools:** `list_tools()` returns the tools the role may use as `EnvironmentTool`, the type a card's `capabilities.tools` holds. Each `inputSchema` is the JSON Schema a model API takes as the tool's parameters. diff --git a/packages/agentenv-protocol/pyproject.toml b/packages/agentenv-protocol/pyproject.toml index 48858287a..a0af7affb 100644 --- a/packages/agentenv-protocol/pyproject.toml +++ b/packages/agentenv-protocol/pyproject.toml @@ -22,7 +22,6 @@ classifiers = [ "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [ - "anyio>=3.6.2", "pydantic>=2.11", "starlette>=0.37", "httpx>=0.27", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/_connect.py b/packages/agentenv-protocol/src/agentenv_protocol/_connect.py index 2f95ca7b3..234afbc79 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/_connect.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/_connect.py @@ -1,12 +1,9 @@ -"""Retry connections before the first request reaches the environment.""" +"""Bound connection attempts for an opted-in HTTPX extension call.""" -from collections.abc import AsyncIterator -from contextlib import asynccontextmanager, nullcontext +import asyncio from importlib import import_module from math import inf, isfinite -from typing import Any -import anyio import httpx try: @@ -15,80 +12,55 @@ sniffio = None -def _runtime(): - # Trio installs sniffio; asyncio-only HTTPX installations can omit it. - if sniffio is not None and sniffio.current_async_library() == "trio": - return import_module("trio") - return anyio +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 - -async def _send_attempt(client: httpx.AsyncClient, request: httpx.Request, deadline: float, runtime) -> httpx.Response: + 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") - stream = None async def trace(event, info): - nonlocal deadline, stream - if event.endswith((".connect_tcp.started", ".start_tls.started")) and isfinite(deadline): - # httpcore passes these arguments to each handshake. TCP and TLS share this attempt's budget. - info["timeout"] = max(0, deadline - runtime.current_time()) + 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): - # Cancellation can interrupt TLS before the pool takes ownership of the socket. - with runtime.CancelScope(shield=True): - await stream.aclose() + # 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": - # A followed redirect has its own connection. Only the original hop is eligible for retry. - deadline = inf + sent = True if previous is not None: await previous(event, info) request.extensions = {**extensions, "trace": trace} try: - return await client.send(request, stream=True) + 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 - - -@asynccontextmanager -async def open_response(client: httpx.AsyncClient, request: httpx.Request) -> AsyncIterator[httpx.Response]: - runtime = _runtime() - timeout = request.extensions["timeout"]["connect"] - deadline = runtime.current_effective_deadline() - if timeout is not None: - deadline = min(deadline, runtime.current_time() + timeout) - - delays = (0.5, 1.0, None) - for attempt, delay in enumerate(delays): - now = runtime.current_time() - remaining = max(0, deadline - now) - share = remaining / (len(delays) - attempt) - attempt_deadline = deadline - if delay is not None and share + delay < remaining: - attempt_deadline = now + share - try: - response = await _send_attempt(client, request, attempt_deadline, runtime) - break - except (httpx.ConnectError, httpx.ConnectTimeout) as exc: - # HTTPX attaches the failing hop's request. A redirect means the original was sent. - if exc.request is not request or delay is None or runtime.current_time() + delay >= deadline: - raise - await runtime.sleep(delay) - if runtime.current_time() >= deadline: - raise - try: - yield response - finally: - with runtime.CancelScope(shield=True): - await response.aclose() - - -async def request(client: httpx.AsyncClient, method: str, url: str, *, timeout: float, total_timeout: float | None, - **kwargs: Any) -> httpx.Response: - outgoing = client.build_request(method, url, timeout=timeout, **kwargs) - with (_runtime().move_on_after(total_timeout) if total_timeout is not None else nullcontext()): - async with open_response(client, outgoing) as response: - await response.aread() - return response - raise httpx.TimeoutException(f"{method} did not finish within {total_timeout}s", request=outgoing) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/client.py b/packages/agentenv-protocol/src/agentenv_protocol/client.py index 9ad2af862..505af9fe3 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/client.py @@ -11,15 +11,16 @@ import httpx -from . import _connect 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): @@ -84,12 +85,11 @@ def granted_headers(url: str, grants: dict[str | None, dict[str, str]]) -> dict[ async def _rpc(base_url: str, method: str, params: dict, timeout: int, verify: bool, - headers: dict[str, str] | None, total_timeout: float | None) -> dict: + headers: dict[str, str] | None) -> dict: request = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params} url = f"{base_url.rstrip('/')}{RPC_PATH}" async with httpx.AsyncClient(verify=verify) as client: - response = await _connect.request(client, "POST", url, json=request, timeout=timeout, total_timeout=total_timeout, - headers=request_headers(url, headers)) + response = await client.post(url, json=request, timeout=timeout, headers=request_headers(url, headers)) response.raise_for_status() body = response.json() if "error" in body: @@ -99,19 +99,19 @@ async def _rpc(base_url: str, method: str, params: dict, timeout: int, verify: b async def reset_data(base_url: str, timeout: int = 30, verify: bool = True, *, - headers: dict[str, str] | None = None, total_timeout: float | None = None) -> ResetDataResponse: - return ResetDataResponse.model_validate(await _rpc(base_url, METHOD_RESET, {}, timeout, verify, headers, total_timeout)) + headers: dict[str, str] | None = None) -> ResetDataResponse: + return ResetDataResponse.model_validate(await _rpc(base_url, METHOD_RESET, {}, timeout, verify, headers)) async def add_data(base_url: str, parts: list[Part], timeout: int = 120, verify: bool = True, *, - headers: dict[str, str] | None = None, total_timeout: float | None = None) -> AddDataResponse: + headers: dict[str, str] | None = None) -> AddDataResponse: params = {"parts": [p.model_dump(mode="json", exclude_none=True) for p in parts]} - return AddDataResponse.model_validate(await _rpc(base_url, METHOD_ADD, params, timeout, verify, headers, total_timeout)) + return AddDataResponse.model_validate(await _rpc(base_url, METHOD_ADD, params, timeout, verify, headers)) async def get_data( base_url: str, timeout: int = 30, verify: bool = True, *, write_namespace: WriteNamespaceGrant | None = None, - paths: list[str] | None = None, headers: dict[str, str] | None = None, total_timeout: float | None = None, + paths: list[str] | None = None, headers: dict[str, str] | None = None, ) -> GetDataResponse: """`data/get`. A server advertising `DATA_OBJECTS_EXTENSION_URI` may be handed `write_namespace` to upload its export under; `uploaded_object_path` reads from the answer where it did. `paths` names what a computer @@ -119,13 +119,12 @@ async def get_data( params = {} if write_namespace is None else {"write_namespace": write_namespace.model_dump(mode="json", exclude_none=True)} if paths is not None: params["paths"] = paths - return GetDataResponse.model_validate(await _rpc(base_url, METHOD_GET, params, timeout, verify, headers, total_timeout)) + return GetDataResponse.model_validate(await _rpc(base_url, METHOD_GET, params, timeout, verify, headers)) -async def get_card(base_url: str, timeout: int = 10, verify: bool = True, *, total_timeout: float | None = None) -> dict: +async def get_card(base_url: str, timeout: int = 10, verify: bool = True) -> dict: async with httpx.AsyncClient(verify=verify) as client: - response = await _connect.request(client, "GET", f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout, - total_timeout=total_timeout) + response = await client.get(f"{base_url.rstrip('/')}{WELL_KNOWN_PATH}", timeout=timeout) response.raise_for_status() return response.json() @@ -325,7 +324,7 @@ def find_child(card: dict, name: str) -> dict | None: async def get_interface_manifest(base_url: str, interface: str, endpoint: str = INTERFACE_MANIFEST_PATH, timeout: int = 30, verify: bool = True, *, - headers: dict[str, str] | None = None, total_timeout: float | None = None): + headers: dict[str, str] | None = None): """Fetch one interface's manifest from a server's manifest index endpoint. ``endpoint`` is the index path — pass the one advertised on the card under @@ -336,14 +335,23 @@ async def get_interface_manifest(base_url: str, interface: str, endpoint: str = """ url = f"{base_url.rstrip('/')}{endpoint}/{interface}" async with httpx.AsyncClient(verify=verify) as client: - response = await _connect.request(client, "GET", url, timeout=timeout, total_timeout=total_timeout, - headers=request_headers(url, headers)) + response = await client.get(url, timeout=timeout, headers=request_headers(url, headers)) response.raise_for_status() 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, total_timeout: float | None = None): + headers: dict[str, str] | None = None): """Invoke a card extension via its advertised REST endpoint. Reads the endpoint and HTTP verb of the extension method named `method` from the card, so the @@ -364,9 +372,14 @@ 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: - arguments = {"params": params or {}} if op["method"] == "GET" else {"json": params or {}} - response = await _connect.request(client, op["method"], url, timeout=timeout, total_timeout=total_timeout, - headers=sent, **arguments) + 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) if response.status_code >= 400: raise ExtensionCallError(response) return response.json() diff --git a/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py b/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py index 5669a01af..77cfab019 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/tool_client.py @@ -10,11 +10,9 @@ from collections.abc import AsyncIterator from typing import Any -import anyio import httpx from pydantic import BaseModel, Field, field_validator -from ._connect import open_response from .tool_context import ROLE_HEADER from .types import PROTOCOL_VERSION, EnvironmentTool @@ -48,7 +46,7 @@ def text(self) -> str: class ToolSession: """One MCP session on an env's ``mcp_url``. Use it on the event loop that opened it, and after any failed call treat - the env's state as unknown. A connection can be retried before sending. A call that reached the server may still run.""" + the env's state as unknown: nothing is retried, and a call that raised may still run on the server.""" def __init__(self, *, mcp_url: str, role: str | None = None, headers: dict[str, str] | None = None, timeout: float = 600.0) -> None: @@ -129,15 +127,13 @@ async def _request(self, method: str, params: dict[str, Any]) -> dict: async def _deadline(self, method: str, exchange: Any) -> Any: try: - with anyio.fail_after(self.timeout): - return await exchange - except TimeoutError as e: + return await asyncio.wait_for(exchange, self.timeout) + except asyncio.TimeoutError as e: raise TimeoutError(f"{method} did not finish within {self.timeout}s") from e async def _exchange(self, message: dict) -> dict: - client = self._open_client() - request = client.build_request("POST", self.mcp_url, json=message, headers=self._session_headers()) - async with open_response(client, request) as response: + async with self._open_client().stream("POST", self.mcp_url, json=message, + headers=self._session_headers()) as response: await self._raise_for_status(response, message["method"]) if "id" not in message: return {} diff --git a/packages/agentenv-protocol/tests/test_client.py b/packages/agentenv-protocol/tests/test_client.py index 5e13b7ad8..3c6d3c570 100644 --- a/packages/agentenv-protocol/tests/test_client.py +++ b/packages/agentenv-protocol/tests/test_client.py @@ -2,10 +2,8 @@ from __future__ import annotations -import json import re -from contextlib import contextmanager -from unittest.mock import patch +from unittest.mock import AsyncMock, MagicMock, patch import httpx import pytest @@ -15,88 +13,108 @@ _BASE = "http://gw/svc/mcp-items" -@contextmanager -def _serve(response: httpx.Response | httpx.ConnectError): - requests = [] +def _resp(json_value, status: int = 200) -> MagicMock: + r = MagicMock() + r.status_code = status + r.json = MagicMock(return_value=json_value) + if status >= 400: + err = httpx.HTTPStatusError("err", request=MagicMock(), response=MagicMock(status_code=status)) + r.raise_for_status = MagicMock(side_effect=err) + else: + r.raise_for_status = MagicMock() + return r - def handle(request): - requests.append(request) - if isinstance(response, httpx.ConnectError): - raise response - return response - transport = httpx.MockTransport(handle) - client = httpx.AsyncClient(transport=transport) - with patch("agentenv_protocol.client.httpx.AsyncClient", return_value=client): - yield requests +def _client(resp: MagicMock) -> MagicMock: + client = MagicMock() + client.post = AsyncMock(return_value=resp) + client.get = AsyncMock(return_value=resp) + client.request = AsyncMock(return_value=resp) + client.__aenter__ = AsyncMock(return_value=client) + client.__aexit__ = AsyncMock(return_value=False) + return client + + +def _patch(client: MagicMock): + return patch("agentenv_protocol.client.httpx.AsyncClient", return_value=client) @pytest.mark.asyncio async def test_reset_data_posts_rpc(): - with _serve(httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {}})) as requests: + client = _client(_resp({"jsonrpc": "2.0", "id": 1, "result": {}})) + with _patch(client): assert (await protocol_v1.reset_data(_BASE)).model_dump() == {} - assert [(r.method, str(r.url)) for r in requests] == [("POST", f"{_BASE}/agentenv")] - assert json.loads(requests[0].content)["method"] == "data/reset" + assert client.post.call_args.args[0] == f"{_BASE}/agentenv" + assert client.post.call_args.kwargs["json"]["method"] == "data/reset" @pytest.mark.asyncio async def test_add_data_posts_parts(): - with _serve(httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {}})) as requests: + client = _client(_resp({"jsonrpc": "2.0", "id": 1, "result": {}})) + with _patch(client): assert (await protocol_v1.add_data(_BASE, [DataPart(data={"items": ["a"]})])).model_dump() == {} - sent = json.loads(requests[0].content) - assert [(r.method, str(r.url)) for r in requests] == [("POST", f"{_BASE}/agentenv")] + sent = client.post.call_args.kwargs["json"] + assert client.post.call_args.args[0] == f"{_BASE}/agentenv" assert sent["method"] == "data/add" assert sent["params"] == {"parts": [{"kind": "data", "data": {"items": ["a"]}}]} @pytest.mark.asyncio async def test_get_data_posts_rpc(): - with _serve(httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {"parts": [{"kind": "data", "data": {"items": []}}]}})) as requests: + client = _client(_resp({"jsonrpc": "2.0", "id": 1, "result": {"parts": [{"kind": "data", "data": {"items": []}}]}})) + with _patch(client): assert (await protocol_v1.get_data(_BASE)).parts[0].data == {"items": []} - assert [(r.method, str(r.url)) for r in requests] == [("POST", f"{_BASE}/agentenv")] - assert json.loads(requests[0].content)["method"] == "data/get" + assert client.post.call_args.args[0] == f"{_BASE}/agentenv" + assert client.post.call_args.kwargs["json"]["method"] == "data/get" @pytest.mark.asyncio async def test_get_card_gets_well_known(): - with _serve(httpx.Response(200, json={"name": "items"})) as requests: + client = _client(_resp({"name": "items"})) + with _patch(client): assert await protocol_v1.get_card(_BASE) == {"name": "items"} - assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/.well-known/agent-env.json")] + assert client.get.call_args.args[0] == f"{_BASE}/.well-known/agent-env.json" @pytest.mark.asyncio async def test_rpc_and_card_strip_trailing_slashes_from_base_url(): base_with_slash = f"{_BASE}/" - with _serve(httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": {}})) as requests: + client = _client(_resp({"jsonrpc": "2.0", "id": 1, "result": {}})) + with _patch(client): await protocol_v1.reset_data(base_with_slash) - assert [(r.method, str(r.url)) for r in requests] == [("POST", f"{_BASE}/agentenv")] + assert client.post.call_args.args[0] == f"{_BASE}/agentenv" - with _serve(httpx.Response(200, json={"name": "items"})) as requests: + client = _client(_resp({"name": "items"})) + with _patch(client): await protocol_v1.get_card(base_with_slash) - assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/.well-known/agent-env.json")] + assert client.get.call_args.args[0] == f"{_BASE}/.well-known/agent-env.json" @pytest.mark.asyncio async def test_supports_v1_true_on_card(): - with _serve(httpx.Response(200, json={"name": "items"})): + with _patch(_client(_resp({"name": "items"}))): assert await protocol_v1.supports_v1(_BASE) is True @pytest.mark.asyncio async def test_supports_v1_false_on_404(): - with _serve(httpx.Response(404)): + with _patch(_client(_resp(None, status=404))): assert await protocol_v1.supports_v1(_BASE) is False @pytest.mark.asyncio async def test_supports_v1_false_on_500(): - with _serve(httpx.Response(500)): + with _patch(_client(_resp(None, status=500))): assert await protocol_v1.supports_v1(_BASE) is False @pytest.mark.asyncio async def test_supports_v1_false_on_connect_error(): - with _serve(httpx.ConnectError("boom")): + client = MagicMock() + client.get = AsyncMock(side_effect=httpx.ConnectError("boom")) + client.__aenter__ = AsyncMock(return_value=client) + client.__aexit__ = AsyncMock(return_value=False) + with _patch(client): assert await protocol_v1.supports_v1(_BASE) is False @@ -270,26 +288,29 @@ def test_find_extension_ignores_children(): @pytest.mark.asyncio async def test_invoke_extension_posts_to_advertised_endpoint(): - with _serve(httpx.Response(200, json={"tool_name": "list_items", "error_rate": 0.75})) as requests: + client = _client(_resp({"tool_name": "list_items", "error_rate": 0.75})) + with _patch(client): result = await protocol_v1.invoke_extension( _BASE, _CARD_SET_ERRORS, "urn:agentenv:set-errors/v1", {"tool_name": "list_items", "error_rate": 0.75}, ) assert result == {"tool_name": "list_items", "error_rate": 0.75} - request, = requests - assert (request.method, str(request.url)) == ("POST", f"{_BASE}/agentenv/ext/set_errors") - assert json.loads(request.content) == {"tool_name": "list_items", "error_rate": 0.75} + args, kwargs = client.request.call_args + assert args[0] == "POST" and args[1] == f"{_BASE}/agentenv/ext/set_errors" + assert kwargs["json"] == {"tool_name": "list_items", "error_rate": 0.75} @pytest.mark.asyncio async def test_invoke_extension_strips_trailing_slashes_from_base_url(): base_with_slash = f"{_BASE}/" - with _serve(httpx.Response(200, json={"tool_name": "list_items", "error_rate": 0.75})) as requests: + client = _client(_resp({"tool_name": "list_items", "error_rate": 0.75})) + with _patch(client): await protocol_v1.invoke_extension( base_with_slash, _CARD_SET_ERRORS, "urn:agentenv:set-errors/v1", {"tool_name": "list_items", "error_rate": 0.75}, ) - assert [str(r.url) for r in requests] == [f"{_BASE}/agentenv/ext/set_errors"] + args, _ = client.request.call_args + assert args[1] == f"{_BASE}/agentenv/ext/set_errors" @pytest.mark.asyncio @@ -298,10 +319,11 @@ async def test_invoke_extension_get_uses_query_params(): "uri": "urn:agentenv:ping/v1", "params": {"endpoint": "/agentenv/ext/ping", "methods": {"ping": {"method": "GET", "request": {}}}}, }]}} - with _serve(httpx.Response(200, json={"pong": True})) as requests: + client = _client(_resp({"pong": True})) + with _patch(client): result = await protocol_v1.invoke_extension(_BASE, card, "urn:agentenv:ping/v1") assert result == {"pong": True} - assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/agentenv/ext/ping")] + assert client.get.call_args.args[0] == f"{_BASE}/agentenv/ext/ping" def _error_response(status: int, **kwargs) -> httpx.Response: @@ -321,7 +343,7 @@ def _error_response(status: int, **kwargs) -> httpx.Response: (_error_response(404, json=["not", "an", "object"]), (None, "Not Found", False, "unknown", None)), ]) async def test_invoke_extension_raises_the_error_fields_it_was_sent(response, fields): - with _serve(response), pytest.raises(ExtensionCallError) as raised: + with _patch(_client(response)), pytest.raises(ExtensionCallError) as raised: await protocol_v1.invoke_extension(_BASE, _CARD_SET_ERRORS, "urn:agentenv:set-errors/v1", {}) error = raised.value assert (error.code, error.detail, error.retryable, error.applied, error.hint) == fields @@ -376,35 +398,41 @@ def test_find_extension_method_unknown_method_or_uri_returns_none(): @pytest.mark.asyncio async def test_invoke_extension_calls_the_named_method(): - with _serve(httpx.Response(200, json={"virtual_time": "2026-01-01T00:00:00Z"})) as requests: + client = _client(_resp({"virtual_time": "2026-01-01T00:00:00Z"})) + with _patch(client): await protocol_v1.invoke_extension( _BASE, _CARD_CLOCK, "urn:agentenv:clock/v1", {"time": "2026-01-01T00:00:00Z"}, method="set_time", ) - request, = requests - assert (request.method, str(request.url)) == ("PUT", f"{_BASE}/clock/set-time") - assert json.loads(request.content) == {"time": "2026-01-01T00:00:00Z"} + args, kwargs = client.request.call_args + assert args[0] == "PUT" and args[1] == f"{_BASE}/clock/set-time" + assert kwargs["json"] == {"time": "2026-01-01T00:00:00Z"} @pytest.mark.asyncio async def test_invoke_extension_named_get_method_uses_query_params(): - with _serve(httpx.Response(200, json={"frozen": False})) as requests: + client = _client(_resp({"frozen": False})) + with _patch(client): assert await protocol_v1.invoke_extension(_BASE, _CARD_CLOCK, "urn:agentenv:clock/v1", method="state") == {"frozen": False} - assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/clock/state")] + assert client.get.call_args.args[0] == f"{_BASE}/clock/state" @pytest.mark.asyncio async def test_invoke_extension_without_a_method_calls_the_first_listed(): - with _serve(httpx.Response(200, json={})) as requests: + client = _client(_resp({})) + with _patch(client): await protocol_v1.invoke_extension(_BASE, _CARD_CLOCK, "urn:agentenv:clock/v1") - assert [(r.method, str(r.url)) for r in requests] == [("GET", f"{_BASE}/clock/time")] + assert client.get.call_args.args[0] == f"{_BASE}/clock/time" + client.request.assert_not_called() @pytest.mark.asyncio async def test_invoke_extension_unknown_method_raises_without_calling(): + client = _client(_resp({})) offered = "does not advertise method 'sync_time' (advertises: get_time, set_time, state)" - with _serve(httpx.Response(200, json={})) as requests, pytest.raises(ValueError, match=re.escape(offered)): + with _patch(client), pytest.raises(ValueError, match=re.escape(offered)): await protocol_v1.invoke_extension(_BASE, _CARD_CLOCK, "urn:agentenv:clock/v1", method="sync_time") - assert not requests + client.get.assert_not_called() + client.request.assert_not_called() @pytest.mark.asyncio diff --git a/packages/agentenv-protocol/tests/test_connect_retries.py b/packages/agentenv-protocol/tests/test_connect_retries.py index 000fe55d4..07b3f9cde 100644 --- a/packages/agentenv-protocol/tests/test_connect_retries.py +++ b/packages/agentenv-protocol/tests/test_connect_retries.py @@ -1,263 +1,184 @@ -"""Drive the protocol clients through HTTPX, injecting failures at the TCP boundary.""" +"""Opted-in extension calls, through HTTPX's real request and redirect handling.""" import asyncio -import json +from contextlib import nullcontext import httpcore import httpx import pytest import trio -from anyio.lowlevel import checkpoint from httpcore._backends.auto import AutoBackend from trio.testing import MockClock -from agentenv_protocol import ExtensionCallError, ToolSession, ToolSessionError, client +from agentenv_protocol import ExtensionCallError, ToolSession, client _URL = "http://env.test" -_CARD = {"capabilities": {"extensions": [{"uri": "urn:test", "params": {"methods": { +_URI = "urn:example:setup/v1" +_CARD = {"capabilities": {"extensions": [{"uri": _URI, "params": {"methods": { "set": {"method": "POST", "endpoint": "/set"}, "get": {"method": "GET", "endpoint": "/get"}, }}}]}} -async def call(route, timeout=5, *, total_timeout=None): - budgets = {"timeout": timeout, "total_timeout": total_timeout} - if route == "rpc": - return await client.add_data(_URL, [], **budgets) - if route == "reset": - return await client.reset_data(_URL, **budgets) - if route == "data": - return await client.get_data(_URL, **budgets) - if route == "card": - return await client.get_card(_URL, **budgets) - if route == "manifest": - return await client.get_interface_manifest(_URL, "items", **budgets) - if route == "tool": - async with ToolSession(mcp_url=_URL + "/mcp", timeout=timeout) as session: - return await session.call_tool("sample") - return await client.invoke_extension(_URL, _CARD, "urn:test", {"value": 1}, method=route, **budgets) - - -class Wire: - def __init__(self): - self.attempts = 0 - self.requests = [] - self.closed = 0 - self.on_connect = None - self.read_error = self.write_error = None - self.status = 200 - self.redirect = False - - async def connect(self, host): - self.attempts += 1 - if self.on_connect: - await self.on_connect(self.attempts) - if host == "redirect.test": - raise httpcore.ConnectError("redirect target unavailable") - return Stream(self) - - -class Stream(httpcore.AsyncMockStream): - def __init__(self, wire): - super().__init__([]) - self.wire = wire - self.data = bytearray() - - async def write(self, buffer, timeout=None): - self.data.extend(buffer) - if self.wire.write_error: - raise self.wire.write_error("interrupted write") - - async def read(self, max_bytes, timeout=None): - headers, body = self.data.split(b"\r\n\r\n", 1) - message = json.loads(body or b"{}") - path = headers.split(b" ", 2)[1].decode() - method = message.get("method", "") - self.wire.requests.append((path, method)) - if self.wire.read_error: - raise self.wire.read_error("interrupted read") - if self.wire.redirect: - return b"HTTP/1.1 307 Temporary Redirect\r\nLocation: http://redirect.test/mcp\r\nContent-Length: 0\r\n\r\n" - data = json.dumps({"jsonrpc": "2.0", "id": message.get("id"), "result": {}}).encode() - status = self.wire.status - if method == "notifications/initialized" and status == 200: - status, data = 202, b"" - return (f"HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {len(data)}\r\n" - "Connection: close\r\n\r\n").encode() + data - - async def aclose(self): - self.wire.closed += 1 - await super().aclose() - - -@pytest.fixture -def wire(monkeypatch): - wire = Wire() - monkeypatch.setenv("no_proxy", "*") +async def extension(method="set", timeout=5): + return await client.invoke_extension(_URL, _CARD, _URI, {"value": 1}, timeout=timeout, method=method) + - async def connect_tcp(self, host, **kwargs): - return await wire.connect(host) +def mock_http(monkeypatch, handle, *, redirects=False): + real = httpx.AsyncClient - monkeypatch.setattr(AutoBackend, "connect_tcp", connect_tcp) - return wire + 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("route", ["rpc", "card", "manifest", "set", "get", "tool"]) -async def test_connection_timeout_recovers_before_the_request_is_sent(wire, route): - failed_attempt = 3 if route == "tool" else 1 +@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 - async def fail_once(attempt): - if attempt == failed_attempt: - raise httpcore.ConnectTimeout("before sending") - wire.on_connect = fail_once - await call(route) - assert wire.attempts == failed_attempt + 1 - assert len(wire.requests) == failed_attempt - assert wire.closed == len(wire.requests) - if route == "tool": - assert [method for _, method in wire.requests] == ["initialize", "notifications/initialized", "tools/call"] +@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): + attempts = [] + + def refuse(request): + attempts.append(request) + raise httpx.ConnectError("connection refused") + + mock_http(monkeypatch, 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 len(attempts) == 1 @pytest.mark.asyncio -@pytest.mark.parametrize("error", [httpcore.ConnectError, httpcore.ConnectTimeout]) -async def test_failed_connections_stop_after_three_attempts(wire, error): +@pytest.mark.parametrize("timeout, expected", [(5, 3), (0.25, 1)]) +async def test_exhaustion_returns_the_last_connection_error(monkeypatch, timeout, expected): started = [] - async def fail(attempt): + def refuse(request): started.append(asyncio.get_running_loop().time()) - raise error(f"attempt {attempt}") + raise httpx.ConnectError(f"attempt {len(started)}") - wire.on_connect = fail - with pytest.raises(getattr(httpx, error.__name__), match="attempt 3") as caught: - await call("rpc") - assert caught.value.request.url.path == "/agentenv" - assert wire.attempts == 3 and wire.requests == [] - assert started[1] - started[0] >= 0.49 - assert started[2] - started[1] >= 0.99 + 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("route", ["rpc", "reset", "data", "card", "manifest", "set", "get", "tool"]) -async def test_retried_call_uses_the_whole_call_deadline(wire, route): - async def connect(attempt): - if attempt == 1: - await asyncio.sleep(0.45) - raise httpcore.ConnectError("first attempt") - await asyncio.sleep(0.65) - - wire.on_connect = connect - with pytest.raises(TimeoutError if route == "tool" else httpx.TimeoutException): - await call(route, timeout=1.4, total_timeout=1.4) - assert wire.attempts == 2 and wire.requests == [] +@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") -@pytest.mark.asyncio -async def test_first_attempt_can_use_up_the_backoff_budget(wire): - async def slow_failure(attempt): - await asyncio.sleep(0.2) - raise httpcore.ConnectError("before sending") - - wire.on_connect = slow_failure - with pytest.raises(httpx.ConnectError, match="before sending"): - await call("rpc", timeout=0.6) - assert wire.attempts == 1 and wire.requests == [] + mock_http(monkeypatch, handle) + with client.retry_extension_connections(), pytest.raises(error): + await extension() + assert len(calls) == 1 @pytest.mark.asyncio -async def test_tool_session_preserves_refusal_when_backoff_cannot_fit(wire): - async def refuse(attempt): - raise httpcore.ConnectError("connection refused") - - wire.on_connect = refuse - with pytest.raises(httpx.ConnectError, match="connection refused"): - await call("tool", timeout=0.25) - assert wire.attempts == 1 and wire.requests == [] +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") -def test_retry_runs_on_native_trio(wire): - async def fail_once(attempt): - if attempt == 1: - raise httpcore.ConnectError("connection refused") - - wire.on_connect = fail_once - trio.run(call, "card", clock=MockClock(autojump_threshold=0)) - assert wire.attempts == 2 and len(wire.requests) == 1 + 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_cancellation_during_backoff_propagates(wire): +async def test_cancelling_one_opted_in_task_leaves_a_sibling_on_one_attempt(monkeypatch): failed = asyncio.Event() + attempts = [] - async def connect(attempt): + def refuse(request): + attempts.append(request) failed.set() - raise httpcore.ConnectError("before sending") + raise httpx.ConnectError("refused") - wire.on_connect = connect - task = asyncio.create_task(call("rpc")) + 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 wire.attempts == 1 and wire.requests == [] + assert len(attempts) == 2 -@pytest.mark.asyncio -@pytest.mark.parametrize("route", ["rpc", "set", "tool"]) -@pytest.mark.parametrize("failure", ["read", "write", "http"]) -async def test_ambiguous_failures_and_http_responses_are_not_retried(wire, route, failure): - if failure == "read": - wire.read_error, expected = httpcore.ReadTimeout, httpx.ReadTimeout - elif failure == "write": - wire.write_error, expected = httpcore.WriteTimeout, httpx.WriteTimeout - else: - wire.status = 503 - expected = {"rpc": httpx.HTTPStatusError, "set": ExtensionCallError, "tool": ToolSessionError}[route] - with pytest.raises(expected): - await call(route) - assert wire.attempts == 1 - assert wire.closed == 1 - - -@pytest.mark.asyncio -async def test_failure_connecting_to_a_redirect_never_resends_the_original_post(wire): - wire.redirect = True - with pytest.raises(httpx.ConnectError) as caught: - await call("tool") - assert caught.value.request.url.host == "redirect.test" - assert wire.requests == [("/mcp", "initialize")] - assert wire.attempts == 2 and wire.closed == 1 - - -@pytest.mark.asyncio -@pytest.mark.parametrize("route", ["rpc", "tool"]) -async def test_deadline_closes_an_incomplete_response_after_retry(monkeypatch, route): - attempts = 0 - closed = [] - - class Body(httpx.AsyncByteStream): - async def __aiter__(self): - yield b"data: " - await asyncio.sleep(5) +@pytest.mark.parametrize("opt_in", [False, True]) +def test_native_trio_uses_its_own_clock_for_backoff(monkeypatch, opt_in): + attempts = [] - async def aclose(self): - await checkpoint() - closed.append(True) - - def handle(request): - nonlocal attempts - attempts += 1 - if attempts == 1: - raise httpx.ConnectTimeout("first attempt", request=request) - return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=Body()) - - transport = httpx.MockTransport(handle) + 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 send(self, request): - return await transport.handle_async_request(request) + 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.setattr(httpx.AsyncHTTPTransport, "handle_async_request", send) - with pytest.raises(TimeoutError if route == "tool" else httpx.TimeoutException): - await call(route, timeout=0.7, total_timeout=0.7) - assert attempts == 2 and closed == [True] + 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 index 04b114f93..1e4920319 100644 --- a/packages/agentenv-protocol/tests/test_transport_timeouts.py +++ b/packages/agentenv-protocol/tests/test_transport_timeouts.py @@ -12,6 +12,14 @@ 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 = [], [] @@ -30,7 +38,7 @@ def accept(reader, writer): @pytest.mark.asyncio -async def test_asyncio_card_lookup_without_sniffio(monkeypatch): +async def test_asyncio_extension_without_sniffio(monkeypatch): monkeypatch.setenv("no_proxy", "*") probe = dedent(""" import asyncio @@ -46,7 +54,10 @@ async def test_asyncio_card_lookup_without_sniffio(monkeypatch): raise from agentenv_protocol import client - assert asyncio.run(client.get_card(sys.argv[1], timeout=3)) == {"name": "items"} + 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): @@ -82,7 +93,7 @@ async def reply(reader, writer): monkeypatch.setattr(anyio, "connect_tcp", stall_first) async with listen(reply) as address: - assert await client.get_card(f"http://{address}", timeout=2) == {} + assert await call(f"http://{address}", timeout=2) == {} assert len(attempts) == 2 and len(requests) == 1 @@ -101,12 +112,12 @@ async def hold(reader, writer): peer_closed.set() async with listen(hold) as address: - call = asyncio.create_task(client.get_card(f"https://{address}", timeout=1.5)) + task = asyncio.create_task(call(f"https://{address}", timeout=1.5)) if cancel: await asyncio.wait_for(hellos.wait(), 2) - call.cancel() + task.cancel() with pytest.raises(asyncio.CancelledError if cancel else httpx.ConnectTimeout): - await call + await task assert len(closed) == (1 if cancel else 2) await asyncio.wait_for(asyncio.gather(*(peer.wait() for peer in closed)), 1) @@ -129,7 +140,7 @@ async def reply(reader, writer): async with listen(reply) as address: if progress: - assert await client.get_card(f"http://{address}", timeout=0.3) == {} + assert await call(f"http://{address}", timeout=0.3) == {} else: with pytest.raises(httpx.ReadTimeout): - await client.get_card(f"http://{address}", timeout=0.3) + await call(f"http://{address}", timeout=0.3) 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_apply_server_config.py b/tst/unit/task_step/test_apply_server_config.py index a04ba2b41..9df2a67ec 100644 --- a/tst/unit/task_step/test_apply_server_config.py +++ b/tst/unit/task_step/test_apply_server_config.py @@ -99,16 +99,19 @@ async def request(self, method, url, *, json=None, timeout=None, headers=None): self.post_calls.append((url, json)) return _resp(200, url, {"ok": True, "echo": json}) + # invoke_extension uses client.get for GET verbs and client.request otherwise; + # our extensions are POST, so request() handles them. + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False -def _patch_httpx(gateway: _MockGateway): - async def handle(request): - url = str(request.url) - if request.method == "GET": - return await gateway.get(url) - return await gateway.request(request.method, url, json=json.loads(request.content)) - real = httpx.AsyncClient - return patch("httpx.AsyncClient", lambda **kwargs: real(transport=httpx.MockTransport(handle), **kwargs)) +def _patch_httpx(gateway: _MockGateway): + """Patch httpx.AsyncClient(...) so both get_card and invoke_extension talk to + our in-memory gateway. AsyncClient is a context manager, so return the mock.""" + return patch("httpx.AsyncClient", return_value=gateway) @pytest.mark.asyncio @@ -854,13 +857,20 @@ async def test_a_multi_envs_computer_is_configured_at_its_own_address_with_its_o child_envs={"desktop": dataclasses.asdict(computer)}) sent = [] - def handle(request): - sent.append((str(request.url), request.headers.get("Authorization"))) - return httpx.Response(200, json={"ok": True}) + class Client: + async def request(self, method, url, *, json=None, timeout=None, headers=None): + sent.append((url, headers)) + return _resp(200, url, {"ok": True}) + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False step = _step(directives=[{"service": service, "uri": _SET_ERRORS_URI, "args": {"tool_name": "t", "error_rate": 0.5}}]) - with patch("httpx.AsyncClient", return_value=httpx.AsyncClient(transport=httpx.MockTransport(handle))), \ + with patch("httpx.AsyncClient", return_value=Client()), \ patch("agent_env.env.env.Env.get", return_value=SimpleNamespace(mcp_server_envs=[], website_envs=[])): await step.execute(TaskStepContext(deployed_envs=[record])) - assert sent == [("https://desk.example/agentenv/ext/set_errors", computer.control_headers["Authorization"])] + assert sent == [("https://desk.example/agentenv/ext/set_errors", computer.control_headers)] 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/tst/unit/task_step/test_prompt_agent_triggers.py b/tst/unit/task_step/test_prompt_agent_triggers.py index 40de8df87..0d33d5b9a 100644 --- a/tst/unit/task_step/test_prompt_agent_triggers.py +++ b/tst/unit/task_step/test_prompt_agent_triggers.py @@ -5,7 +5,6 @@ from __future__ import annotations import asyncio -from types import SimpleNamespace from unittest.mock import AsyncMock, patch import httpx @@ -42,33 +41,19 @@ def _resp(status: int, body: dict, method: str = "GET") -> httpx.Response: return httpx.Response(status, json=body, request=httpx.Request(method, "http://x")) -def _serve_get(handler): - async def handle(transport, request): - assert request.method == "GET" - return await handler(request) - - return patch.object(httpx.AsyncHTTPTransport, "handle_async_request", handle) - - -def _skip_prompt_waits(): - prompt_asyncio = SimpleNamespace(**vars(asyncio)) - prompt_asyncio.sleep = AsyncMock() - return patch("agent_env.task_step.task_steps.prompt_agent.asyncio", prompt_asyncio) - - # ---- _read_env_triggers ----------------------------------------------------- @pytest.mark.asyncio async def test_snapshot_shape_multi_env(): sent = [] - async def fake_get(request): - sent.append((str(request.url), dict(request.url.params), request.extensions["timeout"]["read"])) + async def fake_get(self, url, timeout, params=None, headers=None): + sent.append((url, params, timeout)) return _resp(200, {"triggers": [{"id": "v6-rate", "status": "fired"}, {"id": "v6-accept", "status": "armed"}]}) ctx = _ctx(_env("env-a", "http://gw-a"), _env("env-b", "http://gw-b")) - with _serve_get(fake_get): + with patch.object(httpx.AsyncClient, "get", fake_get): snap = await _step()._read_env_triggers(ctx) assert snap == {"env-a": {"v6-rate": "fired", "v6-accept": "armed"}, @@ -78,11 +63,11 @@ async def fake_get(request): @pytest.mark.asyncio async def test_an_env_whose_card_offers_no_triggers_state_reads_as_empty_with_no_request(): - async def fake_get(request): + async def fake_get(self, url, timeout, params=None, headers=None): raise AssertionError("no request for an env whose card offers no triggers state") ctx = _ctx(_env("env-x", "http://gw-x", EXT_CLOCK_URI)) - with _serve_get(fake_get): + with patch.object(httpx.AsyncClient, "get", fake_get): snap = await _step()._read_env_triggers(ctx) assert snap == {"env-x": {}} @@ -90,41 +75,41 @@ async def fake_get(request): @pytest.mark.asyncio async def test_a_404_from_an_advertised_triggers_state_fails_closed(): - async def fake_get(request): + async def fake_get(self, url, timeout, params=None, headers=None): return _resp(404, {}) ctx = _ctx(_env("env-x", "http://gw-x")) - with _serve_get(fake_get), \ - _skip_prompt_waits(): + with patch.object(httpx.AsyncClient, "get", fake_get), \ + patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): with pytest.raises(RuntimeError, match="fail-closed: could not read /triggers/state for env 'env-x'"): await _step()._read_env_triggers(ctx) @pytest.mark.asyncio async def test_fail_closed_raises_on_persistent_error(): - async def fake_get(request): + async def fake_get(self, url, timeout, params=None, headers=None): raise httpx.ConnectError("gateway down") ctx = _ctx(_env("env-x", "http://gw-x")) - with _serve_get(fake_get), \ - _skip_prompt_waits(): + with patch.object(httpx.AsyncClient, "get", fake_get), \ + patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): with pytest.raises(RuntimeError, match="fail-closed: could not read /triggers/state for env 'env-x'"): await _step()._read_env_triggers(ctx) @pytest.mark.asyncio -async def test_retries_a_failed_trigger_state_read_then_succeeds(): +async def test_retries_then_succeeds(): calls = {"n": 0} - async def fake_get(request): + async def fake_get(self, url, timeout, params=None, headers=None): calls["n"] += 1 if calls["n"] == 1: - raise httpx.ReadTimeout("transient") + raise httpx.ConnectError("transient") return _resp(200, {"triggers": [{"id": "t", "status": "fired"}]}) ctx = _ctx(_env("env-x", "http://gw-x")) - with _serve_get(fake_get), \ - _skip_prompt_waits(): + with patch.object(httpx.AsyncClient, "get", fake_get), \ + patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): snap = await _step()._read_env_triggers(ctx) assert snap == {"env-x": {"t": "fired"}} and calls["n"] == 2 @@ -134,13 +119,13 @@ async def fake_get(request): async def test_triggers_state_is_read_at_the_stored_cards_address(): sent = [] - async def fake_get(request): - sent.append(str(request.url)) + async def fake_get(self, url, timeout, params=None, headers=None): + sent.append(url) return _resp(200, {"triggers": []}) env = _env("env-x", "http://gw-x") env.environment_card_url = f"https://sandbox.example/sb-1{WELL_KNOWN_PATH}" - with _serve_get(fake_get): + with patch.object(httpx.AsyncClient, "get", fake_get): await _step()._read_env_triggers(_ctx(env)) assert sent == ["https://sandbox.example/sb-1/triggers/state"] @@ -235,8 +220,8 @@ def _patched_store(store=None, *, key_prefix=""): async def test_capture_uploads_state_and_records_summary(): calls = {"n": 0} - async def fake_get(request): - if request.url.path.endswith("/clock/state"): + async def fake_get(self, url, timeout, params=None, headers=None): + if url.endswith("/clock/state"): return _resp(200, _CLOCK) calls["n"] += 1 return _resp(200, _STATE) @@ -248,7 +233,7 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) assert len(store.puts) == 1 @@ -271,8 +256,8 @@ async def fake_get(request): @pytest.mark.asyncio async def test_capture_is_kept_under_the_fixture_prefix(): - async def fake_get(request): - return _resp(200, _CLOCK if request.url.path.endswith("/clock/state") else _STATE) + async def fake_get(self, url, timeout, params=None, headers=None): + return _resp(200, _CLOCK if url.endswith("/clock/state") else _STATE) ctx = TaskStepContext( deployed_envs=[_env("env-a", "http://gw-a")], deployed_agents=[], instance_id="inst-1", @@ -280,7 +265,7 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store(key_prefix="fx/") - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) assert store.puts[0]["key"].startswith("fx/env_trigger_state/instance_id=inst-1/env-a-") @@ -289,8 +274,8 @@ async def fake_get(request): @pytest.mark.asyncio async def test_capture_records_clock_context_and_per_trigger_detail(): """A recurrence reads "armed" forever, so only fire_count shows it fired.""" - async def fake_get(request): - return _resp(200, _CLOCK if request.url.path.endswith("/clock/state") else _CLOCK_STATE) + async def fake_get(self, url, timeout, params=None, headers=None): + return _resp(200, _CLOCK if url.endswith("/clock/state") else _CLOCK_STATE) ctx = TaskStepContext( deployed_envs=[_env("env-a", "http://gw-a")], deployed_agents=[], instance_id="inst-1", @@ -298,7 +283,7 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["beat"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) import json as _json @@ -328,8 +313,8 @@ async def test_capture_distinguishes_a_failed_coupling_from_one_that_never_fired "failure_count": 2, "last_failure_at": "2026-06-01T12:00:00Z"}, ]} - async def fake_get(request): - return _resp(200, _CLOCK if request.url.path.endswith("/clock/state") else failed) + async def fake_get(self, url, timeout, params=None, headers=None): + return _resp(200, _CLOCK if url.endswith("/clock/state") else failed) ctx = TaskStepContext( deployed_envs=[_env("env-a", "http://gw-a")], deployed_agents=[], instance_id="inst-1", @@ -338,7 +323,7 @@ async def fake_get(request): "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) rows = ctx.metadata["env_trigger_state"]["env-a"]["triggers"] @@ -358,8 +343,8 @@ async def test_capture_does_not_wait_on_a_firing_recurring_clock_trigger(): "status": "firing", "fire_count": 3, "next_mark": "2026-06-03T00:00:00Z"}]} calls = {"n": 0} - async def fake_get(request): - if request.url.path.endswith("/clock/state"): + async def fake_get(self, url, timeout, params=None, headers=None): + if url.endswith("/clock/state"): return _resp(200, _CLOCK) calls["n"] += 1 return _resp(200, firing) @@ -370,8 +355,8 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["beat"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch, \ - _skip_prompt_waits(): + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch, \ + patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): await _capture_step()._persist_env_trigger_state(ctx) assert calls["n"] == 1, "a recurring clock trigger must not trigger the settle poll" @@ -381,8 +366,8 @@ async def fake_get(request): @pytest.mark.asyncio async def test_capture_tolerates_a_gateway_without_clock_state(): """An unreachable clock state: capture still succeeds, clock recorded as None.""" - async def fake_get(request): - if request.url.path.endswith("/clock/state"): + async def fake_get(self, url, timeout, params=None, headers=None): + if url.endswith("/clock/state"): raise httpx.ConnectError("no clock route") return _resp(200, _STATE) @@ -392,7 +377,7 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) import json as _json @@ -412,8 +397,8 @@ async def fake_get(request): async def test_capture_records_no_clock_with_no_request_when_the_card_offers_no_clock_state(): sent = [] - async def fake_get(request): - sent.append(str(request.url)) + async def fake_get(self, url, timeout, params=None, headers=None): + sent.append(url) return _resp(200, _STATE) ctx = TaskStepContext( @@ -422,7 +407,7 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) import json as _json @@ -434,9 +419,9 @@ async def fake_get(request): async def test_capture_reads_triggers_and_clock_at_the_stored_cards_address(): sent = [] - async def fake_get(request): - sent.append((str(request.url), request.extensions["timeout"]["read"])) - return _resp(200, _CLOCK if request.url.path.endswith("/clock/state") else _STATE) + async def fake_get(self, url, timeout, params=None, headers=None): + sent.append((url, timeout)) + return _resp(200, _CLOCK if url.endswith("/clock/state") else _STATE) env = _env("env-a", "http://gw-a") env.environment_card_url = f"https://sandbox.example/sb-1{WELL_KNOWN_PATH}" @@ -446,7 +431,7 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) assert sent == [("https://sandbox.example/sb-1/triggers/state", 15), ("https://sandbox.example/sb-1/clock/state", 5)] @@ -503,13 +488,13 @@ def test_settle_poll_does_not_wait_out_a_delay_or_working_hours(): async def test_capture_noop_without_registrations(): calls = {"n": 0} - async def fake_get(request): + async def fake_get(self, url, timeout, params=None, headers=None): calls["n"] += 1 return _resp(200, _STATE) ctx = _ctx(_env("env-a", "http://gw-a")) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) assert calls["n"] == 0 and store.puts == [] and "env_trigger_state" not in ctx.metadata @@ -517,7 +502,7 @@ async def fake_get(request): @pytest.mark.asyncio async def test_capture_fail_open_records_error(): - async def fake_get(request): + async def fake_get(self, url, timeout, params=None, headers=None): raise httpx.ConnectError("gateway gone") ctx = TaskStepContext( @@ -526,8 +511,8 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch, \ - _skip_prompt_waits(): + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch, \ + patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): await _capture_step()._persist_env_trigger_state(ctx) entry = ctx.metadata["env_trigger_state"]["env-a"] @@ -541,8 +526,8 @@ async def test_capture_grace_polls_until_settled(): responses = [firing, _STATE] calls = {"n": 0} - async def fake_get(request): - if request.url.path.endswith("/clock/state"): + async def fake_get(self, url, timeout, params=None, headers=None): + if url.endswith("/clock/state"): return _resp(200, _CLOCK) body = responses[min(calls["n"], len(responses) - 1)] calls["n"] += 1 @@ -554,8 +539,8 @@ async def fake_get(request): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(fake_get), cfg_patch, \ - _skip_prompt_waits(): + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch, \ + patch("agent_env.task_step.task_steps.prompt_agent.asyncio.sleep", new=AsyncMock()): await _capture_step()._persist_env_trigger_state(ctx) assert calls["n"] == 2 @@ -564,7 +549,7 @@ async def fake_get(request): @pytest.mark.asyncio async def test_capture_budget_bounds_total_time(): - async def hanging_get(request): + async def hanging_get(self, url, timeout): await asyncio.sleep(999) ctx = TaskStepContext( @@ -575,7 +560,7 @@ async def hanging_get(request): {"step_id": "reg-2", "env_id": "env-b", "added": ["t2"], "executor_agent_name": None}]}) store, cfg_patch = _patched_store() - with _serve_get(hanging_get), cfg_patch, \ + with patch.object(httpx.AsyncClient, "get", hanging_get), cfg_patch, \ patch.object(PromptAgentTaskStep, "_CAPTURE_BUDGET_SECONDS", 0.05): await _capture_step()._persist_env_trigger_state(ctx) @@ -587,7 +572,7 @@ async def hanging_get(request): @pytest.mark.asyncio async def test_capture_put_failure_keeps_inline_summary(): - async def fake_get(request): + async def fake_get(self, url, timeout, params=None, headers=None): return _resp(200, _STATE) class _FailingStore(_FakeStore): @@ -600,7 +585,7 @@ def put(self, *args, **kwargs): {"step_id": "reg-1", "env_id": "env-a", "added": ["v6-rate"], "executor_agent_name": None}]}) _, cfg_patch = _patched_store(_FailingStore()) - with _serve_get(fake_get), cfg_patch: + with patch.object(httpx.AsyncClient, "get", fake_get), cfg_patch: await _capture_step()._persist_env_trigger_state(ctx) entry = ctx.metadata["env_trigger_state"]["env-a"] diff --git a/tst/unit/task_step/test_snapshot_env.py b/tst/unit/task_step/test_snapshot_env.py index cff5e26ab..cf75fb7ca 100644 --- a/tst/unit/task_step/test_snapshot_env.py +++ b/tst/unit/task_step/test_snapshot_env.py @@ -1557,8 +1557,7 @@ async def test_export_of_a_website_whose_card_read_fails_raises_rather_than_skip with pytest.raises(httpx.HTTPError): await SnapshotEnvTaskStep._export_environment_to_file("https://gw-1", "shop", str(tmp_path / "out"), 30, mcp=False) - attempts = 3 if isinstance(card_response, httpx.ConnectError) else 1 - assert [str(r.url) for r in sent] == [f"https://gw-1/svc/shop{WELL_KNOWN_PATH}"] * attempts + assert [str(r.url) for r in sent] == [f"https://gw-1/svc/shop{WELL_KNOWN_PATH}"] @pytest.mark.asyncio diff --git a/uv.lock b/uv.lock index 86cafe030..7d705781b 100644 --- a/uv.lock +++ b/uv.lock @@ -294,8 +294,6 @@ name = "agentenv-framework-protocol" version = "0.1.636" source = { editable = "packages/agentenv-protocol" } dependencies = [ - { name = "anyio", version = "4.14.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.13.14'" }, - { name = "anyio", version = "4.15.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.13.14'" }, { name = "httpx" }, { name = "pydantic" }, { name = "starlette" }, @@ -356,7 +354,6 @@ x11 = [ requires-dist = [ { name = "a2a-sdk", extras = ["http-server"], marker = "extra == 'agent'", specifier = ">=0.3.26,<0.4" }, { name = "a2a-sdk", extras = ["http-server"], marker = "extra == 'dev'", specifier = ">=0.3.26,<0.4" }, - { name = "anyio", specifier = ">=3.6.2" }, { name = "av", marker = "extra == 'computer'", specifier = ">=17" }, { name = "av", marker = "extra == 'dev'", specifier = ">=17" }, { name = "brotli", marker = "extra == 'app'", specifier = ">=1.2" }, From 3722f9b5e134657fc4dd6f55032ecc2cadce9546 Mon Sep 17 00:00:00 2001 From: morningducke <70541786+morningducke@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:01:32 +0300 Subject: [PATCH 7/7] test(protocol): exercise the real transport when checking retry scope --- .../agentenv-protocol/tests/test_connect_retries.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/agentenv-protocol/tests/test_connect_retries.py b/packages/agentenv-protocol/tests/test_connect_retries.py index 07b3f9cde..cb97ac8f4 100644 --- a/packages/agentenv-protocol/tests/test_connect_retries.py +++ b/packages/agentenv-protocol/tests/test_connect_retries.py @@ -68,13 +68,14 @@ def handle(request): @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): - attempts = [] + hosts = [] - def refuse(request): - attempts.append(request) - raise httpx.ConnectError("connection refused") + async def refuse(self, host, **kwargs): + hosts.append(host) + raise httpcore.ConnectError("connection refused") - mock_http(monkeypatch, refuse) + 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, []) @@ -85,7 +86,7 @@ def refuse(request): else: async with ToolSession(mcp_url=_URL + "/mcp"): pytest.fail("MCP initialization should fail") - assert len(attempts) == 1 + assert hosts == ["env.test"] @pytest.mark.asyncio