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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions packages/agentenv-protocol/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,19 @@ extension's, and `client.invoke_extension(base_url, card, uri, params, method=..
its HTTP verb. Without `method`, `invoke_extension` calls the first method listed; an extension
with several methods, such as a gateway's `urn:agentenv:clock/v1`, should always be called by name.

An extension call makes one connection attempt by default. Wrap a call in
`client.retry_extension_connections()` to retry a transient connection failure before sending.

```python
with client.retry_extension_connections():
state = await client.invoke_extension(url, card, "urn:agentenv:clock/v1", {}, method="state")
```

TCP and TLS share the connection budget from `timeout`, including waits of 0.5 and 1 second if
there is time for a second or third attempt. Once the request starts sending, read and write
errors propagate with HTTPX's usual inactivity timeouts. The framework opts in when setting up
the environment clock and tool access.

An extension with several methods is served by giving each handler an `op`. Handlers sharing a URI
merge into one card entry, each method under `params.methods.<op>` with its own verb and endpoint,
by default `/agentenv/ext/<extension>/<op>`, where `<extension>` is the URN's name without
Expand Down
1 change: 1 addition & 0 deletions packages/agentenv-protocol/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ dev = [
"regex>=2023.12.25",
"pytest>=9.0",
"pytest-asyncio>=0.23.0",
"trio>=0.24",
"mcp>=1.25,<2",
"fastmcp>=3.4,<4", # the standalone-fastmcp mount path
"Pillow>=10.4", # the computer extra's frame crops and encodings
Expand Down
66 changes: 66 additions & 0 deletions packages/agentenv-protocol/src/agentenv_protocol/_connect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""Bound connection attempts for an opted-in HTTPX extension call."""

import asyncio
from importlib import import_module
from math import inf, isfinite

import httpx

try:
import sniffio
except ImportError:
sniffio = None


async def send(client: httpx.AsyncClient, request: httpx.Request) -> httpx.Response:
# Match HTTPX's active backend, including a Trio guest task running on an asyncio loop.
trio = import_module("trio") if sniffio is not None and sniffio.current_async_library() == "trio" else None
if trio is None:
now, sleep = asyncio.get_running_loop().time, asyncio.sleep
else:
now, sleep = trio.current_time, trio.sleep

connect_timeout = request.extensions["timeout"]["connect"]
deadline = inf if connect_timeout is None else now() + connect_timeout
sent = False
extensions = request.extensions
previous = extensions.get("trace")

async def trace(event, info):
nonlocal sent, stream
if event.endswith((".connect_tcp.started", ".start_tls.started")) and not sent and isfinite(attempt_deadline):
# TCP and TLS share one attempt's budget, including a TLS handshake through a CONNECT proxy.
info["timeout"] = max(0, attempt_deadline - now())
elif event.endswith((".connect_tcp.complete", ".start_tls.complete")):
stream = info["return_value"]
elif event.endswith(".start_tls.failed") and stream is not None and not isinstance(info["exception"], Exception):
# httpcore hasn't taken ownership of the handshake socket when the caller cancels it.
if trio is None:
await asyncio.shield(stream.aclose())
else:
with trio.CancelScope(shield=True):
await stream.aclose()
elif event.endswith(".send_request_headers.started") and info["request"].method != b"CONNECT":
sent = True
if previous is not None:
await previous(event, info)

request.extensions = {**extensions, "trace": trace}
try:
delays = (0.5, 1.0, None)
for attempt, delay in enumerate(delays):
stream = None
started = now()
remaining = max(0, deadline - started)
share = remaining / (len(delays) - attempt)
attempt_deadline = started + share if delay is not None and share + delay < remaining else deadline
try:
return await client.send(request)
except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
if sent or exc.request is not request or delay is None or now() + delay >= deadline:
raise
await sleep(delay)
if now() >= deadline:
raise
finally:
request.extensions = extensions
18 changes: 17 additions & 1 deletion packages/agentenv-protocol/src/agentenv_protocol/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@

from .manifest import INTERFACE_MANIFEST_PATH
from .transfers import WriteNamespaceGrant
from . import _connect
from .types import CONTROL_TOKEN_HEADER, INTAKE_EXTENSION_URI, MCP_PATH, MCP_TRANSPORT, METHOD_ADD, METHOD_GET, METHOD_RESET, RPC_PATH, WELL_KNOWN_PATH, AddDataResponse, GetDataResponse, Part, ResetDataResponse

logger = logging.getLogger(__name__)

#: The headers that carry the control token of each env address the running code is granted, by address.
_GRANTS: ContextVar[dict[str, dict[str, str]]] = ContextVar("agentenv_control_grants", default={})
_RETRY_EXTENSION_CONNECTIONS = ContextVar("agentenv_retry_extension_connections", default=False)


class ExtensionCallError(httpx.HTTPStatusError):
Expand Down Expand Up @@ -338,6 +340,16 @@ async def get_interface_manifest(base_url: str, interface: str, endpoint: str =
return response.json()


@contextlib.contextmanager
def retry_extension_connections() -> Iterator[None]:
"""Allow up to three connection attempts for extension calls made in this context, before sending the request."""
token = _RETRY_EXTENSION_CONNECTIONS.set(True)
try:
yield
finally:
_RETRY_EXTENSION_CONNECTIONS.reset(token)


async def invoke_extension(base_url: str, card: dict, uri: str, params: dict | None = None, timeout: int = 30, verify: bool = True, *, method: str | None = None,
headers: dict[str, str] | None = None):
"""Invoke a card extension via its advertised REST endpoint.
Expand All @@ -360,7 +372,11 @@ async def invoke_extension(base_url: str, card: dict, uri: str, params: dict | N
url = f"{base_url.rstrip('/')}{op['endpoint']}"
sent = request_headers(url, headers)
async with httpx.AsyncClient(verify=verify) as client:
if op["method"] == "GET":
if _RETRY_EXTENSION_CONNECTIONS.get():
arguments = {"params": params or {}} if op["method"] == "GET" else {"json": params or {}}
request = client.build_request(op["method"], url, headers=sent, timeout=timeout, **arguments)
response = await _connect.send(client, request)
elif op["method"] == "GET":
response = await client.get(url, params=params or {}, timeout=timeout, headers=sent)
else:
response = await client.request(op["method"], url, json=params or {}, timeout=timeout, headers=sent)
Expand Down
185 changes: 185 additions & 0 deletions packages/agentenv-protocol/tests/test_connect_retries.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
"""Opted-in extension calls, through HTTPX's real request and redirect handling."""

import asyncio
from contextlib import nullcontext

import httpcore
import httpx
import pytest
import trio
from httpcore._backends.auto import AutoBackend
from trio.testing import MockClock

from agentenv_protocol import ExtensionCallError, ToolSession, client


_URL = "http://env.test"
_URI = "urn:example:setup/v1"
_CARD = {"capabilities": {"extensions": [{"uri": _URI, "params": {"methods": {
"set": {"method": "POST", "endpoint": "/set"}, "get": {"method": "GET", "endpoint": "/get"},
}}}]}}


async def extension(method="set", timeout=5):
return await client.invoke_extension(_URL, _CARD, _URI, {"value": 1}, timeout=timeout, method=method)


def mock_http(monkeypatch, handle, *, redirects=False):
real = httpx.AsyncClient

def make_client(**kwargs):
kwargs.setdefault("follow_redirects", redirects)
return real(transport=httpx.MockTransport(handle), **kwargs)

monkeypatch.setattr(httpx, "AsyncClient", make_client)


@pytest.mark.asyncio
@pytest.mark.parametrize("method", ["get", "set"])
async def test_only_opted_in_extensions_retry(monkeypatch, method):
attempts, received = [], []

def handle(request):
attempts.append(request)
if len(attempts) == 1:
raise httpx.ConnectTimeout("before sending")
received.append(request)
return httpx.Response(200, json={"ok": True})

mock_http(monkeypatch, handle)
with pytest.raises(httpx.ConnectTimeout):
await extension(method)
assert len(attempts) == 1 and not received
attempts.clear()
with client.retry_extension_connections():
assert await extension(method) == {"ok": True}
assert len(attempts) == 2
[request] = received
if method == "get":
assert request.method == "GET" and request.url.params["value"] == "1"
else:
assert request.method == "POST" and request.content
attempts.clear()
with pytest.raises(httpx.ConnectTimeout):
await extension(method)
assert len(attempts) == 1


@pytest.mark.asyncio
@pytest.mark.parametrize("route", ["data", "card", "manifest", "tool"])
async def test_other_clients_still_make_one_attempt_in_the_retry_context(monkeypatch, route):
hosts = []

async def refuse(self, host, **kwargs):
hosts.append(host)
raise httpcore.ConnectError("connection refused")

monkeypatch.setenv("no_proxy", "*")
monkeypatch.setattr(AutoBackend, "connect_tcp", refuse)
with client.retry_extension_connections(), pytest.raises(httpx.ConnectError):
if route == "data":
await client.add_data(_URL, [])
elif route == "card":
await client.get_card(_URL)
elif route == "manifest":
await client.get_interface_manifest(_URL, "items")
else:
async with ToolSession(mcp_url=_URL + "/mcp"):
pytest.fail("MCP initialization should fail")
assert hosts == ["env.test"]


@pytest.mark.asyncio
@pytest.mark.parametrize("timeout, expected", [(5, 3), (0.25, 1)])
async def test_exhaustion_returns_the_last_connection_error(monkeypatch, timeout, expected):
started = []

def refuse(request):
started.append(asyncio.get_running_loop().time())
raise httpx.ConnectError(f"attempt {len(started)}")

mock_http(monkeypatch, refuse)
with client.retry_extension_connections(), pytest.raises(httpx.ConnectError, match=f"attempt {expected}") as caught:
await extension(timeout=timeout)
assert len(started) == expected and caught.value.request.url.path == "/set"
if expected == 3:
assert started[1] - started[0] >= 0.49 and started[2] - started[1] >= 0.99


@pytest.mark.asyncio
@pytest.mark.parametrize("error", [httpx.ReadTimeout, httpx.WriteTimeout, httpx.PoolTimeout, ExtensionCallError])
async def test_other_errors_propagate_after_one_attempt(monkeypatch, error):
calls = []

def handle(request):
calls.append(request)
if error is ExtensionCallError:
return httpx.Response(503)
raise error("interrupted")

mock_http(monkeypatch, handle)
with client.retry_extension_connections(), pytest.raises(error):
await extension()
assert len(calls) == 1


@pytest.mark.asyncio
async def test_a_failed_redirect_target_does_not_replay_the_first_hop(monkeypatch):
paths = []

def handle(request):
paths.append(request.url.path)
if request.url.path == "/set":
return httpx.Response(307, headers={"Location": "/next"})
raise httpx.ConnectError("redirect target unavailable")

mock_http(monkeypatch, handle, redirects=True)
with client.retry_extension_connections(), pytest.raises(httpx.ConnectError):
await extension()
assert paths == ["/set", "/next"]


@pytest.mark.asyncio
async def test_cancelling_one_opted_in_task_leaves_a_sibling_on_one_attempt(monkeypatch):
failed = asyncio.Event()
attempts = []

def refuse(request):
attempts.append(request)
failed.set()
raise httpx.ConnectError("refused")

mock_http(monkeypatch, refuse)
with client.retry_extension_connections():
task = asyncio.create_task(extension())
await failed.wait()
with pytest.raises(httpx.ConnectError):
await extension()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert len(attempts) == 2


@pytest.mark.parametrize("opt_in", [False, True])
def test_native_trio_uses_its_own_clock_for_backoff(monkeypatch, opt_in):
attempts = []

async def connect(self, host, **kwargs):
attempts.append(trio.current_time())
if len(attempts) == 1:
raise httpcore.ConnectError("connection refused")
return httpcore.AsyncMockStream([b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"])

async def run():
with client.retry_extension_connections() if opt_in else nullcontext():
if opt_in:
assert await extension() == {}
else:
with pytest.raises(httpx.ConnectError):
await extension()

monkeypatch.setenv("no_proxy", "*")
monkeypatch.setattr(AutoBackend, "connect_tcp", connect)
trio.run(run, clock=MockClock(autojump_threshold=0))
assert attempts == ([0, 0.5] if opt_in else [0])
Loading
Loading