Skip to content

Commit 569b94f

Browse files
fix(client): keep tenant defaults local to each call (a2aproject#1463)
# Description Reusing one `GetTaskRequest` with two clients configured for different tenants currently sends both HTTP requests to the first tenant. The tenant decorator writes its default onto the caller's protobuf request, so the next client treats that injected value as an explicit override. Apply the default to a copy for every normal and streaming operation. The original request stays unchanged, and explicit tenant overrides continue to work. The regression uses `ClientFactory`, a real REST transport and a mocked HTTP endpoint. On upstream, the recorded paths are `/a2a/alpha/tasks/task` twice; with the fix, they are `/a2a/alpha/tasks/task` and `/a2a/beta/tasks/task`. Unit coverage also verifies request preservation and per-client defaults for all 11 operations. Validation: - Focused tenant tests: 18 passed. - `./scripts/lint.sh`: passed; ty reports three existing unused-ignore warnings. - `uv run pytest`: 2,569 passed, 207 skipped, 4 xfailed, 1 xpassed. - Coverage suite: 2,569 passed; 93.70% total coverage, exceeding 88%. - `git diff --check`: passed. The initial full run had four setup errors while the isolated v0.3 server dependencies downloaded beyond the fixture's three-second startup deadline. After warming those existing test environments, the full suite passed without changing or skipping tests. - [x] Followed the contribution guide. - [x] Conventional commit title. - [x] Tests and lint run. - [x] Documentation impact reviewed; no additional documentation needed for this fix. AI assistance: implemented and tested autonomously with OpenAI Codex under the account owner's authorization. No human review is claimed. Co-authored-by: Harshil <181649964+Harshil-1603@users.noreply.github.com> Co-authored-by: mykytanetipa <mykytanetipa@google.com>
1 parent 09c9347 commit 569b94f

3 files changed

Lines changed: 91 additions & 19 deletions

File tree

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import copy
2+
13
from collections.abc import AsyncGenerator
24

35
from a2a.client.client import ClientCallContext
@@ -44,6 +46,7 @@ async def send_message(
4446
context: ClientCallContext | None = None,
4547
) -> SendMessageResponse:
4648
"""Sends a streaming message request to the agent and yields responses as they arrive."""
49+
request = copy.deepcopy(request)
4750
request.tenant = self._resolve_tenant(request.tenant)
4851
return await self._base.send_message(request, context=context)
4952

@@ -54,6 +57,7 @@ async def send_message_streaming(
5457
context: ClientCallContext | None = None,
5558
) -> AsyncGenerator[StreamResponse]:
5659
"""Sends a streaming message request to the agent and yields responses."""
60+
request = copy.deepcopy(request)
5761
request.tenant = self._resolve_tenant(request.tenant)
5862
async for event in self._base.send_message_streaming(
5963
request, context=context
@@ -67,6 +71,7 @@ async def get_task(
6771
context: ClientCallContext | None = None,
6872
) -> Task:
6973
"""Retrieves the current state and history of a specific task."""
74+
request = copy.deepcopy(request)
7075
request.tenant = self._resolve_tenant(request.tenant)
7176
return await self._base.get_task(request, context=context)
7277

@@ -77,6 +82,7 @@ async def list_tasks(
7782
context: ClientCallContext | None = None,
7883
) -> ListTasksResponse:
7984
"""Retrieves tasks for an agent."""
85+
request = copy.deepcopy(request)
8086
request.tenant = self._resolve_tenant(request.tenant)
8187
return await self._base.list_tasks(request, context=context)
8288

@@ -87,6 +93,7 @@ async def cancel_task(
8793
context: ClientCallContext | None = None,
8894
) -> Task:
8995
"""Requests the agent to cancel a specific task."""
96+
request = copy.deepcopy(request)
9097
request.tenant = self._resolve_tenant(request.tenant)
9198
return await self._base.cancel_task(request, context=context)
9299

@@ -97,6 +104,7 @@ async def create_task_push_notification_config(
97104
context: ClientCallContext | None = None,
98105
) -> TaskPushNotificationConfig:
99106
"""Sets or updates the push notification configuration for a specific task."""
107+
request = copy.deepcopy(request)
100108
request.tenant = self._resolve_tenant(request.tenant)
101109
return await self._base.create_task_push_notification_config(
102110
request, context=context
@@ -109,6 +117,7 @@ async def get_task_push_notification_config(
109117
context: ClientCallContext | None = None,
110118
) -> TaskPushNotificationConfig:
111119
"""Retrieves the push notification configuration for a specific task."""
120+
request = copy.deepcopy(request)
112121
request.tenant = self._resolve_tenant(request.tenant)
113122
return await self._base.get_task_push_notification_config(
114123
request, context=context
@@ -121,6 +130,7 @@ async def list_task_push_notification_configs(
121130
context: ClientCallContext | None = None,
122131
) -> ListTaskPushNotificationConfigsResponse:
123132
"""Lists push notification configurations for a specific task."""
133+
request = copy.deepcopy(request)
124134
request.tenant = self._resolve_tenant(request.tenant)
125135
return await self._base.list_task_push_notification_configs(
126136
request, context=context
@@ -133,6 +143,7 @@ async def delete_task_push_notification_config(
133143
context: ClientCallContext | None = None,
134144
) -> None:
135145
"""Deletes the push notification configuration for a specific task."""
146+
request = copy.deepcopy(request)
136147
request.tenant = self._resolve_tenant(request.tenant)
137148
await self._base.delete_task_push_notification_config(
138149
request, context=context
@@ -145,6 +156,7 @@ async def subscribe(
145156
context: ClientCallContext | None = None,
146157
) -> AsyncGenerator[StreamResponse]:
147158
"""Reconnects to get task updates."""
159+
request = copy.deepcopy(request)
148160
request.tenant = self._resolve_tenant(request.tenant)
149161
async for event in self._base.subscribe(request, context=context):
150162
yield event
@@ -156,6 +168,7 @@ async def get_extended_agent_card(
156168
context: ClientCallContext | None = None,
157169
) -> AgentCard:
158170
"""Retrieves the Extended AgentCard."""
171+
request = copy.deepcopy(request)
159172
request.tenant = self._resolve_tenant(request.tenant)
160173
return await self._base.get_extended_agent_card(
161174
request,

‎tests/client/transports/test_tenant_decorator.py‎

Lines changed: 34 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from collections.abc import AsyncGenerator
2+
from typing import Any
13
from unittest.mock import AsyncMock
24

35
import pytest
@@ -92,38 +94,53 @@ async def test_resolve_tenant_logic_empty_tenant(
9294
)
9395
@pytest.mark.asyncio
9496
async def test_methods(
95-
self, mock_transport: AsyncMock, method_name, request_obj
97+
self, mock_transport: AsyncMock, method_name: str, request_obj: Any
9698
) -> None:
9799
"""Test that tenant is set on the request for all methods."""
98100
tenant_id = 'test-tenant'
99101
decorator = TenantTransportDecorator(mock_transport, tenant_id)
100102
mock_method = getattr(mock_transport, method_name)
101103

104+
original = request_obj.SerializeToString()
102105
await getattr(decorator, method_name)(request_obj)
106+
other = TenantTransportDecorator(mock_transport, 'other-tenant')
107+
await getattr(other, method_name)(request_obj)
103108

104-
mock_method.assert_called_once()
109+
assert mock_method.await_count == 2
105110
assert mock_transport.mock_calls[0][0] == method_name
106-
assert request_obj.tenant == tenant_id
111+
assert [
112+
call.args[0].tenant for call in mock_method.await_args_list
113+
] == [
114+
tenant_id,
115+
'other-tenant',
116+
]
117+
assert request_obj.SerializeToString() == original
107118

108119
@pytest.mark.asyncio
109120
async def test_streaming_methods(self, mock_transport: AsyncMock) -> None:
110121
"""Test that tenant is set on the request for streaming methods."""
111122
tenant_id = 'test-tenant'
112123
decorator = TenantTransportDecorator(mock_transport, tenant_id)
113124

114-
async def mock_stream(*args, **kwargs):
125+
tenants: list[str] = []
126+
127+
async def mock_stream(
128+
request: Any, **kwargs: Any
129+
) -> AsyncGenerator[StreamResponse]:
130+
tenants.append(request.tenant)
115131
yield StreamResponse()
116132

117-
# Test subscribe
118-
mock_transport.subscribe.return_value = mock_stream()
119-
request_sub = SubscribeToTaskRequest(id='t1')
120-
async for _ in decorator.subscribe(request_sub):
121-
pass
122-
assert request_sub.tenant == tenant_id
123-
124-
# Test send_message_streaming
125-
mock_transport.send_message_streaming.return_value = mock_stream()
126-
request_msg = SendMessageRequest()
127-
async for _ in decorator.send_message_streaming(request_msg):
128-
pass
129-
assert request_msg.tenant == tenant_id
133+
mock_transport.subscribe.side_effect = mock_stream
134+
mock_transport.send_message_streaming.side_effect = mock_stream
135+
other = TenantTransportDecorator(mock_transport, 'other-tenant')
136+
for method, request in [
137+
('subscribe', SubscribeToTaskRequest(id='t1')),
138+
('send_message_streaming', SendMessageRequest()),
139+
]:
140+
original = request.SerializeToString()
141+
async for _ in getattr(decorator, method)(request):
142+
pass
143+
async for _ in getattr(other, method)(request):
144+
pass
145+
assert request.SerializeToString() == original
146+
assert tenants == [tenant_id, 'other-tenant', tenant_id, 'other-tenant']

‎tests/integration/test_tenant.py‎

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
AgentCapabilities,
1313
AgentCard,
1414
AgentInterface,
15+
GetTaskRequest,
1516
ListTasksRequest,
1617
ListTasksResponse,
1718
Message,
@@ -70,8 +71,7 @@ async def test_tenant_decorator_rest(self, agent_card):
7071
request = SendMessageRequest(message=Message(parts=[{'text': 'hi'}]))
7172
await client._transport.send_message(request)
7273

73-
# Check that tenant was populated in request
74-
assert request.tenant == 'tenant-1'
74+
assert request.tenant == ''
7575

7676
# Check that path was prepended in the underlying transport
7777
mock_httpx.build_request.assert_called()
@@ -249,3 +249,45 @@ async def test_jsonrpc_tenant_context_population(
249249
server_context = call_args[0][1]
250250
assert isinstance(server_context, ServerCallContext)
251251
assert server_context.tenant == 'my-test-tenant'
252+
253+
254+
@pytest.mark.asyncio
255+
async def test_reused_request_uses_each_clients_default_tenant() -> None:
256+
paths: list[str] = []
257+
258+
async def respond(request: httpx.Request) -> httpx.Response:
259+
paths.append(request.url.path)
260+
return httpx.Response(
261+
200,
262+
json={
263+
'id': 'task',
264+
'contextId': 'context',
265+
'status': {'state': 'TASK_STATE_WORKING'},
266+
},
267+
)
268+
269+
request = GetTaskRequest(id='task')
270+
async with httpx.AsyncClient(
271+
transport=httpx.MockTransport(respond)
272+
) as http:
273+
factory = ClientFactory(
274+
ClientConfig(
275+
httpx_client=http,
276+
supported_protocol_bindings=[TransportProtocol.HTTP_JSON],
277+
)
278+
)
279+
for tenant in ('alpha', 'beta'):
280+
card = AgentCard(
281+
supported_interfaces=[
282+
AgentInterface(
283+
url='https://agent.example/a2a',
284+
protocol_binding=TransportProtocol.HTTP_JSON,
285+
tenant=tenant,
286+
)
287+
]
288+
)
289+
client = factory.create(card)
290+
await client.get_task(request)
291+
292+
assert paths == ['/a2a/alpha/tasks/task', '/a2a/beta/tasks/task']
293+
assert request.tenant == ''

0 commit comments

Comments
 (0)