diff --git a/tests/http/test_cookies.py b/tests/http/test_cookies.py deleted file mode 100644 index 5bc0ae4f..00000000 --- a/tests/http/test_cookies.py +++ /dev/null @@ -1,42 +0,0 @@ -from __future__ import annotations - -from acp._cookies import MemoryAcpCookieStore - - -def test_store_and_render_single_cookie() -> None: - store = MemoryAcpCookieStore() - store.store_set_cookie("affinity=abc123; Path=/; HttpOnly") - assert store.cookie_header() == "affinity=abc123" - - -def test_store_multiple_cookies_preserves_all() -> None: - store = MemoryAcpCookieStore() - store.store_set_cookies(["a=1; Path=/", "b=2; Secure"]) - assert store.cookie_header() == "a=1; b=2" - - -def test_later_value_overwrites_same_name() -> None: - store = MemoryAcpCookieStore() - store.store_set_cookie("a=1") - store.store_set_cookie("a=2") - assert store.cookie_header() == "a=2" - assert len(store) == 1 - - -def test_empty_store_returns_none() -> None: - store = MemoryAcpCookieStore() - assert store.cookie_header() is None - - -def test_malformed_set_cookie_ignored() -> None: - store = MemoryAcpCookieStore() - store.store_set_cookie("garbage") - store.store_set_cookie("") - assert store.cookie_header() is None - - -def test_clear_drops_all() -> None: - store = MemoryAcpCookieStore() - store.store_set_cookie("a=1") - store.clear() - assert store.cookie_header() is None diff --git a/tests/http/test_fixes.py b/tests/http/test_fixes.py index 6cd63a6c..fafd2121 100644 --- a/tests/http/test_fixes.py +++ b/tests/http/test_fixes.py @@ -1,12 +1,4 @@ -"""Regression tests for reliability fixes on the HTTP/WS transport. - -Covers: -* OutboundStream backpressure (no silent message drops under a full buffer). -* SSE keepalive emission on idle streams. -* HTTP client surfacing disconnect (EOF) when the connection-scoped SSE stream ends. -* Server cleanup of a leaked connection when ``initialize`` fails/times out. -* WebSocket client cookie support (send stored Cookie; capture Set-Cookie). -""" +"""HTTP stream lifecycle and initialization cleanup regressions.""" from __future__ import annotations @@ -20,66 +12,11 @@ import acp.http.server as server_mod from acp.http.client import create_http_stream from acp.http.protocol import CONNECTION_ID_HEADER, CONTENT_TYPE_JSON -from acp.http.server import AcpServer, OutboundStream +from acp.http.server import AcpServer CT_JSON = "application/json" -# -- Finding 1: OutboundStream backpressure ------------------------------------ - - -@pytest.mark.asyncio -async def test_outbound_stream_does_not_drop_beyond_capacity() -> None: - """Pushing more than ``capacity`` messages must not silently drop any. - - With a bounded queue and ``put_nowait``, the (capacity+1)-th message was - dropped. Backpressure-aware push blocks the producer until a consumer drains, - so every message is eventually delivered in order. - """ - stream = OutboundStream(capacity=2) - total = 5 - - async def produce() -> None: - for i in range(total): - await stream.push({"n": i}) - stream.close() - - producer = asyncio.ensure_future(produce()) - received = [msg async for msg in stream.iterate()] - await producer - assert received == [{"n": i} for i in range(total)] - - -@pytest.mark.asyncio -async def test_outbound_stream_push_blocks_when_full() -> None: - """push must not complete once the buffer is full and no consumer drains.""" - stream = OutboundStream(capacity=1) - await stream.push({"n": 0}) # fills the buffer - blocked = asyncio.ensure_future(stream.push({"n": 1})) - await asyncio.sleep(0.05) - assert not blocked.done() - # Draining one message unblocks the producer. - it = stream.iterate() - assert await it.__anext__() == {"n": 0} - await asyncio.wait_for(blocked, timeout=1) - stream.close() - - -# -- Finding 3: SSE keepalive -------------------------------------------------- - - -@pytest.mark.asyncio -async def test_outbound_stream_close_unblocks_full_buffer() -> None: - stream = OutboundStream(capacity=1) - await stream.push({"n": 0}) - blocked = asyncio.create_task(stream.push({"n": 1})) - await asyncio.sleep(0) - assert not blocked.done() - stream.close() - await asyncio.wait_for(blocked, timeout=1) - assert [message async for message in stream.iterate()] == [] - - @pytest.mark.asyncio async def test_open_stream_emits_keepalive_when_idle(monkeypatch: pytest.MonkeyPatch) -> None: """An idle connection-scoped stream must emit periodic SSE keepalive frames.""" @@ -110,25 +47,33 @@ async def drain() -> None: assert any(frame == b": keepalive\n\n" for frame in frames) -# -- Finding 5: initialize failure cleanup ------------------------------------- - - @pytest.mark.asyncio async def test_initialize_timeout_cleans_up_connection(monkeypatch: pytest.MonkeyPatch) -> None: """A hung ``initialize`` must not leak a registered connection.""" monkeypatch.setattr(server_mod, "INITIALIZE_TIMEOUT_SECONDS", 0.1) - server = AcpServer(lambda conn: _SilentInitAgent()) + stopped = asyncio.Event() + + class Agent: + async def initialize(self, protocol_version: int, **kwargs: Any) -> Any: + try: + await asyncio.Event().wait() + finally: + stopped.set() + + server = AcpServer(lambda conn: Agent()) result = await server.handle_post( {"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {"protocolVersion": 1}}, content_type=CT_JSON, connection_id=None, session_id=None, ) - assert result.status_code >= 500 - # No connection should remain registered after a failed initialize. - assert not server._connections - await server.close() + try: + assert result.status_code == 504 + assert CONNECTION_ID_HEADER not in result.headers + assert stopped.is_set() + finally: + await server.close() @pytest.mark.asyncio @@ -137,7 +82,7 @@ async def test_interrupted_initialize_cleans_up_agent(shutdown: bool) -> None: started = asyncio.Event() stopped = asyncio.Event() - class Agent(_SilentInitAgent): + class Agent: async def initialize(self, protocol_version: int = 1, **kwargs: Any) -> Any: started.set() try: @@ -163,15 +108,11 @@ async def initialize(self, protocol_version: int = 1, **kwargs: Any) -> Any: with pytest.raises(asyncio.CancelledError): await asyncio.wait_for(request, timeout=1) assert stopped.is_set() - assert not server._connections finally: request.cancel() await server.close() -# -- Finding 4: HTTP client surfaces disconnect on stream EOF ------------------ - - @pytest.mark.asyncio async def test_http_client_surfaces_eof_when_connection_stream_ends() -> None: """When the connection-scoped SSE stream ends, receive() must return None.""" @@ -219,13 +160,3 @@ async def initialize(self, protocol_version: int = 1, **kwargs: Any) -> Any: from acp.schema import InitializeResponse return InitializeResponse(protocol_version=1) - - -class _SilentInitAgent: - """An agent whose initialize never returns, forcing a server-side timeout.""" - - def on_connect(self, conn: Any) -> None: - pass - - async def initialize(self, protocol_version: int = 1, **kwargs: Any) -> Any: - await asyncio.sleep(3600) diff --git a/tests/http/test_http_client.py b/tests/http/test_http_client.py index cc565c49..99e74add 100644 --- a/tests/http/test_http_client.py +++ b/tests/http/test_http_client.py @@ -9,7 +9,6 @@ import httpx2 import pytest -from acp._sse import serialize_sse_event from acp.connection import Connection from acp.http.client import AcpHttpStatusError, create_http_stream from acp.http.protocol import CONNECTION_ID_HEADER, CONTENT_TYPE_JSON, SESSION_ID_HEADER @@ -65,11 +64,11 @@ async def body() -> Any: return httpx2.Response(200, headers={"Content-Type": "text/event-stream"}, stream=_AsyncByteStream(body())) def push_conn(self, message: dict[str, Any]) -> None: - self.conn_stream.put_nowait(serialize_sse_event(message)) + self.conn_stream.put_nowait(f"data: {json.dumps(message)}\n\n".encode()) def push_session(self, session_id: str, message: dict[str, Any]) -> None: queue = self.session_streams.setdefault(session_id, asyncio.Queue()) - queue.put_nowait(serialize_sse_event(message)) + queue.put_nowait(f"data: {json.dumps(message)}\n\n".encode()) class _AsyncByteStream(httpx2.AsyncByteStream): @@ -137,7 +136,7 @@ async def test_connection_scoped_sse_delivers_new_session_result() -> None: @pytest.mark.asyncio -@pytest.mark.parametrize("payload", [b"[]", b'"text"', b"42"]) +@pytest.mark.parametrize("payload", [b"[]", b'[{"id":2}]', b'"text"', b"42", b"true", b"false", b"null"]) async def test_connection_scoped_sse_skips_non_object_json(payload: bytes) -> None: server = FakeServer() transport, client = _make_transport(server) @@ -337,7 +336,7 @@ async def test_connection_sse_accepts_standard_line_endings(line_ending: str) -> await client.aclose() -@pytest.mark.parametrize("layout", ["cr", "crlf-split", "mixed", "bytewise"]) +@pytest.mark.parametrize("layout", ["cr", "crlf-split", "mixed", "bytewise", "trailing-eof"]) @pytest.mark.asyncio async def test_connection_sse_preserves_split_and_multiline_events(layout: str) -> None: """CRLF split across reads is one ending, including before a second data field.""" @@ -345,7 +344,7 @@ async def test_connection_sse_preserves_split_and_multiline_events(layout: str) transport, client = _make_transport(server) first = {"jsonrpc": "2.0", "method": "_test/update", "params": {"text": "\u4e2d\u6587\u0085\u2028"}} second = {"jsonrpc": "2.0", "method": "_test/done"} - head = 'data: {"jsonrpc":"2.0",' + head = ': keepalive\nevent: message\ndata: {"jsonrpc":"2.0",' tail = 'data: "method":"_test/update","params":{"text":"\u4e2d\u6587\u0085\u2028"}}' last = "data: " + json.dumps(second) if layout == "cr": @@ -362,7 +361,10 @@ async def test_connection_sse_preserves_split_and_multiline_events(layout: str) ] elif layout == "mixed": chunks = [(head + "\r" + tail + "\n\r\n" + last + "\r\r").encode()] + elif layout == "trailing-eof": + chunks = [(head + "\n" + tail + "\n\n" + last + "\n").encode(), None] else: + # The byte-by-byte layout splits multibyte UTF-8 characters across reads. data = (head + "\r\n" + tail + "\r\r" + last + "\n\n").encode() chunks = [data[index : index + 1] for index in range(len(data))] try: diff --git a/tests/http/test_protocol.py b/tests/http/test_protocol.py deleted file mode 100644 index 8b58cba6..00000000 --- a/tests/http/test_protocol.py +++ /dev/null @@ -1,55 +0,0 @@ -from __future__ import annotations - -from acp.http.protocol import ( - INITIALIZE_METHOD, - is_initialize_request, - is_response_message, - message_id_key, - method_requires_session_header, - session_id_from_message, - session_id_from_params, - session_id_from_result, -) - - -def test_is_initialize_request() -> None: - assert is_initialize_request({"method": INITIALIZE_METHOD, "id": 1, "params": {}}) - assert not is_initialize_request({"method": "session/new", "id": 2}) - # A notification (no id) is not a request. - assert not is_initialize_request({"method": INITIALIZE_METHOD}) - - -def test_is_response_message() -> None: - assert is_response_message({"id": 1, "result": {}}) - assert is_response_message({"id": 1, "error": {"code": -1, "message": "x"}}) - assert not is_response_message({"id": 1, "method": "session/prompt"}) - assert not is_response_message({"method": "session/update", "params": {}}) - - -def test_method_requires_session_header() -> None: - assert method_requires_session_header("session/prompt") - assert method_requires_session_header("session/cancel") - assert method_requires_session_header("session/set_mode") - # Connection-level methods (and session-establishing ones) do not require the header. - assert not method_requires_session_header("initialize") - assert not method_requires_session_header("session/new") - assert not method_requires_session_header("session/load") - assert not method_requires_session_header("session/list") - assert not method_requires_session_header(None) - - -def test_message_id_key_normalizes_int_and_str() -> None: - assert message_id_key(1) == "1" - assert message_id_key("1") == "1" - assert message_id_key(1) == message_id_key("1") - assert message_id_key(None) is None - - -def test_session_id_extraction() -> None: - assert session_id_from_params({"sessionId": "s1"}) == "s1" - assert session_id_from_params({}) is None - assert session_id_from_params(None) is None - assert session_id_from_result({"sessionId": "s2"}) == "s2" - assert session_id_from_message({"params": {"sessionId": "s3"}}) == "s3" - assert session_id_from_message({"result": {"sessionId": "s4"}}) == "s4" - assert session_id_from_message({"result": {}}) is None diff --git a/tests/http/test_sse.py b/tests/http/test_sse.py deleted file mode 100644 index cc1e1704..00000000 --- a/tests/http/test_sse.py +++ /dev/null @@ -1,82 +0,0 @@ -from __future__ import annotations - -from collections.abc import AsyncIterator - -import pytest - -from acp._sse import parse_sse_stream, serialize_sse_event, serialize_sse_keepalive - - -def test_serialize_sse_event_frames_json_with_blank_line() -> None: - frame = serialize_sse_event({"jsonrpc": "2.0", "id": 1, "result": {"ok": True}}) - assert frame == b'data: {"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n\n' - - -def test_serialize_sse_keepalive_is_a_comment() -> None: - assert serialize_sse_keepalive() == b": keepalive\n\n" - - -async def _aiter(chunks: list[bytes]) -> AsyncIterator[bytes]: - for chunk in chunks: - yield chunk - - -@pytest.mark.asyncio -async def test_parse_single_event() -> None: - stream = _aiter([b'data: {"id":1}\n\n']) - events = [event async for event in parse_sse_stream(stream)] - assert events == [{"id": 1}] - - -@pytest.mark.asyncio -async def test_parse_multiple_events_split_across_chunks() -> None: - stream = _aiter([b'data: {"id', b'":1}\n\ndata: {"id":2}', b"\n\n"]) - events = [event async for event in parse_sse_stream(stream)] - assert events == [{"id": 1}, {"id": 2}] - - -@pytest.mark.asyncio -async def test_parse_multibyte_utf8_split_across_chunks() -> None: - frame = 'data: {"text":"你好"}\n\n'.encode() - split_at = frame.index("你".encode()) + 1 - stream = _aiter([frame[:split_at], frame[split_at:]]) - - events = [event async for event in parse_sse_stream(stream)] - - assert events == [{"text": "你好"}] - - -@pytest.mark.asyncio -async def test_parse_ignores_comments_and_other_fields() -> None: - stream = _aiter([b': keepalive\n\nevent: message\ndata: {"id":7}\n\n']) - events = [event async for event in parse_sse_stream(stream)] - assert events == [{"id": 7}] - - -@pytest.mark.asyncio -async def test_parse_multiline_data_is_joined() -> None: - stream = _aiter([b'data: {"a":1,\ndata: "b":2}\n\n']) - events = [event async for event in parse_sse_stream(stream)] - assert events == [{"a": 1, "b": 2}] - - -@pytest.mark.asyncio -async def test_parse_flushes_trailing_event_without_blank_line() -> None: - stream = _aiter([b'data: {"id":9}\n']) - events = [event async for event in parse_sse_stream(stream)] - assert events == [{"id": 9}] - - -@pytest.mark.asyncio -async def test_parse_skips_invalid_json() -> None: - stream = _aiter([b'data: not-json\n\ndata: {"id":1}\n\n']) - events = [event async for event in parse_sse_stream(stream)] - assert events == [{"id": 1}] - - -@pytest.mark.asyncio -@pytest.mark.parametrize("payload", [b"[]", b'[ {"id":2} ]', b'"text"', b"42", b"true", b"false", b"null"]) -async def test_parse_skips_non_object_json(payload: bytes) -> None: - stream = _aiter([b"data: " + payload + b'\n\ndata: {"id":1}\n\n']) - events = [event async for event in parse_sse_stream(stream)] - assert events == [{"id": 1}] diff --git a/tests/http/test_websocket.py b/tests/http/test_websocket.py index 5bbddd27..600458d1 100644 --- a/tests/http/test_websocket.py +++ b/tests/http/test_websocket.py @@ -13,7 +13,6 @@ from websockets.asyncio.server import serve from websockets.protocol import State -from acp.connection import Connection from acp.http.protocol import CONNECTION_ID_HEADER from acp.schema import NewSessionResponse, PromptResponse from acp.ws.client import create_websocket_stream @@ -112,26 +111,6 @@ async def send_frames(ws: Any) -> None: await transport.close() -@pytest.mark.asyncio -@pytest.mark.parametrize("frame", ["null", "[]", "{}"]) -async def test_client_connection_recovers_after_invalid_frame(frame: str) -> None: - async def respond(ws: Any) -> None: - request = json.loads(await ws.recv()) - await ws.send(frame) - await ws.send(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": {"protocolVersion": 1}})) - await ws.wait_closed() - - async def handler(method: str, params: Any, is_notification: bool) -> None: - pass - - async with serve(respond, "127.0.0.1", 0) as server: - port = server.sockets[0].getsockname()[1] - transport = await create_websocket_stream(f"ws://127.0.0.1:{port}") - async with Connection(handler, transport) as conn: - result = await asyncio.wait_for(conn.send_request("initialize", {"protocolVersion": 1}), timeout=1) - assert result == {"protocolVersion": 1} - - @pytest.mark.asyncio @pytest.mark.parametrize( ("frame", "code", "message"), diff --git a/tests/http/test_ws_cookies.py b/tests/http/test_ws_cookies.py index a5fdd899..d50dd41b 100644 --- a/tests/http/test_ws_cookies.py +++ b/tests/http/test_ws_cookies.py @@ -1,8 +1,9 @@ -"""WebSocket client cookie support (RFD §5: cookies MUST work on WS transport).""" +"""WebSocket clients carry cookies from one handshake to the next.""" from __future__ import annotations import asyncio +from http.cookies import SimpleCookie from typing import Any import pytest @@ -13,43 +14,33 @@ @pytest.mark.asyncio -async def test_ws_client_captures_set_cookie_from_handshake() -> None: - """A caller-owned cookie store must capture Set-Cookie from the upgrade response.""" +async def test_ws_client_carries_cookies_between_handshakes() -> None: + seen: asyncio.Queue[str | None] = asyncio.Queue() def process_response(connection: Any, request: Any, response: Any) -> Any: - response.headers["Set-Cookie"] = "affinity=abc123; Path=/" + response.headers["Set-Cookie"] = "affinity=old; Path=/" + response.headers["Set-Cookie"] = "flavor=blue; HttpOnly" + response.headers["Set-Cookie"] = "affinity=new; Path=/" + response.headers["Set-Cookie"] = "malformed" return response async def handler(ws: Any) -> None: + seen.put_nowait(ws.request.headers.get("Cookie")) await ws.close() store = MemoryAcpCookieStore() - async with serve(handler, "localhost", 0, process_response=process_response) as server: + async with serve(handler, "127.0.0.1", 0, process_response=process_response) as server: port = server.sockets[0].getsockname()[1] - transport = await create_websocket_stream(f"ws://localhost:{port}", cookie_store=store) + url = f"ws://127.0.0.1:{port}" + transport = await create_websocket_stream(url, cookie_store=store) try: - assert store.cookie_header() == "affinity=abc123" + assert await asyncio.wait_for(seen.get(), timeout=1) is None finally: await transport.close() - -@pytest.mark.asyncio -async def test_ws_client_sends_stored_cookie_on_handshake() -> None: - """Stored cookies must be echoed back as a Cookie header on the next handshake.""" - seen: dict[str, Any] = {} - - async def handler(ws: Any) -> None: - seen["cookie"] = ws.request.headers.get("Cookie") - await ws.close() - - store = MemoryAcpCookieStore() - store.store_set_cookie("affinity=abc123") - - async with serve(handler, "localhost", 0) as server: - port = server.sockets[0].getsockname()[1] - transport = await create_websocket_stream(f"ws://localhost:{port}", cookie_store=store) + transport = await create_websocket_stream(url, cookie_store=store) try: - await asyncio.sleep(0.05) - assert seen.get("cookie") == "affinity=abc123" + cookies = SimpleCookie(await asyncio.wait_for(seen.get(), timeout=1)) + assert {name: cookie.value for name, cookie in cookies.items()} == {"affinity": "new", "flavor": "blue"} finally: await transport.close() diff --git a/tests/real_user/test_stdio_writer.py b/tests/real_user/test_stdio_writer.py index 6f0a843e..23130271 100644 --- a/tests/real_user/test_stdio_writer.py +++ b/tests/real_user/test_stdio_writer.py @@ -1,5 +1,6 @@ import asyncio import io +import json import subprocess import sys import textwrap @@ -100,3 +101,68 @@ def write(self, data: bytes) -> int: writer.close() await asyncio.wait_for(writer.wait_closed(), timeout=2) assert output.getvalue() == b"hello" + + +@pytest.mark.skipif(sys.platform == "win32", reason="native POSIX pipe transport") +@pytest.mark.parametrize("disconnect", [False, True], ids=["cancelled_send", "broken_pipe"]) +def test_connection_sends_settle_after_pipe_stalls(disconnect: bool) -> None: + script = textwrap.dedent(f""" + import asyncio + import contextlib + import sys + + from acp.connection import Connection + from acp.stdio import stdio_streams + + async def handler(method, params, is_notification): + raise AssertionError("unexpected inbound message") + + async def main(): + reader, writer = await stdio_streams() + try: + async with Connection(handler, writer, reader, listening=False) as conn: + first = asyncio.create_task(conn.send_notification("first", {{"data": "x" * (1024 * 1024)}})) + second = asyncio.create_task(conn.send_notification("second")) + await asyncio.sleep(0) + assert not first.done() and not second.done() + print("ready", file=sys.stderr, flush=True) + if {disconnect!r}: + errors = await asyncio.wait_for(asyncio.gather(first, second, return_exceptions=True), 2) + assert all(isinstance(error, ConnectionError) for error in errors), errors + try: + await asyncio.wait_for(conn.send_notification("later"), 2) + except ConnectionError: + pass + else: + raise AssertionError("send succeeded after the pipe broke") + else: + first.cancel() + with contextlib.suppress(asyncio.CancelledError): + await first + await asyncio.wait_for(second, 2) + await asyncio.wait_for(conn.send_notification("later"), 2) + finally: + writer.close() + with contextlib.suppress(ConnectionError): + await asyncio.wait_for(writer.wait_closed(), 2) + + asyncio.run(main()) + """) + with subprocess.Popen( # noqa: S603 + [sys.executable, "-c", script], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) as child: + assert child.stdout is not None + assert child.stderr is not None + try: + assert child.stderr.readline() == b"ready\n" + if disconnect: + child.stdout.close() + assert child.wait(timeout=10) == 0, child.stderr.read().decode() + else: + output, errors = child.communicate(timeout=10) + assert child.returncode == 0, errors.decode() + assert [json.loads(line)["method"] for line in output.splitlines()] == ["first", "second", "later"] + finally: + if child.poll() is None: + child.kill() + child.wait(timeout=5) diff --git a/tests/test_connection_recovery.py b/tests/test_connection_recovery.py index 3728c129..e0738de5 100644 --- a/tests/test_connection_recovery.py +++ b/tests/test_connection_recovery.py @@ -1,234 +1,95 @@ from __future__ import annotations import asyncio -import contextlib import json from collections.abc import Callable from typing import Any -from unittest.mock import AsyncMock, MagicMock import pytest -from acp._transport import memory_transport_pair from acp.agent.connection import AgentSideConnection from acp.client.connection import ClientSideConnection from acp.connection import Connection from acp.exceptions import RequestError from acp.experimental import v2 +LARGE_PARAMS = "x" * (70 * 1024) + @pytest.mark.asyncio @pytest.mark.parametrize( "connect", [AgentSideConnection, ClientSideConnection, v2.AgentSideConnection, v2.ClientSideConnection] ) async def test_on_connect_failure_does_not_start_receiving(connect: Callable[..., Any]) -> None: + received = asyncio.Event() + + class Transport: + async def receive(self) -> None: + received.set() + await asyncio.Event().wait() + + async def send(self, message: dict[str, Any]) -> None: + pytest.fail(f"Unexpected message: {message}") + + async def close(self) -> None: + pass + class FailingHooks: def on_connect(self, connection: Any) -> None: self.connection = connection raise RuntimeError("on_connect failed") - peer, transport = memory_transport_pair() hooks = FailingHooks() - tasks = asyncio.all_tasks() try: with pytest.raises(RuntimeError, match="on_connect failed"): - connect(hooks, transport) - assert asyncio.all_tasks() == tasks + connect(hooks, Transport()) + await asyncio.sleep(0) + assert not received.is_set() finally: await hooks.connection.close() - await peer.close() - - -async def _noop_handler(method: str, params: Any, is_notification: bool) -> Any: - return None - - -def _make_connection( - *, - limit: int = 128, - receive_timeout: float | None = None, -) -> tuple[Connection, asyncio.StreamReader]: - reader = asyncio.StreamReader(limit=limit) - transport = MagicMock() - transport.is_closing.return_value = False - protocol = AsyncMock() - writer = asyncio.StreamWriter(transport, protocol, reader, asyncio.get_running_loop()) - conn = Connection(_noop_handler, writer, reader, listening=False, receive_timeout=receive_timeout) - return conn, reader - - -@pytest.mark.asyncio -async def test_receive_loop_handles_oversized_frame(caplog: pytest.LogCaptureFixture) -> None: - conn, reader = _make_connection(limit=128) - processed: list[str] = [] - - def tracking_process(message: dict[str, Any]) -> None: - processed.append(message["method"]) - - conn._process_message = tracking_process # type: ignore[method-assign] - oversized = {"jsonrpc": "2.0", "method": "too-large", "params": {"data": "X" * 256}} - survivor = {"jsonrpc": "2.0", "method": "survivor"} - reader.feed_data(json.dumps(oversized).encode() + b"\n" + json.dumps(survivor).encode() + b"\n") - reader.feed_eof() - - with caplog.at_level("WARNING"): - await conn._receive_loop() - await conn.close() - - assert processed == ["too-large", "survivor"] - assert "oversized JSON-RPC frame" not in caplog.text - - -@pytest.mark.asyncio -async def test_receive_loop_handles_consecutive_oversized_frames() -> None: - conn, reader = _make_connection(limit=128) - processed: list[str] = [] - - def tracking_process(message: dict[str, Any]) -> None: - processed.append(message["method"]) - conn._process_message = tracking_process # type: ignore[method-assign] - for index in range(2): - oversized = {"jsonrpc": "2.0", "method": f"too-large-{index}", "params": {"data": "Y" * 256}} - reader.feed_data(json.dumps(oversized).encode() + b"\n") - survivor = {"jsonrpc": "2.0", "method": "survivor"} - reader.feed_data(json.dumps(survivor).encode() + b"\n") - reader.feed_eof() - await conn._receive_loop() - await conn.close() - - assert processed == ["too-large-0", "too-large-1", "survivor"] +async def _summarize(method: str, params: Any, is_notification: bool) -> Any: + return {"length": len(params["data"]), "last": params["data"][-1]} @pytest.mark.asyncio -async def test_receive_loop_handles_eof_during_oversized_frame() -> None: - conn, reader = _make_connection(limit=64) - reader.feed_data(b"X" * 256) - reader.feed_eof() - - await conn._receive_loop() - await conn.close() +async def test_consecutive_large_frames_reach_handler(server) -> None: + payloads = [{"data": LARGE_PARAMS}, {"data": LARGE_PARAMS + "2"}, {"data": "next"}] + frames = [ + {"jsonrpc": "2.0", "id": index, "method": "echo", "params": params} for index, params in enumerate(payloads) + ] + async with Connection(_summarize, server.client_writer, server.client_reader): + server.server_writer.writelines((json.dumps(frame) + "\n").encode() for frame in frames) + await server.server_writer.drain() + replies = [json.loads(await asyncio.wait_for(server.server_reader.readline(), timeout=1)) for _ in frames] - assert conn._disconnected is True + assert {reply["id"]: reply["result"] for reply in replies} == { + index: {"length": len(params["data"]), "last": params["data"][-1]} for index, params in enumerate(payloads) + } @pytest.mark.asyncio -async def test_receive_loop_keeps_timeout_semantics() -> None: - conn, _reader = _make_connection(receive_timeout=0.01) - - with pytest.raises(RequestError) as exc_info: - await conn._receive_loop() - await conn.close() +async def test_eof_during_large_frame_rejects_pending_request(server) -> None: + async with Connection(_summarize, server.client_writer, server.client_reader) as conn: + request = asyncio.create_task(conn.send_request("probe")) + await asyncio.wait_for(server.server_reader.readline(), timeout=1) + server.server_writer.write(('{"jsonrpc":"2.0","result":"' + LARGE_PARAMS).encode()) + server.server_writer.write_eof() - exc = exc_info.value - assert isinstance(exc, RequestError) - assert str(exc) == "Internal error" - assert exc.data == {"details": "Agent timeout"} + with pytest.raises(ConnectionError, match="Connection closed"): + await asyncio.wait_for(request, timeout=1) @pytest.mark.asyncio -async def test_receive_loop_keeps_timeout_semantics_while_reading_oversized_frame() -> None: - conn, reader = _make_connection(limit=64, receive_timeout=0.01) - reader.feed_data(b"X" * 256) - - with pytest.raises(RequestError) as exc_info: - await conn._receive_loop() - await conn.close() - - exc = exc_info.value - assert isinstance(exc, RequestError) - assert exc.data == {"details": "Agent timeout"} - - -@pytest.mark.asyncio -async def test_receive_loop_does_not_swallow_unrelated_reader_error() -> None: - conn, reader = _make_connection() - reader.set_exception(ValueError("reader failed")) - - with pytest.raises(ValueError, match="reader failed"): - await conn._receive_loop() - await conn.close() - - -@pytest.mark.asyncio -async def test_receive_loop_ignores_frames_that_are_not_json_objects() -> None: - """A line can be valid JSON and still not be a JSON-RPC message. - - Unparsable input is already skipped by ``NdjsonTransport.receive``. These frames parse - fine but are not objects: an array, a number, a string and ``null``. Without the object - guard they reach ``Connection._process_message`` -- which calls ``message.get(...)`` -- - or, for ``null``, are read as the transport's EOF signal. Either way the connection dies - and the valid frame queued behind them is never handled. - """ - conn, reader = _make_connection() - processed: list[str] = [] - - def tracking_process(message: dict[str, Any]) -> None: - processed.append(message["method"]) - - conn._process_message = tracking_process # type: ignore[method-assign] - non_objects = b"\n".join([b"[]", b"123", b'"x"', b"null", b"", b"not json at all"]) - survivor = {"jsonrpc": "2.0", "method": "survivor"} - reader.feed_data(non_objects + b"\n" + json.dumps(survivor).encode() + b"\n") - reader.feed_eof() - - await conn._receive_loop() - await conn.close() - - assert processed == ["survivor"] - - -@pytest.mark.asyncio -async def test_receive_loop_ignores_responses_with_an_invalid_id() -> None: - """A response whose ``id`` is not a ``RequestId`` must not answer anyone. - - ``_handle_response`` looks the id up in ``_pending``. An array or an object raises there, - which escapes the receive loop, disconnects, and leaves the valid frame behind it - unhandled. ``true`` and ``1.0`` are worse than a crash: they are equal to the integer - ``1``, so they resolve a different request's future -- the aliasing ``_track_incoming`` - already refuses on the way out. - """ - conn, reader = _make_connection() - original = asyncio.get_running_loop().create_future() - conn._pending[1] = original - # The real dispatch is left in place: a response reaches ``_handle_response``, which is - # where the id is used. The loop is not fed EOF, so it stays alive and ``_disconnect`` - # does not reject the pending future before it can be inspected. - handled: list[str] = [] - real_track = conn._track_incoming - - def tracking_track(request_id: Any, task: asyncio.Task[Any]) -> None: - handled.append("request") - real_track(request_id, task) - - conn._track_incoming = tracking_track # type: ignore[method-assign] - - invalid = b"\n".join([ - json.dumps({"jsonrpc": "2.0", "id": [], "result": "array"}).encode(), - json.dumps({"jsonrpc": "2.0", "id": {}, "result": "object"}).encode(), - json.dumps({"jsonrpc": "2.0", "id": True, "result": "aliased"}).encode(), - json.dumps({"jsonrpc": "2.0", "id": 1.0, "result": "aliased"}).encode(), - ]) - survivor = {"jsonrpc": "2.0", "method": "survivor", "id": 2} - reader.feed_data(invalid + b"\n" + json.dumps(survivor).encode() + b"\n") - - loop_task = asyncio.create_task(conn._receive_loop()) - for _ in range(200): - await asyncio.sleep(0) - if handled and 1 not in conn._incoming: - break - - # None of the four bad ids answered the integer-1 request, and the loop kept going: the - # valid request behind them was dispatched. Request 2 answers nothing and is cleaned up, - # so only the unanswered request 1 remains pending. - assert not original.done() - assert sorted(conn._pending) == [1] - assert handled == ["request"] - - loop_task.cancel() - with contextlib.suppress(asyncio.CancelledError): - await loop_task - - conn._pending.clear() - await conn.close() +@pytest.mark.parametrize("partial_frame", [False, True]) +async def test_receive_timeout_is_reported_by_main_loop(server, partial_frame: bool) -> None: + async with Connection( + _summarize, server.client_writer, server.client_reader, listening=False, receive_timeout=0.1 + ) as conn: + if partial_frame: + server.server_writer.write(('{"jsonrpc":"2.0","result":"' + LARGE_PARAMS).encode()) + await server.server_writer.drain() + + with pytest.raises(RequestError, check=lambda error: error.data == {"details": "Agent timeout"}): + await asyncio.wait_for(conn.main_loop(), timeout=1) diff --git a/tests/test_deserialize.py b/tests/test_deserialize.py index dc3e7ad1..f0f1a8da 100644 --- a/tests/test_deserialize.py +++ b/tests/test_deserialize.py @@ -1,53 +1,20 @@ -"""Regression tests for lenient deserialization restored by ``acp._deserialize`` and the -validators ``scripts/gen_schema.py`` injects: ``x-deserialize-default-on-error`` (salvage a -malformed field to its default) and ``x-deserialize-skip-invalid-items`` (drop bad array -items). Mirrors the TypeScript SDK's ``src/schema-deserialize.test.ts``. -""" - -from typing import Any +"""Public v1 schema contracts for lenient deserialization.""" import pytest -from pydantic import BaseModel, ValidationError, field_validator +from pydantic import ValidationError -from acp._deserialize import salvage_on_error, skip_invalid_items from acp.schema import ( HttpHeader, HttpMcpServer, McpServerHttp, NewSessionRequest, + TextContentBlock, ToolCallLocation, ToolCallUpdate, WriteTextFileRequest, ) -class _Salvage(BaseModel): - n: int | None = None - - @field_validator("n", mode="wrap") - @classmethod - def _v(cls, value: Any, handler: Any) -> Any: - return salvage_on_error(value, handler, lambda: None) - - -def test_salvage_on_error_replaces_invalid_value() -> None: - assert _Salvage.model_validate({"n": "not-an-int"}).n is None - assert _Salvage.model_validate({"n": 7}).n == 7 - - -class _Skip(BaseModel): - xs: list[int] = [] - - @field_validator("xs", mode="wrap") - @classmethod - def _v(cls, value: Any, handler: Any) -> Any: - return skip_invalid_items(value, handler) - - -def test_skip_invalid_items_drops_bad_entries() -> None: - assert _Skip.model_validate({"xs": [1, "bad", 3]}).xs == [1, 3] - - def test_meta_is_salvaged_to_none() -> None: request = WriteTextFileRequest.model_validate({ "sessionId": "s", @@ -77,33 +44,11 @@ def test_dual_annotated_optional_list_salvages_a_malformed_container() -> None: assert update.locations is None -class _Item(BaseModel): - n: int - - -class _Other(BaseModel): - s: str - - -class _SkipModels(BaseModel): - xs: list[_Item] = [] - - @field_validator("xs", mode="wrap") - @classmethod - def _v(cls, value: Any, handler: Any) -> Any: - return skip_invalid_items(value, handler) - - -def test_skip_invalid_items_raises_for_local_model_instances() -> None: - # Wire data (dicts) stays lenient... - assert _SkipModels.model_validate({"xs": [{"n": 1}, {"bogus": 1}]}).xs == [_Item(n=1)] - # ...but a wrong model built in code is a programming error, not data from a newer peer. - with pytest.raises(ValidationError): - _SkipModels(xs=[_Item(n=1), _Other(s="x")]) # type: ignore[list-item] +def test_tool_call_update_rejects_incompatible_local_location_model() -> None: with pytest.raises(ValidationError): ToolCallUpdate( tool_call_id="t", - locations=(ToolCallLocation(path="/p"), _Other(s="x")), # type: ignore[arg-type] + locations=[ToolCallLocation(path="/p"), TextContentBlock(text="x")], # type: ignore[list-item] ) diff --git a/tests/test_elicitation_catchall.py b/tests/test_elicitation_catchall.py index 7c35c284..bf6778d2 100644 --- a/tests/test_elicitation_catchall.py +++ b/tests/test_elicitation_catchall.py @@ -5,14 +5,15 @@ known values must still resolve to their specific typed variant. """ -from typing import get_type_hints +import asyncio +from typing import cast, get_type_hints import pytest from pydantic import TypeAdapter, ValidationError -from acp import Client -from acp._protocol_adapters import _mode_from_create_elicitation_request +from acp import Client, connect_to_agent from acp.agent.connection import AgentSideConnection +from acp.connection import Connection from acp.exceptions import RequestError from acp.schema import ( AcceptElicitationResponse, @@ -88,19 +89,42 @@ def test_custom_elicitation_request_preserves_mode_and_payload() -> None: assert parsed.model_dump(by_alias=True)["codec"] == "opus" -def test_unknown_elicitation_mode_dispatches_to_clean_request_error() -> None: - # A custom mode parses (above); the client router must then reject it with a clean - # RequestError (invalid params) rather than a bare TypeError that surfaces as an - # opaque -32603 internal error. - request = _REQUEST.validate_python({ - "mode": "x-voice", - "message": "hi", - "sessionId": "sess-1", - }) - with pytest.raises(RequestError) as exc_info: - _mode_from_create_elicitation_request(request) - assert isinstance(exc_info.value, RequestError) - assert exc_info.value.code == -32602 +@pytest.mark.asyncio +@pytest.mark.parametrize("legacy", [False, True]) +async def test_custom_elicitation_mode_dispatches_over_the_wire(server, legacy: bool) -> None: + class ModernClient(Client): + async def create_elicitation(self, **kwargs): + pytest.fail("Unsupported modes must fail before invoking the handler") + + class LegacyClient: + def on_connect(self, conn): + pass + + async def createElicitation(self, params): + assert isinstance(params, CreateOtherElicitationRequest) + assert params.mode == "x-voice" + return {"action": "decline"} + + async def handler(method, params, is_notification): + pytest.fail(f"Unexpected incoming method: {method}") + + async with ( + connect_to_agent( + cast(Client, LegacyClient()) if legacy else ModernClient(), + server.client_writer, + server.client_reader, + use_unstable_protocol=True, + ), + Connection(handler, server.server_writer, server.server_reader) as peer, + ): + payload = {"mode": "x-voice", "message": "hi", "sessionId": "s"} + request = peer.send_request("elicitation/create", payload) + if legacy: + with pytest.warns(DeprecationWarning): + assert await asyncio.wait_for(request, timeout=1) == {"action": "decline"} + else: + with pytest.raises(RequestError, check=lambda error: error.code == -32602): + await asyncio.wait_for(request, timeout=1) def test_elicitation_property_schema_catchall() -> None: diff --git a/tests/test_gen_all.py b/tests/test_gen_all.py index d53cb2a5..20686fbd 100644 --- a/tests/test_gen_all.py +++ b/tests/test_gen_all.py @@ -1,81 +1,14 @@ +"""Verify that the published method signatures match the checked-in schemas.""" + from pathlib import Path from shutil import copytree import pytest -from acp.schema import ReadTextFileRequest -from scripts.gen_all import ROOT, resolve_ref, schema_source_paths -from scripts.gen_meta import generate_meta -from scripts.gen_schema import generate_schema +from scripts.gen_all import ROOT from scripts.gen_signature import gen_signature -def test_generated_field_descriptions_are_introspectable() -> None: - path_description = "Absolute path to the file to read." - assert ReadTextFileRequest.model_fields["path"].description == path_description - assert ReadTextFileRequest.model_json_schema()["properties"]["path"]["description"] == path_description - - -def test_resolve_ref_accepts_schema_release_tags() -> None: - assert resolve_ref("schema-v1.16.0") == "refs/tags/schema-v1.16.0" - assert resolve_ref("schema-v2.0.0-alpha.3") == "refs/tags/schema-v2.0.0-alpha.3" - - -def test_resolve_ref_keeps_legacy_version_tags() -> None: - assert resolve_ref("0.13.6") == "refs/tags/v0.13.6" - assert resolve_ref("v0.13.6") == "refs/tags/v0.13.6" - - -def test_schema_release_tags_prefer_v1_schema_layout() -> None: - assert schema_source_paths("refs/tags/schema-v1.16.0")[0] == ( - "schema/v1/schema.unstable.json", - "schema/v1/meta.unstable.json", - ) - - -def test_v2_generation_uses_v2_schema_layout() -> None: - assert schema_source_paths("refs/tags/schema-v2.0.0-alpha.3", 2) == ( - ("schema/v2/schema.unstable.json", "schema/v2/meta.unstable.json"), - ) - - -def test_legacy_tags_keep_legacy_schema_layout_first() -> None: - assert schema_source_paths("refs/tags/v0.13.6")[0] == ( - "schema/schema.unstable.json", - "schema/meta.unstable.json", - ) - - -def test_parse_args_formats_output_by_default(monkeypatch) -> None: - from scripts import gen_all - - monkeypatch.setattr("sys.argv", ["gen_all.py"]) - assert gen_all.parse_args().format_output is True - - -def test_parse_args_can_skip_format(monkeypatch) -> None: - from scripts import gen_all - - monkeypatch.setattr("sys.argv", ["gen_all.py", "--no-format"]) - assert gen_all.parse_args().format_output is False - - -def test_codegen_check_is_clean_and_read_only() -> None: - outputs = ( - Path("src/acp/meta.py"), - Path("src/acp/schema.py"), - Path("src/acp/experimental/v2/meta.py"), - Path("src/acp/experimental/v2/schema.py"), - ) - before = {output: output.read_bytes() for output in outputs} - - assert generate_schema(check=True) - assert generate_meta(check=True) - assert generate_schema(check=True, protocol_version=2) - assert generate_meta(check=True, protocol_version=2) - assert {output: output.read_bytes() for output in outputs} == before - - @pytest.mark.parametrize("protocol_version", [1, 2]) def test_generated_signatures_are_in_sync(tmp_path: Path, protocol_version: int) -> None: source = ROOT / "src" / "acp" @@ -88,170 +21,3 @@ def test_generated_signatures_are_in_sync(tmp_path: Path, protocol_version: int) for output in generated.rglob("*.py"): relative_path = output.relative_to(generated) assert output.read_bytes() == (source / relative_path).read_bytes(), relative_path - - -def test_signature_generation_preserves_inline_literal_values() -> None: - import ast - from typing import Literal, get_type_hints - - from scripts.gen_signature import NodeTransformer - - tree = ast.parse( - "from typing import Any\n" - "from schema import SetProviderRequest, StringPropertySchema\n" - "class Methods:\n" - ' @param_model(SetProviderRequest, method="providers/set", unstable=True)\n' - " async def set_provider(self, **kwargs: Any): ...\n" - " @param_model(StringPropertySchema)\n" - " async def string_property(self, **kwargs: Any): ...\n" - ) - NodeTransformer().visit(tree) - ast.fix_missing_locations(tree) - # Evaluate the annotation itself to catch unquoted literal values and ensure - # generation adds the required typing import. - typing_import = tree.body[0] - assert isinstance(typing_import, ast.ImportFrom) - assert "Literal" in {alias.name for alias in typing_import.names} - methods = tree.body[-1] - assert isinstance(methods, ast.ClassDef) - provider = methods.body[0] - assert isinstance(provider, ast.AsyncFunctionDef) - decorator = provider.decorator_list[0] - assert isinstance(decorator, ast.Call) - assert {keyword.arg: ast.literal_eval(keyword.value) for keyword in decorator.keywords} == { - "method": "providers/set", - "unstable": True, - } - # Schema 1.33 removed SuggestNesRequest. StringPropertySchema.format is a multi-value Literal with no schema alias. - choose = methods.body[-1] - assert isinstance(choose, ast.AsyncFunctionDef) - fmt = next(arg for arg in choose.args.args + choose.args.kwonlyargs if arg.arg == "format") - annotation = ast.unparse(fmt.annotation) - - class Annotated: - __annotations__ = {"format": annotation} - - assert ( - get_type_hints(Annotated, globalns={"Literal": Literal})["format"] - == Literal["email", "uri", "date", "date-time"] | None - ) - - -@pytest.mark.parametrize( - "expression", - [ - "SetSessionConfigOptionBooleanRequest | SetSessionConfigOptionSelectRequest", - "Union[SetSessionConfigOptionBooleanRequest, SetSessionConfigOptionSelectRequest]", - "Annotated[SetSessionConfigOptionBooleanRequest | SetSessionConfigOptionSelectRequest, Field(discriminator='type')]", - "RequestAlias", - "CreateElicitationRequest", - ], -) -def test_signature_generation_preserves_union_signatures(expression) -> None: - import ast - - from scripts.gen_signature import NodeTransformer - - tree = ast.parse( - "from typing import Annotated, Any, Union\n" - "from schema import SetSessionConfigOptionBooleanRequest, SetSessionConfigOptionSelectRequest, CreateElicitationRequest\n" - "RequestAlias = SetSessionConfigOptionBooleanRequest | SetSessionConfigOptionSelectRequest\n" - "class Methods:\n" - f" @param_model({expression}, method='example/request')\n" - " async def request(self, config_id: str, session_id: str, value: str | bool, **kwargs: Any): ...\n" - ) - before = ast.dump(tree) - NodeTransformer().visit(tree) - assert ast.dump(tree) == before - - -def test_signature_generation_reuses_named_union_aliases() -> None: - import ast - from types import SimpleNamespace - from typing import Annotated - - from pydantic import BaseModel - - from scripts.gen_signature import NodeTransformer - - class Request(BaseModel): - value: int | str - optional_value: str | int | None = None - - schema = SimpleNamespace(Request=Request, Value=Annotated[str | int, "value"]) - tree = ast.parse("from .schema import Request\n@param_model(Request)\nasync def request(self): ...\n") - NodeTransformer(schema).visit(tree) - ast.fix_missing_locations(tree) - assert ast.unparse(tree) == ( - "from .schema import Request, Value\n\n" - "@param_model(Request)\n" - "async def request(self, value: Value, optional_value: Value | None=None):\n" - " ..." - ) - - -@pytest.mark.parametrize( - "expression", - [ - "DeleteSessionRequest", - "Annotated[DeleteSessionRequest, Field(title='Delete')]", - "RequestAlias", - "schema.DeleteSessionRequest", - ], -) -def test_signature_generation_expands_single_model_types(expression) -> None: - import ast - - from scripts.gen_signature import NodeTransformer - - tree = ast.parse( - "from typing import Annotated, Any, TypeAlias\n" - "from schema import DeleteSessionRequest\n" - "RequestAlias: TypeAlias = Annotated[DeleteSessionRequest, Field(title='Delete')]\n" - "class Methods:\n" - f" @param_model({expression}, method='session/delete')\n" - " async def delete_session(self, **kwargs: Any): ...\n" - ) - NodeTransformer().visit(tree) - methods = tree.body[-1] - assert isinstance(methods, ast.ClassDef) - method = methods.body[0] - assert isinstance(method, ast.AsyncFunctionDef) - assert [arg.arg for arg in method.args.args] == ["self", "session_id"] - assert ast.unparse(method.decorator_list[0]) == f"param_model({expression}, method='session/delete')" - - -def test_v2_signature_generation_uses_v2_schema_and_qualified_types() -> None: - import ast - - from acp.experimental import v2 - from scripts.gen_signature import NodeTransformer - - tree = ast.parse( - "from typing import Any\n" - "from . import schema\n" - "class Methods:\n" - " @param_model(schema.InitializeRequest)\n" - " async def initialize(self, **kwargs: Any): ...\n" - ) - NodeTransformer(v2.schema).visit(tree) - ast.fix_missing_locations(tree) - methods = tree.body[-1] - assert isinstance(methods, ast.ClassDef) - method = methods.body[0] - assert isinstance(method, ast.AsyncFunctionDef) - assert [arg.arg for arg in method.args.args] == ["self", "protocol_version", "info", "capabilities"] - assert method.args.args[2].annotation is not None - assert method.args.args[3].annotation is not None - assert ast.unparse(method.args.args[2].annotation) == "schema.Implementation" - assert ast.unparse(method.args.args[3].annotation) == "schema.ClientCapabilities | None" - - -def test_v1_signature_generation_does_not_rewrite_experimental_files(tmp_path) -> None: - experimental = tmp_path / "experimental" / "v2" - experimental.mkdir(parents=True) - target = experimental / "interfaces.py" - source = "from . import schema\n@param_model(schema.InitializeRequest)\nasync def initialize(self): ...\n" - target.write_text(source) - gen_signature(tmp_path) - assert target.read_text() == source diff --git a/tests/test_golden.py b/tests/test_golden.py index 4349c5da..0a289db4 100644 --- a/tests/test_golden.py +++ b/tests/test_golden.py @@ -255,3 +255,9 @@ def test_models_match_golden(name: str, builder: Callable[[], BaseModel]) -> Non model = builder() assert isinstance(model, BaseModel) assert _dump_model(model) == raw + + +def test_generated_field_descriptions_are_introspectable() -> None: + path_description = "Absolute path to the file to read." + assert ReadTextFileRequest.model_fields["path"].description == path_description + assert ReadTextFileRequest.model_json_schema()["properties"]["path"]["description"] == path_description diff --git a/tests/test_message_sender.py b/tests/test_message_sender.py deleted file mode 100644 index 9a6604f8..00000000 --- a/tests/test_message_sender.py +++ /dev/null @@ -1,91 +0,0 @@ -from __future__ import annotations - -import asyncio - -import pytest - -from acp.task import MessageSender - - -class _FakeWriter: - def __init__(self, *, fail_with: Exception | None = None) -> None: - self.fail_with = fail_with - self.written: list[bytes] = [] - self.release = asyncio.Event() - self.block = False - - def write(self, data: bytes) -> None: - self.written.append(data) - - async def drain(self) -> None: - if self.block: - await self.release.wait() - if self.fail_with is not None: - raise self.fail_with - - -def _make_sender(writer: _FakeWriter) -> MessageSender: - return MessageSender(writer) # type: ignore[arg-type] - - -@pytest.mark.asyncio -async def test_sends_are_written_in_call_order() -> None: - writer = _FakeWriter() - writer.block = True - sender = _make_sender(writer) - - tasks = [asyncio.create_task(sender.send({"n": i})) for i in range(3)] - await asyncio.sleep(0) - writer.release.set() - await asyncio.wait_for(asyncio.gather(*tasks), 1) - assert writer.written == [b'{"n":0}\n', b'{"n":1}\n', b'{"n":2}\n'] - - -@pytest.mark.asyncio -async def test_send_after_close_raises() -> None: - writer = _FakeWriter() - sender = _make_sender(writer) - await sender.send({"a": 1}) - await sender.close() - with pytest.raises(ConnectionError): - await asyncio.wait_for(sender.send({"a": 2}), 1) - assert writer.written == [b'{"a":1}\n'] - - -@pytest.mark.asyncio -async def test_write_failure_fails_waiting_and_later_sends() -> None: - writer = _FakeWriter(fail_with=BrokenPipeError("boom")) - writer.block = True - sender = _make_sender(writer) - - first = asyncio.create_task(sender.send({"n": 1})) - waiting = asyncio.create_task(sender.send({"n": 2})) - await asyncio.sleep(0) - writer.release.set() - - with pytest.raises(BrokenPipeError): - await asyncio.wait_for(first, 1) - with pytest.raises(ConnectionError) as excinfo: - await asyncio.wait_for(waiting, 1) - assert isinstance(excinfo.value.__cause__, BrokenPipeError) - with pytest.raises(ConnectionError): - await asyncio.wait_for(sender.send({"n": 3}), 1) - assert len(writer.written) == 1 - - -@pytest.mark.asyncio -async def test_cancelled_send_releases_lock() -> None: - writer = _FakeWriter() - writer.block = True - sender = _make_sender(writer) - - stuck = asyncio.create_task(sender.send({"n": 1})) - waiting = asyncio.create_task(sender.send({"n": 2})) - await asyncio.sleep(0) - stuck.cancel() - with pytest.raises(asyncio.CancelledError): - await stuck - - writer.release.set() - await asyncio.wait_for(waiting, 1) - assert writer.written == [b'{"n":1}\n', b'{"n":2}\n'] diff --git a/tests/test_param_model.py b/tests/test_param_model.py deleted file mode 100644 index 0d82ed31..00000000 --- a/tests/test_param_model.py +++ /dev/null @@ -1,126 +0,0 @@ -from typing import Annotated, Any, Literal, Protocol, Union - -import pytest -from pydantic import BaseModel, BeforeValidator, Field, ValidationError - -from acp.router import MessageRouter -from acp.utils import compatible_class, param_model - - -class TextRequest(BaseModel): - kind: Literal["text"] = "text" - value: str - field_meta: dict[str, Any] | None = Field(None, alias="_meta") - - -class NumberRequest(BaseModel): - kind: Literal["number"] = "number" - value: int - precision: int = 0 - field_meta: dict[str, Any] | None = Field(None, alias="_meta") - - -TaggedRequest = Annotated[TextRequest | NumberRequest, Field(discriminator="kind")] - - -@pytest.mark.parametrize( - "request_type", - [ - TextRequest, - TextRequest | NumberRequest, - Union[TextRequest, NumberRequest], # noqa: UP007 - cover the typing.Union spelling - TaggedRequest, - Annotated[TextRequest, Field(title="Text")], - Annotated[TextRequest, Field(title="Text")] | NumberRequest, - ], -) -def test_decorator_preserves_original_type_and_function(request_type): - async def handler(**kwargs): - return kwargs - - decorated = param_model(request_type, method="example/request")(handler) - assert decorated is handler - assert decorated.__param_model__ is request_type - assert decorated.__route__.request_type is request_type - assert not hasattr(decorated, "__param_models__") - - -@pytest.mark.parametrize("request_type", [str, Any, list[TextRequest], TextRequest | str, TextRequest | None]) -def test_decorator_rejects_non_model_branches(request_type): - with pytest.raises(TypeError, match="expects a BaseModel"): - param_model(request_type) - - -def test_decorator_accepts_only_one_type_expression(): - with pytest.raises(TypeError): - param_model(TextRequest, NumberRequest) # type: ignore[call-arg] - - -@pytest.mark.asyncio -async def test_discriminated_union_keeps_validation_metadata_and_shared_fields(): - class Interface(Protocol): - @param_model(TaggedRequest, method="example/request") - async def request(self, value: str | int, kind: str, **kwargs: Any) -> Any: ... - - class Handler: - async def request(self, value: str | int, kind: str, **kwargs: Any): - return value, kind, kwargs - - router = MessageRouter.from_protocol(Interface, Handler()) - assert await router( - "example/request", - { - "kind": "number", - "value": 3, - "precision": 2, - "_meta": {"trace": "test"}, - }, - False, - ) == (3, "number", {"trace": "test"}) - # An ordinary union would infer a branch from defaults. A tagged union must - # require its discriminator, proving the Annotated metadata was retained. - with pytest.raises(ValidationError) as error: - await router("example/request", {"value": "hello"}, False) - assert isinstance(error.value, ValidationError) - assert error.value.errors()[0]["type"] == "union_tag_not_found" - - -@pytest.mark.asyncio -async def test_annotated_single_model_keeps_custom_validator(): - def uppercase(payload): - return {**payload, "value": payload["value"].upper()} - - class Interface(Protocol): - @param_model(Annotated[TextRequest, BeforeValidator(uppercase)], method="example/request") - async def request(self, value: str, kind: str, **kwargs: Any) -> str: ... - - class Handler: - async def request(self, value: str, kind: str, **kwargs: Any): - return value - - router = MessageRouter.from_protocol(Interface, Handler()) - assert await router("example/request", {"value": "hello"}, False) == "HELLO" - - -@pytest.mark.parametrize("request_type", [TextRequest | NumberRequest, TaggedRequest]) -def test_union_legacy_calls_use_shared_fields_and_meta(request_type): - @compatible_class - class Calls: - @param_model(request_type) - def set_value(self, value, kind, **kwargs): - return value, kind, kwargs - - @param_model(request_type) - def configure(self, value, kind, **kwargs): - return value, kind, kwargs - - calls = Calls() - request = NumberRequest(value=4, precision=2, _meta={"trace": "test"}) - expected = (4, "number", {"trace": "test"}) - with pytest.warns(DeprecationWarning): - assert getattr(calls, "setValue")(request) == expected # noqa: B009 - dynamically added alias - with pytest.warns(DeprecationWarning): - assert calls.configure(request) == expected - with pytest.warns(DeprecationWarning): - assert calls.configure(params=request) == expected - assert calls.configure(value=4, kind="number", trace="test") == expected diff --git a/tests/test_protocol_method_coverage.py b/tests/test_protocol_method_coverage.py index 055aa247..88106551 100644 --- a/tests/test_protocol_method_coverage.py +++ b/tests/test_protocol_method_coverage.py @@ -1,21 +1,17 @@ """Exercise v1 methods added after the original session/terminal API.""" import asyncio -import inspect from typing import Any, cast from unittest.mock import AsyncMock import pytest -from pydantic import ValidationError -from acp import schema +from acp import connect_to_agent, schema +from acp._transport import memory_transport_pair from acp.agent.connection import AgentSideConnection -from acp.agent.router import build_agent_router -from acp.client.connection import ClientSideConnection -from acp.client.router import build_client_router +from acp.connection import Connection from acp.exceptions import RequestError -from acp.interfaces import Agent, Client -from acp.meta import AGENT_METHODS, CLIENT_METHODS +from acp.interfaces import Agent REQUESTS = [ ("delete_session", "session/delete", {"session_id": "s"}, schema.DeleteSessionResponse()), @@ -49,7 +45,7 @@ @pytest.mark.asyncio @pytest.mark.parametrize(("name", "wire_method", "params", "response"), REQUESTS) -async def test_agent_request_roundtrip(connect, agent, name, wire_method, params, response): +async def test_agent_request_roundtrip(server, agent, client, name, wire_method, params, response): handler = AsyncMock(return_value=response) # Python 3.10 cannot inspect the signature of a bare AsyncMock. @@ -57,9 +53,16 @@ async def handle(**kwargs): return await handler(**kwargs) setattr(agent, name, handle) - _, connection = connect(use_unstable_protocol=True) - result = await getattr(connection, name)(**params, trace="test") + events = [] + async with ( + AgentSideConnection(agent, server.server_writer, server.server_reader, use_unstable_protocol=True), + connect_to_agent( + client, server.client_writer, server.client_reader, use_unstable_protocol=True, observers=[events.append] + ) as connection, + ): + result = await asyncio.wait_for(getattr(connection, name)(**params, trace="test"), timeout=1) assert result == response + assert events[0].message["method"] == wire_method assert handler.await_args is not None assert handler.await_args.kwargs.items() >= (params | {"trace": "test"}).items() @@ -116,14 +119,20 @@ async def test_delete_session_empty_and_legacy_response(connect, agent): agent.delete_session.assert_awaited_once_with(session_id="s") +async def _unexpected_request(method, params, is_notification): + pytest.fail(f"Unexpected incoming method: {method}") + + @pytest.mark.asyncio -@pytest.mark.parametrize(("name", "wire_method", "params", "response"), REQUESTS) -async def test_unimplemented_requests_report_method_not_found(name, wire_method, params, response): - router = build_agent_router(cast(Agent, object()), use_unstable_protocol=True) - with pytest.raises(RequestError) as exc: - await router(wire_method, {}, False) - assert isinstance(exc.value, RequestError) - assert exc.value.code == -32601 +@pytest.mark.parametrize("wire_method", [wire_method for _, wire_method, _, _ in REQUESTS]) +async def test_unimplemented_requests_report_method_not_found(wire_method): + peer_transport, agent_transport = memory_transport_pair() + async with ( + AgentSideConnection(cast(Agent, object()), agent_transport, use_unstable_protocol=True), + Connection(_unexpected_request, peer_transport) as peer, + ): + with pytest.raises(RequestError, check=lambda error: error.code == -32601): + await asyncio.wait_for(peer.send_request(wire_method, {}), timeout=1) @pytest.mark.asyncio @@ -132,28 +141,14 @@ class Handler: async def delete_session(self, session_id: str, **kwargs: Any): return None - router = build_agent_router(cast(Agent, Handler())) - assert await router("session/delete", {"sessionId": "s"}, False) == {} - with pytest.raises(ValidationError): - await router("session/delete", {}, False) - - -@pytest.mark.parametrize( - ("builder", "methods", "connection", "interface"), - [ - (build_agent_router, AGENT_METHODS, ClientSideConnection, Agent), - (build_client_router, CLIENT_METHODS, AgentSideConnection, Client), - ], -) -def test_all_schema_methods_have_routes_and_senders(builder, methods, connection, interface): - router = builder(object(), use_unstable_protocol=True) - assert set(router._requests) | set(router._notifications) == set(methods.values()) - source = inspect.getsource(connection) - for key in methods: - assert f'["{key}"]' in source - for name, method in inspect.getmembers(connection, inspect.isfunction): - if hasattr(method, "__param_model__"): - assert hasattr(interface, name) or any(char.isupper() for char in name) + peer_transport, agent_transport = memory_transport_pair() + async with ( + AgentSideConnection(cast(Agent, Handler()), agent_transport), + Connection(_unexpected_request, peer_transport) as peer, + ): + with pytest.raises(RequestError, check=lambda error: error.code == -32602): + await asyncio.wait_for(peer.send_request("session/delete", {}), timeout=1) + assert await asyncio.wait_for(peer.send_request("session/delete", {"sessionId": "s"}), timeout=1) == {} @pytest.mark.asyncio diff --git a/tests/test_protocol_router.py b/tests/test_protocol_router.py deleted file mode 100644 index 6d564d08..00000000 --- a/tests/test_protocol_router.py +++ /dev/null @@ -1,179 +0,0 @@ -"""Protocols are the source of truth for both signatures and wire routing.""" - -from typing import Any, Literal, Protocol, cast - -import pytest -from pydantic import BaseModel, Field, ValidationError - -from acp.agent.router import build_agent_router -from acp.client.router import build_client_router -from acp.exceptions import RequestError -from acp.interfaces import Agent, Client -from acp.router import MessageRouter -from acp.schema import SetSessionConfigOptionBooleanRequest -from acp.utils import normalize_result, param_model - - -class Params(BaseModel): - value: str - field_meta: dict[str, Any] | None = Field(None, alias="_meta") - - -class Parent(Protocol): - @param_model(Params, method="example/message", adapt_result=normalize_result) - async def message(self, value: str, **kwargs: Any) -> Any: ... - - -class Example(Parent, Protocol): - @param_model(Params, method="example/message", kind="notification") - async def notify(self, value: str, **kwargs: Any) -> None: ... - - @param_model(Params, method="example/preview", unstable=True) - async def preview(self, value: str, **kwargs: Any) -> Any: ... - - @param_model(Params, method="example/optional", optional=True, default_result={}) - async def optional(self, value: str, **kwargs: Any) -> Any: ... - - @param_model(Params) - async def local(self, value: str, **kwargs: Any) -> Any: ... - - -@pytest.mark.asyncio -async def test_routes_come_from_protocol_including_inherited_members(): - calls = [] - - class Implementation: - async def message(self, value: str, **kwargs: Any): - calls.append(("request", value, kwargs)) - - async def notify(self, value: str, **kwargs: Any): - calls.append(("notification", value, kwargs)) - - async def preview(self, value: str, **kwargs: Any): - return value - - @param_model(Params, method="example/private") - async def private(self, value: str, **kwargs: Any): - raise AssertionError("Implementation-only routes must not be exposed") - - router = MessageRouter.from_protocol(Example, Implementation()) - assert await router("example/message", {"value": "hello", "_meta": {"trace": 1}}, False) == {} - assert await router("example/message", {"value": "bye"}, True) is None - assert calls == [("request", "hello", {"trace": 1}), ("notification", "bye", {})] - assert await router("example/optional", {}, False) == {} - with pytest.raises(ValidationError): - await router("example/message", {}, False) - for method in ["example/private", "local"]: - with pytest.raises(RequestError): - await router(method, {"value": "hidden"}, False) - with pytest.warns(UserWarning, match="unstable"), pytest.raises(RequestError): - await router("example/preview", {"value": "preview"}, False) - enabled = MessageRouter.from_protocol(Example, Implementation(), use_unstable_protocol=True) - assert await enabled("example/preview", {"value": "preview"}, False) == "preview" - - -@pytest.mark.asyncio -async def test_union_route_uses_shared_fields_and_preserves_legacy_model(): - class Text(BaseModel): - value: str - kind: Literal["text"] = "text" - - class Number(BaseModel): - value: int - kind: Literal["number"] = "number" - precision: int = 0 - - class UnionProtocol(Protocol): - @param_model(Text | Number, method="example/union") - async def set_value(self, value: str | int, kind: str) -> Any: ... - - class Modern: - async def set_value(self, value: str | int, kind: str): - return value, kind - - class Legacy: - async def setValue(self, params): - return params - - payload = {"kind": "number", "value": 3, "precision": 2} - router = MessageRouter.from_protocol(UnionProtocol, Modern()) - assert await router("example/union", payload, False) == (3, "number") - legacy = MessageRouter.from_protocol(UnionProtocol, Legacy()) - with pytest.warns(DeprecationWarning): - result = await legacy("example/union", payload, False) - assert isinstance(result, Number) - assert result.precision == 2 - - -def test_duplicate_routes_are_rejected(): - class Duplicate(Parent, Protocol): - @param_model(Params, method="example/message") - async def other(self, value: str, **kwargs: Any) -> Any: ... - - with pytest.raises(ValueError, match="Duplicate request route"): - MessageRouter.from_protocol(Duplicate, object()) - - -@pytest.mark.asyncio -async def test_legacy_config_adapter_receives_boolean_request(): - class Legacy: - async def setConfigOption(self, params): - assert isinstance(params, SetSessionConfigOptionBooleanRequest) - assert params.value is False - return None - - router = build_agent_router(cast(Agent, Legacy())) - with pytest.warns(DeprecationWarning): - assert ( - await router( - "session/set_config_option", - {"sessionId": "s", "configId": "flag", "type": "boolean", "value": False}, - False, - ) - == {} - ) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("legacy", [False, True]) -async def test_elicitation_custom_mode_keeps_existing_dispatch_behavior(legacy): - class Handler: - async def createElicitation(self, params): - return {"mode": params.mode} - - class Modern: - async def create_elicitation(self, **kwargs): - raise AssertionError("Unsupported modes must fail before invoking the handler") - - router = build_client_router(cast(Client, Handler() if legacy else Modern()), use_unstable_protocol=True) - payload = {"mode": "x-voice", "message": "hi", "sessionId": "s"} - if legacy: - with pytest.warns(DeprecationWarning): - assert await router("elicitation/create", payload, False) == {"mode": "x-voice"} - else: - with pytest.raises(RequestError) as error: - await router("elicitation/create", payload, False) - assert isinstance(error.value, RequestError) - assert error.value.code == -32602 - - -@pytest.mark.asyncio -async def test_missing_handlers_and_extensions(): - router = MessageRouter.from_protocol(Example, object()) - with pytest.raises(RequestError): - await router("example/message", {"value": "hi"}, False) - with pytest.raises(RequestError): - await router("_example/extension", {}, False) - assert await router("_example/extension", {}, True) is None - - class Extensions: - async def ext_method(self, name, payload): - return [name, payload] - - async def ext_notification(self, name, payload): - assert name == "example/extension" - assert payload == {"value": 1} - - router = MessageRouter.from_protocol(Example, Extensions()) - assert await router("_example/extension", {"value": 1}, False) == ["example/extension", {"value": 1}] - assert await router("_example/extension", {"value": 1}, True) is None diff --git a/tests/test_reentrant_shutdown.py b/tests/test_reentrant_shutdown.py index 9a50b701..17659571 100644 --- a/tests/test_reentrant_shutdown.py +++ b/tests/test_reentrant_shutdown.py @@ -2,15 +2,20 @@ from __future__ import annotations +import asyncio import os import subprocess import sys from pathlib import Path +from typing import Any import pytest +from acp._transport import memory_transport_pair +from acp.connection import Connection + -@pytest.mark.parametrize("caller", ["notification", "request", "observer", "supervisor"]) +@pytest.mark.parametrize("caller", ["notification", "request", "observer"]) @pytest.mark.parametrize("siblings", [False, True]) def test_shutdown_from_owned_task(caller: str, siblings: bool) -> None: # A regression can poison cancellation cleanup with a self-await cycle. @@ -19,56 +24,37 @@ def test_shutdown_from_owned_task(caller: str, siblings: bool) -> None: import asyncio from acp.connection import Connection from acp._transport import memory_transport_pair -from acp.task import TaskSupervisor async def main(): finished = asyncio.Event() sibling_started = asyncio.Event() sibling_stopped = asyncio.Event() - supervisor = TaskSupervisor(source='test') async def sibling(): sibling_started.set() try: await asyncio.Event().wait() finally: sibling_stopped.set() - if CALLER == 'supervisor': - async def owned(): - if SIBLINGS: - supervisor.create(sibling()) - await sibling_started.wait() - await supervisor.shutdown() - await asyncio.sleep(0) - assert not asyncio.current_task().cancelled() - if SIBLINGS: - assert sibling_stopped.is_set() - finished.set() - task = supervisor.create(owned()) - await asyncio.wait_for(finished.wait(), 2) - await task - await supervisor.shutdown() - assert not supervisor._tasks - print('closed cleanly') - return local, peer = memory_transport_pair() async def handler(method, params, is_notification): - if CALLER == 'observer': - return None - await close_here() + if method == 'sibling': + await sibling() + elif CALLER != 'observer': + await close_here() async def observer(event): - if CALLER == 'observer': + if event.message.get('method') == 'stop': await close_here() connection = Connection(handler, local, observers=[observer] if CALLER == 'observer' else []) async def close_here(): - if SIBLINGS: - connection._tasks.create(sibling()) - await sibling_started.wait() await connection.close() await asyncio.sleep(0) assert not asyncio.current_task().cancelled() if SIBLINGS: assert sibling_stopped.is_set() finished.set() + if SIBLINGS: + await peer.send({'jsonrpc': '2.0', 'method': 'sibling', 'id': 2}) + await asyncio.wait_for(sibling_started.wait(), 2) message = {'jsonrpc': '2.0', 'method': 'stop'} if CALLER == 'request': message['id'] = 1 @@ -77,7 +63,6 @@ async def close_here(): await asyncio.sleep(0) await connection.close() await peer.close() - assert not connection._tasks._tasks print('closed cleanly') asyncio.run(main()) """ @@ -96,25 +81,26 @@ async def close_here(): @pytest.mark.asyncio -@pytest.mark.parametrize("siblings", [0, 2]) -async def test_external_shutdown_still_awaits_owned_task_cleanup(siblings: int) -> None: - import asyncio - - from acp.task import TaskSupervisor +async def test_external_shutdown_awaits_in_flight_handler_cleanup() -> None: + started: asyncio.Queue[str] = asyncio.Queue() + stopped: set[str] = set() - supervisor = TaskSupervisor(source="external-test") - stopped: list[int] = [] - - async def owned(index: int) -> None: + async def handler(method: str, params: Any, is_notification: bool) -> None: + started.put_nowait(method) try: await asyncio.Event().wait() finally: - stopped.append(index) + await asyncio.sleep(0) + stopped.add(method) - tasks = [supervisor.create(owned(index)) for index in range(siblings)] - await asyncio.sleep(0) - await supervisor.shutdown() - assert sorted(stopped) == list(range(siblings)) - assert all(task.cancelled() for task in tasks) - assert not supervisor._tasks - await supervisor.shutdown() + local, peer = memory_transport_pair() + async with Connection(handler, local) as conn: + try: + for identifier, method in enumerate(("first", "second")): + await peer.send({"jsonrpc": "2.0", "id": identifier, "method": method}) + assert await asyncio.wait_for(started.get(), timeout=1) == method + + await asyncio.wait_for(conn.close(), timeout=1) + assert stopped == {"first", "second"} + finally: + await peer.close() diff --git a/tests/test_request_error_logging.py b/tests/test_request_error_logging.py index 12f3ec4d..37993a7e 100644 --- a/tests/test_request_error_logging.py +++ b/tests/test_request_error_logging.py @@ -1,120 +1,52 @@ -"""Unhandled RPC handler exceptions must be logged instead of silently swallowed. - -Requests already returned a JSON-RPC -32603 error but discarded the original -traceback; notifications suppressed the exception entirely. Both now log the -underlying exception so integrators (e.g. Sentry via its logging integration) -can see server-side handler crashes. -""" +"""Unhandled RPC handler exceptions remain visible to application logging.""" from __future__ import annotations +import asyncio import logging from typing import Any import pytest -from acp._transport import Transport -from acp.connection import Connection, MethodHandler - - -class _RecordingTransport: - """Message transport that records outgoing frames.""" - - def __init__(self) -> None: - self.sent: list[dict[str, Any]] = [] - - async def send(self, message: dict[str, Any]) -> None: - self.sent.append(message) - - async def receive(self) -> dict[str, Any] | None: - return None - - async def close(self) -> None: - pass - - -def _make_connection(handler: MethodHandler) -> tuple[Connection, _RecordingTransport]: - transport = _RecordingTransport() - conn = Connection(handler, transport, listening=False) - return conn, transport - - -async def _raising_handler(method: str, params: Any, is_notification: bool) -> Any: - raise RuntimeError("kaboom") - - -def _assert_logged_runtime_error(caplog: pytest.LogCaptureFixture, method: str) -> None: - records = [ - record - for record in caplog.records - if record.levelno == logging.ERROR and record.exc_info and f"method={method}" in record.getMessage() - ] - assert len(records) == 1, f"expected exactly one logged error for method={method}" - exc_info = records[0].exc_info - assert exc_info is not None - logged = exc_info[1] - assert isinstance(logged, RuntimeError) - assert str(logged) == "kaboom" +from acp._transport import memory_transport_pair +from acp.connection import Connection, StreamDirection, StreamEvent +from acp.exceptions import RequestError @pytest.mark.asyncio -async def test_run_request_unhandled_exception_is_logged_and_sent_as_internal_error(caplog): - conn, transport = _make_connection(_raising_handler) - request = {"jsonrpc": "2.0", "id": 7, "method": "explode", "params": None} +@pytest.mark.parametrize("notification", [False, True], ids=["request", "notification"]) +async def test_unhandled_handler_exception_is_logged(caplog: pytest.LogCaptureFixture, notification: bool) -> None: + client, server = memory_transport_pair() - try: - with caplog.at_level(logging.ERROR): - await conn._run_request(request) - finally: - await conn.close() - - # A handled application exception becomes exactly one JSON-RPC error frame. - assert len(transport.sent) == 1 - response = transport.sent[0] - assert response["id"] == 7 - assert "result" not in response - assert response["error"] == {"code": -32603, "message": "Internal error", "data": {"details": "kaboom"}} + async def handler(method: str, params: Any, is_notification: bool) -> Any: + if method == "explode": + raise RuntimeError("kaboom") + return "pong" - # The original exception is logged, not discarded by `raise err from None`. - _assert_logged_runtime_error(caplog, "explode") + replies = [] + def record(event: StreamEvent) -> None: + if event.direction == StreamDirection.OUTGOING: + replies.append(event.message) -@pytest.mark.asyncio -async def test_run_notification_unhandled_exception_is_logged_and_not_answered(caplog): - conn, transport = _make_connection(_raising_handler) - notification = {"jsonrpc": "2.0", "method": "session/cancel", "params": {"sessionId": "s1"}} - - try: + async with Connection(handler, client) as peer, Connection(handler, server, observers=[record]): with caplog.at_level(logging.ERROR): - result = await conn._run_notification(notification) - finally: - await conn.close() - - # A notification has no response: the error is neither raised nor written to the wire. - assert result is None - assert transport.sent == [] - - # It must still be logged — previously contextlib.suppress dropped it silently. - _assert_logged_runtime_error(caplog, "session/cancel") - - -@pytest.mark.asyncio -async def test_response_send_failure_is_not_mapped_to_a_handler_error(caplog): - class _FailingTransport(_RecordingTransport): - async def send(self, message: dict[str, Any]) -> None: - raise ConnectionError("send failed") - - async def successful_handler(method: str, params: Any, is_notification: bool) -> Any: - return {"ok": True} - - transport: Transport = _FailingTransport() - conn = Connection(successful_handler, transport, listening=False) - request = {"jsonrpc": "2.0", "id": 8, "method": "succeed", "params": None} - - try: - with caplog.at_level(logging.ERROR), pytest.raises(ConnectionError, match="send failed"): - await conn._run_request(request) - finally: - await conn.close() - - assert "Unhandled error while handling request method=succeed" not in caplog.text + if notification: + await peer.send_notification("explode") + else: + with pytest.raises(RequestError) as exc: + await asyncio.wait_for(peer.send_request("explode"), timeout=1) + assert isinstance(exc.value, RequestError) + assert exc.value.code == -32603 + assert str(exc.value) == "Internal error" + assert exc.value.data == {"details": "kaboom"} + assert await asyncio.wait_for(peer.send_request("ping"), timeout=1) == "pong" + + assert len(replies) == (1 if notification else 2) + records = [record for record in caplog.records if record.levelno == logging.ERROR and record.exc_info] + assert len(records) == 1 + assert "method=explode" in records[0].getMessage() + assert records[0].exc_info is not None + error = records[0].exc_info[1] + assert isinstance(error, RuntimeError) + assert str(error) == "kaboom" diff --git a/tests/test_rpc.py b/tests/test_rpc.py index 8c78dc8f..06a8bf21 100644 --- a/tests/test_rpc.py +++ b/tests/test_rpc.py @@ -145,6 +145,26 @@ async def test_session_notifications_flow(connect, client): assert client.notifications[0].session_id == "sess" +@pytest.mark.asyncio +@pytest.mark.parametrize("with_metadata", [False, True]) +async def test_session_update_serializes_nested_metadata_and_discriminators(server, agent, with_metadata: bool): + outer_meta = {"outer": "value"} if with_metadata else {} + inner_meta = {"inner": "value"} if with_metadata else {} + update = AgentMessageChunk( + content=TextContentBlock(text="demo", field_meta=inner_meta or None), + field_meta=outer_meta or None, + ) + async with AgentSideConnection(agent, server.server_writer, server.server_reader) as conn: + await conn.session_update(session_id="s", update=update) + frame = json.loads(await asyncio.wait_for(server.client_reader.readline(), timeout=1)) + + expected: dict[str, Any] = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "demo"}} + if with_metadata: + expected["_meta"] = outer_meta + expected["content"]["_meta"] = inner_meta + assert frame == {"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "s", "update": expected}} + + @pytest.mark.asyncio async def test_session_notice_reaches_client(connect, client): agent_side, client_side = connect() @@ -480,37 +500,6 @@ async def test_new_requests_fail_fast_after_remote_eof(server): await conn.close() -@pytest.mark.asyncio -async def test_cancelled_request_is_removed_from_pending_map() -> None: - sent = asyncio.Event() - - class _NeverRespondTransport: - async def send(self, message: dict[str, Any]) -> None: - sent.set() - - async def receive(self) -> dict[str, Any] | None: - await asyncio.Event().wait() - return None - - async def close(self) -> None: - pass - - conn = Connection( - lambda method, params, is_notification: None, - _NeverRespondTransport(), - listening=False, - ) - request = asyncio.create_task(conn.send_request("ping")) - - await sent.wait() - request.cancel() - with pytest.raises(asyncio.CancelledError): - await request - - assert conn._pending == {} - await conn.close() - - @pytest.mark.asyncio async def test_invalid_params_results_in_error_response(connect, server): # Only start agent-side (server) so we can inject raw request from client socket @@ -970,11 +959,11 @@ async def test_connection_init_under_eager_task_factory(server): finally: loop.set_task_factory(previous_factory) - assert conn._transport._receive_timeout == 0.5 # type: ignore[attr-defined] - # Let the loop tick once so any deferred receive-task crash would land. - await asyncio.sleep(0) - assert conn._disconnected is False - await conn.close() + async with conn: + request = asyncio.create_task(conn.send_request("ping")) + frame = json.loads(await asyncio.wait_for(server.server_reader.readline(), timeout=1)) + await _send_responses(server.server_writer, {"jsonrpc": "2.0", "id": frame["id"], "result": "pong"}) + assert await asyncio.wait_for(request, timeout=1) == "pong" async def _response_handler(method: str, params: Any, is_notification: bool) -> None: @@ -1043,8 +1032,6 @@ async def test_bad_response_rejects_all_requests_before_close(server, error: Any assert len(done) == 2 for task in tasks: assert isinstance(task.exception(), ConnectionError) - assert conn._disconnected - assert not conn._pending if receive_loop is not None: with pytest.raises(AttributeError): await receive_loop @@ -1085,30 +1072,27 @@ async def test_response_compatibility(server, response: dict[str, Any], value: A assert isinstance(exception, RequestError) assert (exception.code, str(exception), exception.data) == error assert tasks[1].result() == "survivor" - assert not conn._pending - assert not conn._disconnected finally: await _cleanup_response_requests(conn, tasks) @pytest.mark.asyncio @pytest.mark.parametrize("request_id", [[], {}, True, 1.0, 999, "unknown", None]) -async def test_unknown_or_invalid_ids_do_not_parse_bad_error(server, request_id: Any) -> None: +@pytest.mark.parametrize("reply", [{"error": ["malformed"]}, {"result": "wrong request"}]) +async def test_unknown_or_invalid_ids_cannot_settle_a_request(server, request_id: Any, reply: dict[str, Any]) -> None: conn = Connection(_response_handler, server.client_writer, server.client_reader) tasks: list[asyncio.Task[Any]] = [] try: tasks, _ = await _start_response_requests(conn, server.server_reader) await _send_responses( server.server_writer, - {"jsonrpc": "2.0", "id": request_id, "error": ["malformed"]}, + {"jsonrpc": "2.0", "id": request_id, **reply}, {"jsonrpc": "2.0", "id": 0, "result": "first"}, {"jsonrpc": "2.0", "id": 1, "result": "second"}, ) _, pending = await asyncio.wait(tasks, timeout=1) assert not pending assert [task.result() for task in tasks] == ["first", "second"] - assert not conn._disconnected - assert not conn._pending finally: await _cleanup_response_requests(conn, tasks) @@ -1134,7 +1118,6 @@ async def test_cancelled_request_and_late_bad_response(server) -> None: assert not pending assert tasks[0].cancelled() assert tasks[1].result() == "survivor" - assert not conn._disconnected finally: await _cleanup_response_requests(conn, tasks) @@ -1154,7 +1137,6 @@ async def test_duplicate_bad_response_is_ignored(server) -> None: _, pending = await asyncio.wait(tasks, timeout=1) assert not pending assert [task.result() for task in tasks] == ["first", "second"] - assert not conn._disconnected finally: await _cleanup_response_requests(conn, tasks) @@ -1174,45 +1156,7 @@ async def test_normal_shutdown_rejects_pending(server, action: str) -> None: _, pending = await asyncio.wait(tasks, timeout=1) assert not pending assert all(isinstance(task.exception(), ConnectionError) for task in tasks) - assert not conn._pending + with pytest.raises(ConnectionError): + await asyncio.wait_for(conn.send_notification("after_shutdown"), timeout=1) finally: await _cleanup_response_requests(conn, tasks) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("status", ["done", "cancelled"]) -async def test_completed_future_is_removed_without_parsing(server, status: str) -> None: - conn = Connection(_response_handler, server.client_writer, server.client_reader, listening=False) - future = asyncio.get_running_loop().create_future() - conn._pending[0] = future - if status == "done": - future.set_result("original") - else: - future.cancel() - try: - conn._handle_response({"id": 0, "error": ["malformed"]}) - assert not conn._pending - assert not conn._disconnected - if status == "done": - assert future.result() == "original" - else: - assert future.cancelled() - finally: - await conn.close() - - -@pytest.mark.asyncio -async def test_done_callback_runs_after_pending_removal(server) -> None: - conn = Connection(_response_handler, server.client_writer, server.client_reader, listening=False) - future = asyncio.get_running_loop().create_future() - observed: list[bool] = [] - conn._pending[0] = future - future.add_done_callback(lambda _: observed.append(0 in conn._pending)) - try: - conn._handle_response({"id": 0, "result": "ok"}) - assert observed == [] - assert not conn._pending - await asyncio.sleep(0) - assert observed == [False] - finally: - await conn.close() diff --git a/tests/test_sender_parameters.py b/tests/test_sender_parameters.py deleted file mode 100644 index a7888393..00000000 --- a/tests/test_sender_parameters.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Every sender puts each of its parameters on the wire. - -`scripts/gen_signature.py` rewrites sender signatures from the schema, but the bodies are hand-written. A field the -schema adds can land in a signature and never reach the request model, and the call then drops it silently. -""" - -import ast -from pathlib import Path - -import pytest - -SRC = Path(__file__).resolve().parents[1] / "src" / "acp" - - -@pytest.mark.parametrize("module", ["client/connection.py", "agent/connection.py"]) -def test_every_sender_uses_all_its_parameters(module: str) -> None: - unused: list[str] = [] - for node in ast.walk(ast.parse((SRC / module).read_text(encoding="utf-8"))): - if isinstance(node, ast.AsyncFunctionDef) and not node.name.startswith("__"): - params = [a.arg for a in node.args.args + node.args.kwonlyargs if a.arg != "self"] - names = {n.id for n in ast.walk(node) if isinstance(n, ast.Name)} - unused += [f"{node.name}({p})" for p in params if p not in names] - assert unused == [] diff --git a/tests/test_stateless_mcp.py b/tests/test_stateless_mcp.py index 37363f06..d00848fc 100644 --- a/tests/test_stateless_mcp.py +++ b/tests/test_stateless_mcp.py @@ -11,6 +11,7 @@ from acp._transport import memory_transport_pair from acp.agent.connection import AgentSideConnection from acp.client.connection import ClientSideConnection +from acp.connection import Connection from acp.exceptions import RequestError from acp.experimental import v2 from acp.interfaces import Agent as AgentProtocol @@ -231,17 +232,31 @@ async def handle(request_id, **kwargs): @pytest.mark.asyncio -async def test_removed_binding_methods_and_reverse_calls_are_not_exposed(peers): - a, c, _, _ = peers +async def test_removed_binding_methods_and_reverse_calls_are_not_exposed(peers, schema): + a, c, _, client = peers assert not hasattr(a, "connect_mcp") assert not hasattr(a, "disconnect_mcp") assert not hasattr(a, "notify_mcp") assert not hasattr(c, "mcp_message") - for method in ("mcp/connect", "mcp/disconnect"): - with pytest.raises(RequestError) as error: - await a._conn.send_request(method, {"serverId": "s"}) - assert isinstance(error.value, RequestError) - assert error.value.code == -32601 + + async def initialize(method, params, is_notification): + assert method == "initialize" + return {"protocolVersion": 2, "info": {"name": "test", "version": "1"}} + + raw_transport, client_transport = memory_transport_pair() + sdk_client = ( + v2.ClientSideConnection(cast(ClientProtocol, client), client_transport) + if schema is v2.schema + else ClientSideConnection(cast(ClientProtocol, client), client_transport, use_unstable_protocol=True) + ) + async with Connection(initialize, raw_transport) as raw_peer, sdk_client: + if schema is v2.schema: + await asyncio.wait_for( + sdk_client.initialize(protocol_version=2, info=schema.Implementation(name="test", version="1")), 1 + ) + for method in ("mcp/connect", "mcp/disconnect"): + with pytest.raises(RequestError, check=lambda error: error.code == -32601): + await asyncio.wait_for(raw_peer.send_request(method, {"serverId": "s"}), 1) @pytest.mark.asyncio diff --git a/tests/test_utils.py b/tests/test_utils.py deleted file mode 100644 index 436fd731..00000000 --- a/tests/test_utils.py +++ /dev/null @@ -1,103 +0,0 @@ -import pytest - -from acp.schema import ( - AgentMessageChunk, - SetSessionConfigOptionBooleanRequest, - SetSessionConfigOptionSelectRequest, - TextContentBlock, -) -from acp.utils import serialize_params - - -def test_serialize_params_uses_meta_aliases() -> None: - chunk = AgentMessageChunk( - session_update="agent_message_chunk", - content=TextContentBlock(type="text", text="demo", field_meta={"inner": "value"}), - field_meta={"outer": "value"}, - ) - - payload = serialize_params(chunk) - - assert payload["_meta"] == {"outer": "value"} - assert payload["content"]["_meta"] == {"inner": "value"} - - -def test_serialize_params_omits_meta_when_absent() -> None: - chunk = AgentMessageChunk( - session_update="agent_message_chunk", - content=TextContentBlock(type="text", text="demo"), - ) - - payload = serialize_params(chunk) - - assert "_meta" not in payload - assert "_meta" not in payload["content"] - - -def test_serialize_params_includes_defaulted_discriminators() -> None: - chunk = AgentMessageChunk(content=TextContentBlock(text="demo")) - - assert serialize_params(chunk) == { - "sessionUpdate": "agent_message_chunk", - "content": {"type": "text", "text": "demo"}, - } - - -def test_field_meta_can_be_set_by_name_on_models() -> None: - chunk = AgentMessageChunk( - session_update="agent_message_chunk", - content=TextContentBlock(type="text", text="demo", field_meta={"inner": "value"}), - field_meta={"outer": "value"}, - ) - - assert chunk.field_meta == {"outer": "value"} - assert chunk.content.field_meta == {"inner": "value"} - - -def test_serialize_params_uses_boolean_config_variant() -> None: - request = SetSessionConfigOptionBooleanRequest( - config_id="brave_mode", - session_id="sess", - type="boolean", - value=True, - ) - - payload = serialize_params(request) - - assert payload == { - "configId": "brave_mode", - "sessionId": "sess", - "type": "boolean", - "value": True, - } - - -def test_serialize_params_uses_select_config_variant() -> None: - request = SetSessionConfigOptionSelectRequest( - config_id="theme", - session_id="sess", - value="dark", - ) - - payload = serialize_params(request) - - assert payload == { - "configId": "theme", - "sessionId": "sess", - "value": "dark", - } - - -@pytest.mark.parametrize( - "original, expected", - [ - ("simple_test", "simpleTest"), - ("another_example_here", "anotherExampleHere"), - ("lowercase", "lowercase"), - ("alreadyCamelCase", "alreadyCamelCase"), - ], -) -def test_to_camel_case(original, expected) -> None: - from acp.utils import to_camel_case - - assert to_camel_case(original) == expected