Skip to content

Commit 11f1116

Browse files
fix(compat): return HTTP errors from v0.3 REST streams that fail early (a2aproject#1403)
# Description The v0.3 REST adapter starts the SSE response before the handler runs, so any error raised before the first event becomes an empty 200 `text/event-stream`: a malformed `message:stream` body (even `{bad`), or `tasks/{id}:subscribe` for an unknown task. `message:send` answers 400 for the same body, and the v1.0 routes answer 400/404. `_handle_streaming_request` now fetches the first event before creating the response, as `RestDispatcher._handle_streaming` already does, so `@rest_stream_error_handler` maps these errors to the usual JSON error. Mid-stream behaviour is unchanged. Follow-up to a2aproject#1401, which noted this as a separate problem. - New tests (malformed `message:stream` → 400, unknown-task subscribe → 404, events still streamed in order) fail on main and pass with the fix. - `scripts/lint.sh` and `uv run pytest` on Linux pass. - [x] Follow the [`CONTRIBUTING` Guide](https://github.com/a2aproject/a2a-python/blob/main/CONTRIBUTING.md). - [x] Make your Pull Request title in the <https://www.conventionalcommits.org/> specification. - [x] Ensure the tests and linter pass - [ ] Appropriate docs were updated (not needed) Co-authored-by: Mateusz Iwaniuk <45974414+Iwaniukooo11@users.noreply.github.com>
1 parent 6ca8593 commit 11f1116

2 files changed

Lines changed: 78 additions & 1 deletion

File tree

‎src/a2a/compat/v0_3/rest_adapter.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,14 +93,28 @@ async def _handle_streaming_request(
9393

9494
call_context = self._context_builder.build(request)
9595

96+
# Fetch the first item before starting the SSE response so that
97+
# errors raised before any event (e.g. a malformed body) are mapped
98+
# to an HTTP error by @rest_stream_error_handler instead of an empty
99+
# 200 stream, matching the v1.0 REST dispatcher.
100+
stream = aiter(method(request, call_context))
101+
try:
102+
first_item = await anext(stream)
103+
except StopAsyncIteration:
104+
return create_event_source_response(
105+
iter([]),
106+
shutdown_grace_period=self._shutdown_grace_period,
107+
)
108+
96109
async def event_generator(
97110
stream: AsyncIterable[Any],
98111
) -> AsyncIterator[str]:
112+
yield json_utils.dumps(first_item)
99113
async for item in stream:
100114
yield json_utils.dumps(item)
101115

102116
return create_event_source_response(
103-
event_generator(method(request, call_context)),
117+
event_generator(stream),
104118
shutdown_grace_period=self._shutdown_grace_period,
105119
)
106120

‎tests/compat/v0_3/test_rest_routes_compat.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
import logging
23

34
from collections.abc import AsyncIterator
@@ -19,6 +20,7 @@
1920
TaskState as TaskState10,
2021
TaskStatus as TaskStatus10,
2122
)
23+
from a2a.utils.errors import TaskNotFoundError
2224
from fastapi import FastAPI
2325
from google.protobuf import json_format
2426
from httpx import ASGITransport, AsyncClient
@@ -298,3 +300,64 @@ async def stream_with_non_ascii(
298300
payload = payload.decode('utf-8')
299301
assert non_ascii_text in payload
300302
assert '\\u4f60\\u597d' not in payload
303+
304+
305+
@pytest.mark.anyio
306+
async def test_v03_message_stream_malformed_json_returns_400(
307+
client: AsyncClient, request_handler: MagicMock
308+
) -> None:
309+
response = await client.post(
310+
'/v1/message:stream',
311+
content=b'{bad',
312+
headers={'Content-Type': 'application/json'},
313+
)
314+
315+
assert response.status_code == 400
316+
assert response.headers['content-type'].startswith('application/json')
317+
assert response.json()['error']['status'] == 'INVALID_ARGUMENT'
318+
request_handler.on_message_send_stream.assert_not_called()
319+
320+
321+
@pytest.mark.anyio
322+
async def test_v03_subscribe_unknown_task_returns_404(
323+
client: AsyncClient, request_handler: MagicMock
324+
) -> None:
325+
async def not_found(*args: object, **kwargs: object) -> AsyncIterator[None]:
326+
raise TaskNotFoundError
327+
yield
328+
329+
request_handler.on_subscribe_to_task.side_effect = not_found
330+
331+
response = await client.post('/v1/tasks/unknown:subscribe')
332+
333+
assert response.status_code == 404
334+
assert response.json()['error']['status'] == 'NOT_FOUND'
335+
336+
337+
@pytest.mark.anyio
338+
async def test_v03_streaming_yields_all_events_in_order(
339+
request_handler: RequestHandler,
340+
) -> None:
341+
adapter = REST03Adapter(http_handler=request_handler)
342+
343+
async def stream(
344+
request: Request, context: object
345+
) -> AsyncIterator[dict[str, int]]:
346+
for i in range(3):
347+
yield {'n': i}
348+
349+
mock_req = MagicMock(spec=Request)
350+
mock_req.body = AsyncMock(return_value=b'{}')
351+
mock_req.headers = Headers({'a2a-version': '0.3'})
352+
mock_req.user = MagicMock(is_authenticated=False)
353+
mock_req.auth = None
354+
mock_req.scope = {}
355+
356+
response = await adapter._handle_streaming_request(stream, mock_req)
357+
chunks = [chunk async for chunk in response.body_iterator]
358+
359+
assert [json.loads(chunk) for chunk in chunks] == [
360+
{'n': 0},
361+
{'n': 1},
362+
{'n': 2},
363+
]

0 commit comments

Comments
 (0)