Skip to content

Commit 830049d

Browse files
fix(client): decode SSE streams as UTF-8 (#1489)
The REST and JSON-RPC streaming clients share an SSE reader that delegates decoding to HTTPX or HTTPX2. When the response declares an ISO-8859-1 charset or the caller sets an ISO-8859-1 client default, a valid UTF-8 SSE payload such as `café 東京` comes back corrupted. [The SSE standard requires UTF-8 decoding.](https://html.spec.whatwg.org/multipage/server-sent-events.html#interpreting-an-event-stream) Read response bytes, keep the existing CR, LF, and CRLF framing, and decode each complete line as UTF-8. The regression feeds one byte at a time so both multibyte characters and CRLF cross chunk boundaries. [#1259](#1259) covers leading byte-order mark handling. ## Validation - On upstream `0fc0d3a`, both charset override cases corrupted the payload and the UTF-8 control passed. The fix passes all three cases with HTTPX and HTTPX2. - All 174 client transport tests and 1,167 HTTPX2-marked tests passed. - The full Ubuntu suite and coverage run each reported 2,628 passed, 215 skipped, 4 expected failures, and 1 unexpected pass. Coverage was 93.73%. PostgreSQL and MySQL service-dependent cases were skipped. - `scripts/lint.sh` and `uv build` passed. OpenAI Codex helped investigate, implement, and test this change. --------- Co-authored-by: Mateusz Iwaniuk <45974414+Iwaniukooo11@users.noreply.github.com>
1 parent e7114a3 commit 830049d

4 files changed

Lines changed: 90 additions & 42 deletions

File tree

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

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -71,37 +71,39 @@ async def send_http_request(
7171
return response.json()
7272

7373

74-
_SSE_LINE_END = re.compile(r'\r\n|\r|\n')
74+
_SSE_LINE_END = re.compile(rb'\r\n|\r|\n')
7575

7676

7777
async def _aiter_sse_lines(
7878
response: Response,
7979
) -> AsyncGenerator[str, None]:
80-
"""Yields lines ended only by CRLF, LF or CR, unlike `aiter_lines()`.
80+
"""Yields SSE lines split on CRLF/LF/CR, decoding UTF-8 here, not via httpx.
8181
8282
The unfinished line is kept as a list of pieces and joined once, and
8383
only the new chunk is scanned, so a long `data:` line that spans many
8484
chunks costs linear rather than quadratic time.
8585
"""
86-
pieces: list[str] = []
86+
# SSE is always UTF-8, regardless of HTTP charset and client defaults.
87+
# CR and LF cannot split a UTF-8 code point, so decode complete lines.
88+
pieces: list[bytes] = []
8789
held_cr = False
88-
async for chunk in response.aiter_text():
89-
text = '\r' + chunk if held_cr else chunk
90+
async for chunk in response.aiter_bytes():
91+
data = b'\r' + chunk if held_cr else chunk
9092
# Hold a trailing CR back: the next chunk may start with its LF.
91-
held_cr = text.endswith('\r')
92-
*lines, rest = _SSE_LINE_END.split(text[:-1] if held_cr else text)
93+
held_cr = data.endswith(b'\r')
94+
*lines, rest = _SSE_LINE_END.split(data[:-1] if held_cr else data)
9395
if lines:
94-
lines[0] = ''.join(pieces) + lines[0]
96+
lines[0] = b''.join(pieces) + lines[0]
9597
pieces = []
9698
for line in lines:
97-
yield line
99+
yield line.decode('utf-8', errors='replace')
98100
if rest:
99101
pieces.append(rest)
100-
tail = ''.join(pieces)
102+
tail = b''.join(pieces)
101103
# A held CR at end of stream still ends a line, even an empty one. That
102104
# blank line is what dispatches the last event, so yield it too.
103105
if held_cr or tail:
104-
yield tail
106+
yield tail.decode('utf-8', errors='replace')
105107

106108

107109
async def parse_sse_stream(

‎tests/client/transports/test_http_helpers.py‎

Lines changed: 58 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,21 @@ def test_default_sse_error_handler():
2626

2727
@pytest.mark.asyncio
2828
async def test_parse_sse_stream_edge_cases():
29-
async def mock_aiter_text():
30-
yield ': comment line (should be ignored)\n'
31-
yield 'event: custom_event\n'
32-
yield 'data: hello\n'
33-
yield 'data: world\n'
34-
yield '\n'
35-
yield '\n'
36-
yield 'data: \n'
37-
yield '\n'
38-
39-
response = httpx_lib.Response(200)
40-
response.aiter_text = mock_aiter_text # type: ignore
29+
response = httpx_lib.Response(
30+
200,
31+
content=_byte_chunks(
32+
[
33+
b': comment line (should be ignored)\n',
34+
b'event: custom_event\n',
35+
b'data: hello\n',
36+
b'data: world\n',
37+
b'\n',
38+
b'\n',
39+
b'data: \n',
40+
b'\n',
41+
]
42+
),
43+
)
4144

4245
events = [e async for e in parse_sse_stream(response)]
4346
assert events == [
@@ -51,6 +54,49 @@ async def _byte_chunks(chunks: list[bytes]) -> AsyncIterator[bytes]:
5154
yield chunk
5255

5356

57+
@pytest.mark.asyncio
58+
@pytest.mark.parametrize(
59+
('content_type', 'default_encoding'),
60+
[
61+
pytest.param('text/event-stream', 'utf-8', id='utf8-control'),
62+
pytest.param(
63+
'text/event-stream; charset=iso-8859-1',
64+
'utf-8',
65+
id='response-charset',
66+
),
67+
pytest.param(
68+
'text/event-stream', 'iso-8859-1', id='client-default-encoding'
69+
),
70+
],
71+
)
72+
async def test_send_http_stream_request_sse_uses_utf8(
73+
content_type: str, default_encoding: str
74+
) -> None:
75+
"""Decode SSE as UTF-8 even when HTTP text decoding selects another charset."""
76+
body = 'data: café 東京\r\n\r\n'.encode('utf-8')
77+
chunks = [body[i : i + 1] for i in range(len(body))]
78+
79+
def respond(request: httpx_lib.Request) -> httpx_lib.Response:
80+
return httpx_lib.Response(
81+
200,
82+
headers={'Content-Type': content_type},
83+
content=_byte_chunks(chunks),
84+
)
85+
86+
async with httpx_lib.AsyncClient(
87+
transport=httpx_lib.MockTransport(respond),
88+
default_encoding=default_encoding,
89+
) as client:
90+
events = [
91+
event
92+
async for event in send_http_stream_request(
93+
client, 'GET', 'https://agent.example'
94+
)
95+
]
96+
97+
assert events == ['café 東京']
98+
99+
54100
@pytest.mark.asyncio
55101
@pytest.mark.parametrize(
56102
('chunks', 'expected'),

‎tests/client/transports/test_jsonrpc_client.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -454,8 +454,8 @@ async def test_send_message_streaming_sse_error(
454454
mock_response = AsyncMock(spec=httpx_lib.Response)
455455
mock_response.raise_for_status = MagicMock()
456456
mock_response.headers = {'content-type': 'text/event-stream'}
457-
mock_response.aiter_text.return_value = async_iterable_from_list(
458-
['event: error\ndata: Simulated SSE error\n\n']
457+
mock_response.aiter_bytes.return_value = async_iterable_from_list(
458+
[b'event: error\ndata: Simulated SSE error\n\n']
459459
)
460460
mock_aconnect_sse.return_value.__aenter__.return_value = mock_response
461461

@@ -474,7 +474,7 @@ async def test_send_message_streaming_request_error(
474474
mock_response = AsyncMock(spec=httpx_lib.Response)
475475
mock_response.raise_for_status = MagicMock()
476476
mock_response.headers = {'content-type': 'text/event-stream'}
477-
mock_response.aiter_text.side_effect = httpx_lib.RequestError(
477+
mock_response.aiter_bytes.side_effect = httpx_lib.RequestError(
478478
'Simulated request error', request=MagicMock()
479479
)
480480
mock_aconnect_sse.return_value.__aenter__.return_value = mock_response
@@ -494,7 +494,7 @@ async def test_send_message_streaming_timeout(
494494
mock_response = AsyncMock(spec=httpx_lib.Response)
495495
mock_response.raise_for_status = MagicMock()
496496
mock_response.headers = {'content-type': 'text/event-stream'}
497-
mock_response.aiter_text.side_effect = httpx_lib.TimeoutException(
497+
mock_response.aiter_bytes.side_effect = httpx_lib.TimeoutException(
498498
'Timeout'
499499
)
500500
mock_aconnect_sse.return_value.__aenter__.return_value = mock_response
@@ -580,7 +580,7 @@ async def test_send_message_streaming_server_error_propagates(
580580
request=httpx_lib.Request('POST', 'http://test.url'),
581581
response=mock_response,
582582
)
583-
mock_response.aiter_text.return_value = async_iterable_from_list([])
583+
mock_response.aiter_bytes.return_value = async_iterable_from_list([])
584584
mock_aconnect_sse.return_value.__aenter__.return_value = mock_response
585585

586586
with pytest.raises(A2AClientError) as exc_info:
@@ -812,8 +812,8 @@ async def test_send_message_streaming_ignores_unrecognized_fields(
812812
mock_response = AsyncMock(spec=httpx_lib.Response)
813813
mock_response.raise_for_status = MagicMock()
814814
mock_response.headers = {'content-type': 'text/event-stream'}
815-
mock_response.aiter_text.return_value = async_iterable_from_list(
816-
[f'data: {json.dumps(payload)}\n\n']
815+
mock_response.aiter_bytes.return_value = async_iterable_from_list(
816+
[f'data: {json.dumps(payload)}\n\n'.encode()]
817817
)
818818
mock_sse_source.return_value.__aenter__.return_value = mock_response
819819

@@ -968,8 +968,8 @@ async def test_streaming_malformed_event_raises_a2a_error(
968968
mock_response = AsyncMock(spec=httpx_lib.Response)
969969
mock_response.raise_for_status = MagicMock()
970970
mock_response.headers = {'content-type': 'text/event-stream'}
971-
mock_response.aiter_text.return_value = async_iterable_from_list(
972-
[f'{line}\n' for line in lines]
971+
mock_response.aiter_bytes.return_value = async_iterable_from_list(
972+
[f'{line}\n'.encode() for line in lines]
973973
)
974974
mock_sse_source.return_value.__aenter__.return_value = mock_response
975975

‎tests/client/transports/test_rest_client.py‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ async def test_send_message_streaming_timeout(
112112
mock_response = AsyncMock(spec=httpx_lib.Response)
113113
mock_response.headers = {'content-type': 'text/event-stream'}
114114
mock_response.raise_for_status.return_value = None
115-
mock_response.aiter_text.side_effect = httpx_lib.TimeoutException(
115+
mock_response.aiter_bytes.side_effect = httpx_lib.TimeoutException(
116116
'Read timed out'
117117
)
118118
mock_aconnect_sse.return_value.__aenter__.return_value = mock_response
@@ -351,7 +351,7 @@ async def test_send_message_streaming_with_new_extensions(
351351
mock_response = AsyncMock(spec=httpx_lib.Response)
352352
mock_response.headers = {'content-type': 'text/event-stream'}
353353
mock_response.raise_for_status.return_value = None
354-
mock_response.aiter_text.return_value = async_iterable_from_list([])
354+
mock_response.aiter_bytes.return_value = async_iterable_from_list([])
355355
mock_aconnect_sse.return_value.__aenter__.return_value = mock_response
356356

357357
context = ClientCallContext(
@@ -401,7 +401,7 @@ async def test_send_message_streaming_server_error_propagates(
401401
request=httpx_lib.Request('POST', 'http://test.url'),
402402
response=mock_response,
403403
)
404-
mock_response.aiter_text.return_value = async_iterable_from_list([])
404+
mock_response.aiter_bytes.return_value = async_iterable_from_list([])
405405
mock_aconnect_sse.return_value.__aenter__.return_value = mock_response
406406

407407
with pytest.raises(A2AClientError) as exc_info:
@@ -836,7 +836,7 @@ async def test_rest_streaming_methods_prepend_tenant( # noqa: PLR0913
836836
mock_response = AsyncMock(spec=httpx_lib.Response)
837837
mock_response.headers = {'content-type': 'text/event-stream'}
838838
mock_response.raise_for_status.return_value = None
839-
mock_response.aiter_text.return_value = async_iterable_from_list([])
839+
mock_response.aiter_bytes.return_value = async_iterable_from_list([])
840840
mock_aconnect_sse.return_value.__aenter__.return_value = mock_response
841841

842842
# 3. Call the method
@@ -989,8 +989,8 @@ async def test_send_message_streaming_ignores_unrecognized_fields(
989989
mock_response = AsyncMock(spec=httpx_lib.Response)
990990
mock_response.raise_for_status = MagicMock()
991991
mock_response.headers = {'content-type': 'text/event-stream'}
992-
mock_response.aiter_text.return_value = async_iterable_from_list(
993-
[f'data: {json.dumps(payload)}\n\n']
992+
mock_response.aiter_bytes.return_value = async_iterable_from_list(
993+
[f'data: {json.dumps(payload)}\n\n'.encode()]
994994
)
995995
mock_sse_source.return_value.__aenter__.return_value = mock_response
996996

@@ -1074,8 +1074,8 @@ async def test_stream_error_raises_mapped_error(
10741074
mock_response = AsyncMock(spec=httpx_lib.Response)
10751075
mock_response.raise_for_status = MagicMock()
10761076
mock_response.headers = {'content-type': 'text/event-stream'}
1077-
mock_response.aiter_text.return_value = async_iterable_from_list(
1078-
[sse_text]
1077+
mock_response.aiter_bytes.return_value = async_iterable_from_list(
1078+
[sse_text.encode()]
10791079
)
10801080
mock_sse_source.return_value.__aenter__.return_value = mock_response
10811081

@@ -1100,8 +1100,8 @@ async def test_stream_event_of_unknown_type_is_still_yielded(
11001100
mock_response = AsyncMock(spec=httpx_lib.Response)
11011101
mock_response.raise_for_status = MagicMock()
11021102
mock_response.headers = {'content-type': 'text/event-stream'}
1103-
mock_response.aiter_text.return_value = async_iterable_from_list(
1104-
[f'data: {json.dumps({"someNewEvent": {"id": "e1"}})}\n\n']
1103+
mock_response.aiter_bytes.return_value = async_iterable_from_list(
1104+
[f'data: {json.dumps({"someNewEvent": {"id": "e1"}})}\n\n'.encode()]
11051105
)
11061106
mock_sse_source.return_value.__aenter__.return_value = mock_response
11071107

0 commit comments

Comments
 (0)