Skip to content

Commit 086c47a

Browse files
committed
Merge branch 'main' into fix/rest-stream-inband-error
Resolve the conflict in test_rest_client.py and switch the new stream error tests to mock aiter_text, since a2aproject#1456 changed the SSE reader from aiter_lines to aiter_text.
2 parents e617c01 + c8ccea9 commit 086c47a

24 files changed

Lines changed: 762 additions & 65 deletions

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

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import re
23

34
from collections.abc import AsyncGenerator, Callable, Iterator
45
from contextlib import contextmanager
@@ -65,6 +66,39 @@ async def send_http_request(
6566
return response.json()
6667

6768

69+
_SSE_LINE_END = re.compile(r'\r\n|\r|\n')
70+
71+
72+
async def _aiter_sse_lines(
73+
response: httpx.Response,
74+
) -> AsyncGenerator[str, None]:
75+
"""Yields lines ended only by CRLF, LF or CR, unlike `aiter_lines()`.
76+
77+
The unfinished line is kept as a list of pieces and joined once, and
78+
only the new chunk is scanned, so a long `data:` line that spans many
79+
chunks costs linear rather than quadratic time.
80+
"""
81+
pieces: list[str] = []
82+
held_cr = False
83+
async for chunk in response.aiter_text():
84+
text = '\r' + chunk if held_cr else chunk
85+
# Hold a trailing CR back: the next chunk may start with its LF.
86+
held_cr = text.endswith('\r')
87+
*lines, rest = _SSE_LINE_END.split(text[:-1] if held_cr else text)
88+
if lines:
89+
lines[0] = ''.join(pieces) + lines[0]
90+
pieces = []
91+
for line in lines:
92+
yield line
93+
if rest:
94+
pieces.append(rest)
95+
tail = ''.join(pieces)
96+
# A held CR at end of stream still ends a line, even an empty one. That
97+
# blank line is what dispatches the last event, so yield it too.
98+
if held_cr or tail:
99+
yield tail
100+
101+
68102
async def parse_sse_stream(
69103
response: httpx.Response,
70104
) -> AsyncGenerator[tuple[str, str], None]:
@@ -75,9 +109,7 @@ async def parse_sse_stream(
75109
event_name = 'message'
76110
payload_chunks: list[str] = []
77111

78-
async for line in response.aiter_lines():
79-
raw_line = line.rstrip('\r\n')
80-
112+
async for raw_line in _aiter_sse_lines(response):
81113
# Empty line denotes the completion of the current event block
82114
if not raw_line:
83115
if payload_chunks:

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

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -574,7 +574,9 @@ def oauth2_flows(cls, flows: types.OAuthFlows) -> a2a_pb2.OAuthFlows:
574574
token_url=flows.password.token_url,
575575
),
576576
)
577-
raise ValueError('Unknown oauth flow definition')
577+
# No v0.3 flow is set, e.g. for a v1.0 device code flow, which v0.3
578+
# does not have.
579+
return a2a_pb2.OAuthFlows()
578580

579581
@classmethod
580582
def skill(cls, skill: types.AgentSkill) -> a2a_pb2.AgentSkill:
@@ -1058,13 +1060,15 @@ def oauth2_flows(cls, flows: a2a_pb2.OAuthFlows) -> types.OAuthFlows:
10581060
scopes=dict(flows.implicit.scopes.items()),
10591061
),
10601062
)
1061-
return types.OAuthFlows(
1062-
password=types.PasswordOAuthFlow(
1063-
refresh_url=flows.password.refresh_url,
1064-
scopes=dict(flows.password.scopes.items()),
1065-
token_url=flows.password.token_url,
1066-
),
1067-
)
1063+
if flows.HasField('password'):
1064+
return types.OAuthFlows(
1065+
password=types.PasswordOAuthFlow(
1066+
refresh_url=flows.password.refresh_url,
1067+
scopes=dict(flows.password.scopes.items()),
1068+
token_url=flows.password.token_url,
1069+
),
1070+
)
1071+
return types.OAuthFlows()
10681072

10691073
@classmethod
10701074
def stream_response(

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,12 @@ def routes(self) -> dict[tuple[str, str], Callable[[Request], Any]]:
148148
): functools.partial(
149149
self._handle_request, self.handler.get_push_notification
150150
),
151+
(
152+
'/v1/tasks/{id}/pushNotificationConfigs/{push_id}',
153+
'DELETE',
154+
): functools.partial(
155+
self._handle_request, self.handler.delete_push_notification
156+
),
151157
(
152158
'/v1/tasks/{id}/pushNotificationConfigs',
153159
'POST',

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,36 @@ async def get_push_notification(
194194
)
195195
return MessageToDict(pb2_v03_config)
196196

197+
@validate_version(constants.PROTOCOL_VERSION_0_3)
198+
async def delete_push_notification(
199+
self,
200+
request: Request,
201+
context: ServerCallContext,
202+
) -> dict[str, Any]:
203+
"""Handles the 'tasks/pushNotificationConfig/delete' REST method.
204+
205+
Args:
206+
request: The incoming `Request` object.
207+
context: Context provided by the server.
208+
209+
Returns:
210+
An empty `dict`, the JSON form of `google.protobuf.Empty`.
211+
"""
212+
task_id = request.path_params['id']
213+
push_id = request.path_params['push_id']
214+
215+
rpc_req = types_v03.DeleteTaskPushNotificationConfigRequest(
216+
id='',
217+
params=types_v03.DeleteTaskPushNotificationConfigParams(
218+
id=task_id, push_notification_config_id=push_id
219+
),
220+
)
221+
222+
await self.handler03.on_delete_task_push_notification_config(
223+
rpc_req, context
224+
)
225+
return {}
226+
197227
@validate_version(constants.PROTOCOL_VERSION_0_3)
198228
async def set_push_notification(
199229
self,

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

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from collections.abc import AsyncGenerator
66
from typing import Any, NoReturn
7+
from urllib.parse import quote
78

89
import httpx
910

@@ -58,6 +59,11 @@
5859
}
5960

6061

62+
def _quote_id(value: str) -> str:
63+
"""Percent-encodes an id so it stays a single URL path segment."""
64+
return quote(value, safe='')
65+
66+
6167
@trace_class(kind=SpanKind.CLIENT)
6268
class CompatRestTransport(ClientTransport):
6369
"""A backward compatible REST transport for A2A v0.3."""
@@ -101,7 +107,7 @@ async def send_message(
101107
'POST',
102108
'/v1/message:send',
103109
context=context,
104-
json=MessageToDict(req_proto, preserving_proto_field_name=True),
110+
json=MessageToDict(req_proto),
105111
)
106112

107113
resp_proto = ParseDict(
@@ -146,7 +152,7 @@ async def send_message_streaming(
146152
'POST',
147153
'/v1/message:stream',
148154
context=context,
149-
json=MessageToDict(req_proto, preserving_proto_field_name=True),
155+
json=MessageToDict(req_proto),
150156
):
151157
yield event
152158

@@ -163,7 +169,7 @@ async def get_task(
163169

164170
response_data = await self._execute_request(
165171
'GET',
166-
f'/v1/tasks/{request.id}',
172+
f'/v1/tasks/{_quote_id(request.id)}',
167173
context=context,
168174
params=params,
169175
)
@@ -192,7 +198,7 @@ async def cancel_task(
192198
"""Requests the agent to cancel a specific task."""
193199
response_data = await self._execute_request(
194200
'POST',
195-
f'/v1/tasks/{request.id}:cancel',
201+
f'/v1/tasks/{_quote_id(request.id)}:cancel',
196202
context=context,
197203
)
198204
resp_proto = ParseDict(
@@ -221,9 +227,9 @@ async def create_task_push_notification_config(
221227
)
222228
response_data = await self._execute_request(
223229
'POST',
224-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs',
230+
f'/v1/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
225231
context=context,
226-
json=MessageToDict(req_proto, preserving_proto_field_name=True),
232+
json=MessageToDict(req_proto),
227233
)
228234
resp_proto = ParseDict(
229235
response_data,
@@ -243,7 +249,8 @@ async def get_task_push_notification_config(
243249
"""Retrieves the push notification configuration for a specific task."""
244250
response_data = await self._execute_request(
245251
'GET',
246-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
252+
f'/v1/tasks/{_quote_id(request.task_id)}'
253+
f'/pushNotificationConfigs/{_quote_id(request.id)}',
247254
context=context,
248255
)
249256
resp_proto = ParseDict(
@@ -264,7 +271,7 @@ async def list_task_push_notification_configs(
264271
"""Lists push notification configurations for a specific task."""
265272
response_data = await self._execute_request(
266273
'GET',
267-
f'/v1/tasks/{request.task_id}/pushNotificationConfigs',
274+
f'/v1/tasks/{_quote_id(request.task_id)}/pushNotificationConfigs',
268275
context=context,
269276
)
270277
resp_proto = ParseDict(
@@ -285,8 +292,10 @@ async def delete_task_push_notification_config(
285292
context: ClientCallContext | None = None,
286293
) -> None:
287294
"""Deletes the push notification configuration for a specific task."""
288-
raise NotImplementedError(
289-
'delete_task_push_notification_config not supported in v0.3 REST'
295+
await self._execute_request(
296+
'DELETE',
297+
f'/v1/tasks/{request.task_id}/pushNotificationConfigs/{request.id}',
298+
context=context,
290299
)
291300

292301
async def subscribe(
@@ -308,7 +317,7 @@ async def subscribe(
308317
try:
309318
async for event in self._send_stream_request(
310319
subscribe_method,
311-
f'/v1/tasks/{request.id}:subscribe',
320+
f'/v1/tasks/{_quote_id(request.id)}:subscribe',
312321
context=context,
313322
):
314323
yield event

‎src/a2a/server/request_handlers/default_request_handler.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,9 @@ async def _setup_message_execution(
316316
)
317317

318318
task = task_manager.update_with_message(params.message, task)
319+
# Agents must infer the contextId from the task when the message
320+
# names only a taskId.
321+
context_id = context_id or task.context_id
319322
elif params.message.task_id:
320323
raise TaskNotFoundError(
321324
message=f'Task {params.message.task_id} was specified but does not exist'
@@ -325,7 +328,7 @@ async def _setup_message_execution(
325328
request_context = await self._request_context_builder.build(
326329
params=params,
327330
task_id=task.id if task else None,
328-
context_id=params.message.context_id,
331+
context_id=context_id,
329332
task=task,
330333
context=context,
331334
)

‎src/a2a/server/request_handlers/default_request_handler_v2.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,9 @@ async def _setup_active_task(
428428
f'context {task.context_id} of task {original_task_id}'
429429
)
430430
)
431+
# Agents must infer the contextId from the task when the message
432+
# names only a taskId.
433+
original_context_id = original_context_id or task.context_id
431434

432435
# Build context to resolve or generate missing IDs
433436
request_context = await self._request_context_builder.build(

‎src/a2a/server/tasks/database_task_store.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ def _after_cursor(self, cursor: ListTasksCursor) -> Any:
345345
)
346346
try:
347347
cursor_timestamp = _ns_to_datetime(cursor.timestamp_ns)
348-
except OverflowError as e:
348+
except (OverflowError, ValueError) as e:
349349
raise InvalidParamsError('Invalid page token') from e
350350
return or_(
351351
timestamp_col < cursor_timestamp,

‎src/a2a/utils/proto_utils.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def parse_lenient(
7070
7171
Raises:
7272
ParseError: If the data is not valid ProtoJSON, including bytes that
73-
are not valid UTF-8.
73+
are not valid UTF-8 and decoded values that are not objects.
7474
"""
7575
if isinstance(data, bytes):
7676
try:
@@ -79,6 +79,14 @@ def parse_lenient(
7979
raise ParseError(f'Failed to load JSON: {e}.') from e
8080
if isinstance(data, str):
8181
return Parse(data, message, ignore_unknown_fields=True)
82+
# A message is a JSON object. With ignore_unknown_fields, ParseDict reads
83+
# an empty list as an empty message (it iterates the value as if it were
84+
# the object's keys), and raises TypeError for null or a number.
85+
if not isinstance(data, dict):
86+
raise ParseError(
87+
f'Expected a JSON object for {message.DESCRIPTOR.name}, '
88+
f'got {type(data).__name__}.'
89+
)
8290
return ParseDict(data, message, ignore_unknown_fields=True)
8391

8492

‎tests/client/transports/test_http_helpers.py‎

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from collections.abc import AsyncIterator
2+
13
import httpx
24
import pytest
35

@@ -21,7 +23,7 @@ def test_default_sse_error_handler():
2123

2224
@pytest.mark.asyncio
2325
async def test_parse_sse_stream_edge_cases():
24-
async def mock_aiter_lines():
26+
async def mock_aiter_text():
2527
yield ': comment line (should be ignored)\n'
2628
yield 'event: custom_event\n'
2729
yield 'data: hello\n'
@@ -32,7 +34,7 @@ async def mock_aiter_lines():
3234
yield '\n'
3335

3436
response = httpx.Response(200)
35-
response.aiter_lines = mock_aiter_lines # type: ignore
37+
response.aiter_text = mock_aiter_text # type: ignore
3638

3739
events = [e async for e in parse_sse_stream(response)]
3840
assert events == [
@@ -41,6 +43,60 @@ async def mock_aiter_lines():
4143
]
4244

4345

46+
async def _byte_chunks(chunks: list[bytes]) -> AsyncIterator[bytes]:
47+
for chunk in chunks:
48+
yield chunk
49+
50+
51+
@pytest.mark.asyncio
52+
@pytest.mark.parametrize(
53+
('chunks', 'expected'),
54+
[
55+
pytest.param(
56+
['data: a
b
c\x85d\n\n'.encode()],
57+
[('message', 'a
b
c\x85d')],
58+
id='unicode-line-separators-stay-in-data',
59+
),
60+
pytest.param(
61+
[b'data: a\xe2\x80', b'\xa8b\r', b'\ndata: c\r\r'],
62+
[('message', 'a
b\nc')],
63+
id='crlf-and-character-split-across-chunks',
64+
),
65+
pytest.param(
66+
[b'data: a\r'],
67+
[],
68+
id='event-without-blank-line-is-not-dispatched',
69+
),
70+
],
71+
)
72+
async def test_parse_sse_stream_ends_lines_only_at_cr_or_lf(
73+
chunks: list[bytes], expected: list[tuple[str, str]]
74+
) -> None:
75+
"""Only CRLF, LF and CR end a line, as the SSE specification requires."""
76+
response = httpx.Response(200, content=_byte_chunks(chunks))
77+
78+
events = [e async for e in parse_sse_stream(response)]
79+
80+
assert events == expected
81+
82+
83+
@pytest.mark.asyncio
84+
@pytest.mark.timeout(10)
85+
async def test_parse_sse_stream_long_data_line_over_many_chunks() -> None:
86+
"""A multi-megabyte data: line read in small chunks stays linear."""
87+
payload = 'x' * (2 * 1024 * 1024)
88+
body = f'data: {payload}\r\n\r\n'.encode()
89+
chunk_size = 512
90+
chunks = [body[i : i + chunk_size] for i in range(0, len(body), chunk_size)]
91+
response = httpx.Response(200, content=_byte_chunks(chunks))
92+
93+
# Re-joining and re-scanning the whole line on every chunk took tens of
94+
# seconds here; the linear version takes well under a second.
95+
events = [e async for e in parse_sse_stream(response)]
96+
97+
assert events == [('message', payload)]
98+
99+
44100
@pytest.mark.asyncio
45101
async def test_send_http_stream_request_non_sse(mocker):
46102
client = httpx.AsyncClient()

0 commit comments

Comments
 (0)