Skip to content

Commit 8c48ad3

Browse files
coder-abuclaudemykytanetipa
authored
fix(client): raise stream errors sent as plain SSE data events (a2aproject#1444)
# Description `RestTransport` only treats an SSE event named `error` as an error. A stream error sent as an ordinary `data:` event, with the `google.rpc.Status` body from section 11.6, goes to `parse_lenient`. That drops the unknown `error` key, so the caller gets an empty `StreamResponse` and no exception. Before a2aproject#1354 the strict `Parse` at least raised a `ParseError`. Section 11.7 only says the `data` field carries a `StreamResponse` and does not name an event type for errors, so SDK servers differ: - a2a-js and this SDK send `event: error`. - a2a-go sends a plain `data:` event, in [`handleStreamingRequest`](https://github.com/a2aproject/a2a-go/blob/ea739de3859f0574175bc9876eda39b7120da8e3/a2asrv/rest.go#L332-L347) through `sseWriter.WriteData`. It does this for errors in the middle of a stream, and for early ones too when the request's `Accept` header lists no JSON type. The Python client always sends `Accept: text/event-stream`. a2a-go's own client reads the error from the `error` key of the data object ([`ParseStreamResponse`](https://github.com/a2aproject/a2a-go/blob/ea739de3859f0574175bc9876eda39b7120da8e3/internal/rest/rest.go#L375-L400)). So a Python client streaming from an a2a-go agent reads a `TaskNotFoundError`, or any other mid-stream failure, as an empty event and keeps going. When a data event parses to no payload, `RestTransport` now checks it for an `error` key and raises through the same `_handle_sse_error` that handles `event: error`. `JsonRpcTransport` already raises for in-band errors the same way. Normal events are not decoded a second time. An event with no known payload and no `error` key is still yielded as before, so the forward compatibility from a2aproject#1354 stays. The repro at the end of this description (a mock server sending one plain `data:` error event), on main (2cc1dd5): ``` event: None 0 stream ended without an error ``` On this branch: ``` raised TaskNotFoundError: task not found: t1 ``` ``` $ pytest tests/client/transports/test_rest_client.py # main with the new tests FAILED tests/client/transports/test_rest_client.py::TestRestStreamErrors::test_stream_error_raises_mapped_error[data_event] 1 failed, 43 passed $ pytest --ignore=tests/integration/cross_version # this branch, Python 3.10, locked deps 2558 passed, 207 skipped, 4 xfailed, 1 xpassed $ pytest --cov=src src/a2a/client/transports/rest.py 87% (the new lines are covered) TOTAL 94% ``` The `error_event` case and the unknown-event case pass on main as well. They pin the existing `event: error` path, which had no REST client test, and the lenient handling of unknown events. The cross-version tests are left out because their servers don't start within the 3 s timeout on my machine; the same happens on main. `ruff check`, `ruff format` and `ty check` pass, with only the three existing unused `type: ignore` warnings from `ty`. - [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 (Run `bash scripts/format.sh` from the repository root to format) - [x] Appropriate docs were updated (if necessary) No issue exists, since the new test reproduces it. <details><summary>Repro script</summary> ```python import asyncio import json import httpx from a2a.client.transports.rest import RestTransport from a2a.types.a2a_pb2 import AgentCard, SubscribeToTaskRequest # The google.rpc.Status body a2a-go writes as a plain `data:` event. ERROR = { 'error': { 'code': 404, 'status': 'NOT_FOUND', 'message': 'task not found: t1', 'details': [ { '@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'TASK_NOT_FOUND', 'domain': 'a2a-protocol.org', } ], } } def handler(request: httpx.Request) -> httpx.Response: return httpx.Response( 200, headers={'content-type': 'text/event-stream'}, content=f'id: 1\ndata: {json.dumps(ERROR)}\n\n'.encode(), ) async def main() -> None: async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http: transport = RestTransport(http, AgentCard(), 'http://agent.example') try: async for event in transport.subscribe(SubscribeToTaskRequest(id='t1')): print('event:', event.WhichOneof('payload'), event.ByteSize()) print('stream ended without an error') except Exception as e: print(f'raised {type(e).__name__}: {e}') asyncio.run(main()) ``` </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Mykyta Netipa <mykytanetipa@google.com>
1 parent c8ccea9 commit 8c48ad3

2 files changed

Lines changed: 97 additions & 0 deletions

File tree

‎src/a2a/client/transports/rest.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,8 +407,22 @@ async def _send_stream_request(
407407
**http_kwargs,
408408
):
409409
event: StreamResponse = parse_lenient(sse_data, StreamResponse())
410+
if event.WhichOneof('payload') is None:
411+
self._raise_in_band_error(sse_data)
410412
yield event
411413

414+
def _raise_in_band_error(self, sse_data: str) -> None:
415+
"""Raises the error carried by a data event, if it carries one.
416+
417+
The HTTP+JSON binding defines no SSE event type for errors, so a
418+
server may send the ``google.rpc.Status`` body as an ordinary data
419+
event instead of an ``event: error`` one. ``StreamResponse`` has no
420+
``error`` field, so that body parses to an event with no payload.
421+
"""
422+
payload = json.loads(sse_data)
423+
if isinstance(payload, dict) and 'error' in payload:
424+
self._handle_sse_error(sse_data)
425+
412426
async def _send_request(self, request: httpx.Request) -> dict[str, Any]:
413427
return await send_http_request(
414428
self.httpx_client, request, self._handle_http_error

‎tests/client/transports/test_rest_client.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -945,3 +945,86 @@ async def test_get_task_rejects_body_that_is_not_an_object(
945945

946946
with pytest.raises(json_format.ParseError, match='JSON object'):
947947
await client.get_task(GetTaskRequest(id='task-1'))
948+
949+
950+
_TASK_NOT_FOUND_BODY = {
951+
'error': {
952+
'code': 404,
953+
'status': 'NOT_FOUND',
954+
'message': 'Task t1 not found',
955+
'details': [
956+
{
957+
'@type': 'type.googleapis.com/google.rpc.ErrorInfo',
958+
'reason': 'TASK_NOT_FOUND',
959+
'domain': 'a2a-protocol.org',
960+
}
961+
],
962+
}
963+
}
964+
965+
966+
class TestRestStreamErrors:
967+
@pytest.mark.asyncio
968+
@pytest.mark.parametrize(
969+
'sse_text',
970+
[
971+
f'event: error\ndata: {json.dumps(_TASK_NOT_FOUND_BODY)}\n\n',
972+
f'data: {json.dumps(_TASK_NOT_FOUND_BODY)}\n\n',
973+
],
974+
ids=['error_event', 'data_event'],
975+
)
976+
@patch('a2a.client.transports.http_helpers._SSEEventSource')
977+
async def test_stream_error_raises_mapped_error(
978+
self,
979+
mock_sse_source: AsyncMock,
980+
mock_httpx_client: AsyncMock,
981+
mock_agent_card: MagicMock,
982+
sse_text: str,
983+
):
984+
"""An error body raises whether or not the event is named `error`."""
985+
client = RestTransport(
986+
httpx_client=mock_httpx_client,
987+
agent_card=mock_agent_card,
988+
url='http://agent.example.com/api',
989+
)
990+
mock_response = AsyncMock(spec=httpx.Response)
991+
mock_response.raise_for_status = MagicMock()
992+
mock_response.headers = {'content-type': 'text/event-stream'}
993+
mock_response.aiter_text.return_value = async_iterable_from_list(
994+
[sse_text]
995+
)
996+
mock_sse_source.return_value.__aenter__.return_value = mock_response
997+
998+
with pytest.raises(TaskNotFoundError, match='Task t1 not found'):
999+
async for _ in client.subscribe(SubscribeToTaskRequest(id='t1')):
1000+
pass
1001+
1002+
@pytest.mark.asyncio
1003+
@patch('a2a.client.transports.http_helpers._SSEEventSource')
1004+
async def test_stream_event_of_unknown_type_is_still_yielded(
1005+
self,
1006+
mock_sse_source: AsyncMock,
1007+
mock_httpx_client: AsyncMock,
1008+
mock_agent_card: MagicMock,
1009+
):
1010+
"""An event with no known payload and no error stays a lenient parse."""
1011+
client = RestTransport(
1012+
httpx_client=mock_httpx_client,
1013+
agent_card=mock_agent_card,
1014+
url='http://agent.example.com/api',
1015+
)
1016+
mock_response = AsyncMock(spec=httpx.Response)
1017+
mock_response.raise_for_status = MagicMock()
1018+
mock_response.headers = {'content-type': 'text/event-stream'}
1019+
mock_response.aiter_text.return_value = async_iterable_from_list(
1020+
[f'data: {json.dumps({"someNewEvent": {"id": "e1"}})}\n\n']
1021+
)
1022+
mock_sse_source.return_value.__aenter__.return_value = mock_response
1023+
1024+
events = [
1025+
event
1026+
async for event in client.subscribe(SubscribeToTaskRequest(id='t1'))
1027+
]
1028+
1029+
assert len(events) == 1
1030+
assert events[0].WhichOneof('payload') is None

0 commit comments

Comments
 (0)