Skip to content

Commit d2cb22e

Browse files
sylvesterkaczmarekcopybara-github
authored andcommitted
fix: warn when session state is dropped
Merge #6859 Fixes #6854 PiperOrigin-RevId: 997885826
1 parent 7a50a85 commit d2cb22e

9 files changed

Lines changed: 484 additions & 9 deletions

File tree

‎docs/guides/agents/remote_a2a_agent/task.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,3 +204,18 @@ behavior:
204204
`finish_task` to signal completion.
205205
- **No Direct Transfer**: Task agents cannot be targeted via
206206
`transfer_to_agent`; they must be invoked as sub-agents/tools.
207+
208+
### Session state boundary
209+
210+
The caller and remote agent use separate sessions. Session state and
211+
`EventActions.state_delta` do not cross the A2A boundary in either direction:
212+
213+
- `output_key` on the remote agent writes only to the remote server's session.
214+
- A caller-side state-only event has no content to include in the A2A request.
215+
- A state delta supplied by a remote peer is not applied to the caller's
216+
session, because peers are not allowed to mutate caller state.
217+
218+
Pass values required by the remote agent in event content. Return values needed
219+
by the caller as response content or, in task mode, as `finish_task` output.
220+
ADK logs a warning when it is about to drop a state-only hand-off or receives a
221+
non-empty remote state delta.

‎src/google/adk/a2a/agent/_remote_a2a_agent.py‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@
7878
from ..converters.part_converter import GenAIPartToA2APartConverter
7979
from ..converters.to_adk_event import _create_mock_function_call_for_required_user_input
8080
from ..converters.to_adk_event import _TASK_RESPONSE_BOUNDARY_STATES
81+
from ..converters.to_adk_event import _warn_if_peer_metadata_has_state_delta
8182
from ..converters.to_adk_event import MOCK_FUNCTION_CALL_FOR_REQUIRED_USER_AUTH
8283
from ..converters.to_adk_event import MOCK_FUNCTION_CALL_FOR_REQUIRED_USER_INPUT
8384
from ..experimental import a2a_experimental
@@ -628,6 +629,11 @@ async def _before_request(
628629
class RemoteA2aAgent(BaseAgent):
629630
"""Agent that communicates with a remote A2A agent via A2A client.
630631
632+
Session state is local to each side of an A2A boundary. Only event content is
633+
included in requests, and state deltas from a remote peer are not applied to
634+
the caller's session. Put values needed by the peer in event content and
635+
return values needed by the caller as content or task output.
636+
631637
This agent supports multiple ways to specify the remote agent:
632638
1. Direct AgentCard object
633639
2. URL to agent card JSON
@@ -637,7 +643,6 @@ class RemoteA2aAgent(BaseAgent):
637643
- Agent card resolution and validation
638644
- HTTP client management with proper resource cleanup
639645
- A2A message conversion and error handling
640-
- Session state management across requests
641646
"""
642647

643648
mode: TaskAgentMode | None = None
@@ -1385,6 +1390,20 @@ def _construct_message_parts_from_session(
13851390
" session history. Workflow path scopes are not supported."
13861391
)
13871392

1393+
if events_to_process:
1394+
last_event = events_to_process[0]
1395+
has_state_delta = bool(
1396+
last_event.actions and last_event.actions.state_delta
1397+
)
1398+
has_content = bool(last_event.content and last_event.content.parts)
1399+
if has_state_delta and not has_content:
1400+
logger.warning(
1401+
"RemoteA2aAgent '%s' cannot forward the preceding state-only"
1402+
" event across A2A. Session state is local to each agent; include"
1403+
" the required values in event content instead.",
1404+
self.name,
1405+
)
1406+
13881407
# Collect all FC IDs emitted by this remote agent (in the task scope, when
13891408
# there is one). A function response answering one of these resumes a call
13901409
# the peer itself made; anything else is history that belongs to someone
@@ -1562,6 +1581,13 @@ async def _handle_a2a_response(
15621581
try:
15631582
if isinstance(a2a_response, tuple):
15641583
task, update = a2a_response
1584+
# The legacy converters never rebuild EventActions from peer metadata,
1585+
# so surface a dropped state delta here. Read only this item's own
1586+
# metadata: the aggregated task keeps metadata merged from earlier
1587+
# updates and would repeat the warning.
1588+
_warn_if_peer_metadata_has_state_delta(
1589+
task if update is None else update
1590+
)
15651591
if update is None:
15661592
# This is the initial response for a streaming task or the complete
15671593
# response for a non-streaming task, which is the full task state.
@@ -1662,6 +1688,7 @@ async def _handle_a2a_response(
16621688

16631689
# Otherwise, it's a regular A2AMessage for non-streaming responses.
16641690
elif isinstance(a2a_response, A2AMessage):
1691+
_warn_if_peer_metadata_has_state_delta(a2a_response)
16651692
event = convert_a2a_message_to_event(
16661693
a2a_response, self.name, ctx, self._a2a_part_converter
16671694
)

‎src/google/adk/a2a/converters/to_adk_event.py‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,36 @@ def _extract_genai_metadata(
305305
"""
306306

307307

308+
_STATE_DELTA_ACTION_FIELDS = frozenset({"state_delta", "stateDelta"})
309+
"""Both spellings of ``EventActions.state_delta`` in serialized metadata."""
310+
311+
312+
def _warn_if_peer_state_delta(parsed_actions: dict[str, Any]) -> None:
313+
"""Warns that a non-empty peer state delta will not reach caller state."""
314+
if any(parsed_actions.get(key) for key in _STATE_DELTA_ACTION_FIELDS):
315+
logger.warning(
316+
"Ignoring a session state delta from a remote A2A peer. Session state"
317+
" is local to each agent; return values needed by the caller as event"
318+
" content or task output instead."
319+
)
320+
321+
322+
def _warn_if_peer_metadata_has_state_delta(a2a_object: Any) -> None:
323+
"""Warns when a peer's task, update or message metadata has a state delta.
324+
325+
The legacy response path never rebuilds ``EventActions`` from peer metadata,
326+
so it calls this to surface the dropped delta the same way
327+
``_extract_event_actions`` does.
328+
"""
329+
metadata = _compat.meta_to_dict(getattr(a2a_object, "metadata", None))
330+
raw_actions = metadata.get(_get_adk_metadata_key("actions"))
331+
if raw_actions is None:
332+
return
333+
parsed_actions = _parse_adk_metadata_value(raw_actions)
334+
if isinstance(parsed_actions, dict):
335+
_warn_if_peer_state_delta(parsed_actions)
336+
337+
308338
def _extract_event_actions(metadata: Any) -> EventActions:
309339
"""Extracts ADK event actions from A2A metadata.
310340
@@ -336,10 +366,12 @@ def _extract_event_actions(metadata: Any) -> EventActions:
336366
for key, value in parsed_actions.items()
337367
if key in _PEER_SETTABLE_ACTION_FIELDS
338368
}
339-
if len(peer_actions) != len(parsed_actions):
369+
dropped_fields = set(parsed_actions) - set(peer_actions)
370+
_warn_if_peer_state_delta(parsed_actions)
371+
if dropped_fields:
340372
logger.debug(
341373
"Dropping ADK actions metadata fields that a peer may not set: %s",
342-
sorted(set(parsed_actions) - set(peer_actions)),
374+
sorted(dropped_fields),
343375
)
344376

345377
try:

‎tests/unittests/a2a/agent/test_remote_a2a_agent.py‎

Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,10 @@
4646
from google.adk.a2a.agent.utils import execute_after_request_interceptors
4747
from google.adk.a2a.agent.utils import execute_before_card_request_interceptors
4848
from google.adk.a2a.agent.utils import execute_before_request_interceptors
49+
from google.adk.a2a.converters import event_converter
50+
from google.adk.a2a.converters.from_adk_event import convert_event_to_a2a_events
4951
from google.adk.a2a.converters.part_converter import convert_genai_part_to_a2a_part
52+
from google.adk.a2a.converters.utils import _get_adk_metadata_key
5053
from google.adk.agents.invocation_context import InvocationContext
5154
from google.adk.agents.llm.task._finish_task_tool import FINISH_TASK_ERROR_RESULT
5255
from google.adk.agents.llm.task._finish_task_tool import FINISH_TASK_SUCCESS_RESULT
@@ -59,6 +62,7 @@
5962
from google.adk.auth.auth_credential import OAuth2Auth
6063
from google.adk.auth.auth_preprocessor import TOOLSET_AUTH_CREDENTIAL_ID_PREFIX
6164
from google.adk.events.event import Event
65+
from google.adk.events.event_actions import EventActions
6266
from google.adk.flows.llm_flows.context._fencing import QUOTED_CONTENT_BEGIN
6367
from google.adk.flows.llm_flows.context._fencing import QUOTED_CONTENT_END
6468
from google.adk.flows.llm_flows.tools._functions import REQUEST_EUC_FUNCTION_CALL_NAME
@@ -1600,6 +1604,24 @@ def test_construct_message_parts_from_session_user_input_metadata(self):
16001604
assert len(parts) == 1
16011605
assert _compat.part_metadata(parts[0]).get("is_user_input") is True
16021606

1607+
def test_construct_message_parts_warns_for_state_only_handoff(self, caplog):
1608+
"""A state-only hand-off warns before the remote receives stale content."""
1609+
self.mock_session.events = [
1610+
Event(
1611+
author="local_agent",
1612+
actions=EventActions(state_delta={"routing": "priority"}),
1613+
)
1614+
]
1615+
1616+
with caplog.at_level("WARNING"):
1617+
parts, context_id = self.agent._construct_message_parts_from_session(
1618+
self.mock_context
1619+
)
1620+
1621+
assert parts == []
1622+
assert context_id is None
1623+
assert "cannot forward the preceding state-only event" in caplog.text
1624+
16031625
def test_construct_message_parts_from_session_success_multiple_parts(self):
16041626
"""Test successful message parts construction from session."""
16051627
# Mock event with text content
@@ -3182,6 +3204,51 @@ def test_construct_message_parts_from_session_non_foreign_fr_not_converted_when_
31823204
assert parts[0] == mock_a2a_part
31833205
self.mock_genai_part_converter.assert_called_once_with(user_part)
31843206

3207+
def test_task_mode_state_warning_uses_latest_applicable_event(self, caplog):
3208+
"""An unrelated state-only event outside the task scope does not warn."""
3209+
task_scope = self.mock_context.isolation_scope
3210+
self.mock_genai_part_converter.return_value = _compat.make_text_part(
3211+
"converted"
3212+
)
3213+
trigger = _make_dummy_task_trigger_event(task_scope, self.agent.name)
3214+
applicable = Event(
3215+
author="user",
3216+
isolation_scope=task_scope,
3217+
content=genai_types.Content(parts=[genai_types.Part(text="hello")]),
3218+
)
3219+
unrelated_state_only = Event(
3220+
author="other",
3221+
isolation_scope="different-task",
3222+
actions=EventActions(state_delta={"routing": "priority"}),
3223+
)
3224+
self.mock_session.events = [trigger, applicable, unrelated_state_only]
3225+
3226+
with caplog.at_level("WARNING"):
3227+
self.agent._construct_message_parts_from_session(self.mock_context)
3228+
3229+
assert "cannot forward the preceding state-only event" not in caplog.text
3230+
3231+
def test_task_mode_state_warning_logs_for_state_only_event_in_scope(
3232+
self, caplog
3233+
):
3234+
"""A state-only event at the end of the task scope logs a warning."""
3235+
task_scope = self.mock_context.isolation_scope
3236+
self.mock_genai_part_converter.return_value = _compat.make_text_part(
3237+
"converted"
3238+
)
3239+
trigger = _make_dummy_task_trigger_event(task_scope, self.agent.name)
3240+
state_only_in_scope = Event(
3241+
author="local_agent",
3242+
isolation_scope=task_scope,
3243+
actions=EventActions(state_delta={"routing": "priority"}),
3244+
)
3245+
self.mock_session.events = [trigger, state_only_in_scope]
3246+
3247+
with caplog.at_level("WARNING"):
3248+
self.agent._construct_message_parts_from_session(self.mock_context)
3249+
3250+
assert "cannot forward the preceding state-only event" in caplog.text
3251+
31853252

31863253
class TestRemoteA2aAgentStreamingArtifactChunks:
31873254
"""Regression tests for chunked artifact streams."""
@@ -3239,6 +3306,150 @@ async def test_artifact_update_without_parts_is_ignored(self):
32393306
assert result is None
32403307

32413308

3309+
_PEER_STATE_DELTA_WARNING = (
3310+
"Ignoring a session state delta from a remote A2A peer"
3311+
)
3312+
3313+
3314+
class TestRemoteA2aAgentPeerStateDelta:
3315+
"""A remote peer's state delta is never applied, but dropping it is logged."""
3316+
3317+
def setup_method(self):
3318+
"""Setup test fixtures."""
3319+
self.agent = RemoteA2aAgent(
3320+
name="test_agent",
3321+
agent_card=create_test_agent_card(),
3322+
)
3323+
self.mock_context = Mock(spec=InvocationContext)
3324+
self.mock_context.invocation_id = "invocation-123"
3325+
self.mock_context.branch = "main"
3326+
3327+
def _remote_event(self, state_delta):
3328+
"""Build the final event of a remote LlmAgent(output_key="findings")."""
3329+
return Event(
3330+
author="remote_agent",
3331+
invocation_id="remote-invocation",
3332+
content=genai_types.Content(
3333+
role="model", parts=[genai_types.Part(text="the findings")]
3334+
),
3335+
actions=EventActions(state_delta=state_delta),
3336+
)
3337+
3338+
def _remote_invocation_context(self):
3339+
remote_context = Mock(spec=InvocationContext)
3340+
remote_context.app_name = "remote_app"
3341+
remote_context.user_id = "user"
3342+
remote_context.session = Mock(spec=Session)
3343+
remote_context.session.id = "remote-session"
3344+
return remote_context
3345+
3346+
def _working_task(self):
3347+
return _compat.make_task(
3348+
id="task-123",
3349+
status=_compat.make_task_status(_compat.TS_WORKING),
3350+
context_id="context-123",
3351+
)
3352+
3353+
async def _round_trip_legacy(self, state_delta):
3354+
"""Send a remote event through the default (legacy) server and client."""
3355+
updates = event_converter.convert_event_to_a2a_events(
3356+
self._remote_event(state_delta),
3357+
self._remote_invocation_context(),
3358+
"task-123",
3359+
"context-123",
3360+
)
3361+
return [
3362+
await self.agent._handle_a2a_response(
3363+
(self._working_task(), update), self.mock_context
3364+
)
3365+
for update in updates
3366+
]
3367+
3368+
@pytest.mark.asyncio
3369+
async def test_legacy_round_trip_warns_on_peer_state_delta(self, caplog):
3370+
"""The default client path logs a remote output_key it cannot apply."""
3371+
with caplog.at_level("WARNING"):
3372+
events = await self._round_trip_legacy({"findings": "the findings"})
3373+
3374+
assert _PEER_STATE_DELTA_WARNING in caplog.text
3375+
assert [event.content.parts[0].text for event in events] == ["the findings"]
3376+
assert all(event.actions.state_delta == {} for event in events)
3377+
3378+
@pytest.mark.asyncio
3379+
async def test_legacy_round_trip_without_state_delta_does_not_warn(
3380+
self, caplog
3381+
):
3382+
"""The legacy server sends stateDelta: {} on every event; ignore it."""
3383+
with caplog.at_level("WARNING"):
3384+
await self._round_trip_legacy({})
3385+
3386+
assert _PEER_STATE_DELTA_WARNING not in caplog.text
3387+
3388+
@pytest.mark.asyncio
3389+
async def test_legacy_full_task_warns_on_peer_state_delta(self, caplog):
3390+
"""A non-streaming client sees the delta merged into the task metadata."""
3391+
task = _compat.make_task(
3392+
id="task-123",
3393+
status=_compat.make_task_status(_compat.TS_COMPLETED),
3394+
context_id="context-123",
3395+
metadata={
3396+
_get_adk_metadata_key("actions"): {
3397+
"stateDelta": {"findings": "the findings"}
3398+
}
3399+
},
3400+
)
3401+
3402+
with caplog.at_level("WARNING"):
3403+
await self.agent._handle_a2a_response((task, None), self.mock_context)
3404+
3405+
assert _PEER_STATE_DELTA_WARNING in caplog.text
3406+
3407+
@pytest.mark.asyncio
3408+
async def test_legacy_message_warns_on_peer_state_delta(self, caplog):
3409+
"""A direct message response carrying a state delta also warns."""
3410+
message = _compat.make_message(
3411+
message_id="msg-1",
3412+
role=_compat.ROLE_AGENT,
3413+
parts=[_compat.make_text_part("the findings")],
3414+
metadata={
3415+
_get_adk_metadata_key("actions"): {
3416+
"stateDelta": {"findings": "the findings"}
3417+
}
3418+
},
3419+
)
3420+
3421+
with caplog.at_level("WARNING"):
3422+
event = await self.agent._handle_a2a_response(message, self.mock_context)
3423+
3424+
assert _PEER_STATE_DELTA_WARNING in caplog.text
3425+
assert event.actions.state_delta == {}
3426+
3427+
@pytest.mark.asyncio
3428+
async def test_new_integration_round_trip_warns_on_peer_state_delta(
3429+
self, caplog
3430+
):
3431+
"""The new integration path logs a remote output_key it cannot apply."""
3432+
updates = convert_event_to_a2a_events(
3433+
self._remote_event({"findings": "the findings"}),
3434+
{},
3435+
"task-123",
3436+
"context-123",
3437+
)
3438+
3439+
with caplog.at_level("WARNING"):
3440+
events = [
3441+
await self.agent._handle_a2a_response_v2(
3442+
(self._working_task(), update), self.mock_context
3443+
)
3444+
for update in updates
3445+
]
3446+
3447+
assert _PEER_STATE_DELTA_WARNING in caplog.text
3448+
events = [event for event in events if event]
3449+
assert [event.content.parts[0].text for event in events] == ["the findings"]
3450+
assert all(event.actions.state_delta == {} for event in events)
3451+
3452+
32423453
class TestRemoteA2aAgentMessageHandlingFromFactory:
32433454
"""Test message handling functionality."""
32443455

0 commit comments

Comments
 (0)