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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 0 additions & 42 deletions tests/http/test_cookies.py

This file was deleted.

107 changes: 19 additions & 88 deletions tests/http/test_fixes.py
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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."""
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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."""
Expand Down Expand Up @@ -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)
14 changes: 8 additions & 6 deletions tests/http/test_http_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -337,15 +336,15 @@ 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."""
server = FakeServer()
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":
Expand All @@ -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:
Expand Down
55 changes: 0 additions & 55 deletions tests/http/test_protocol.py

This file was deleted.

Loading
Loading