From 559aa6a12831acdef831c758bd19f4823049175a Mon Sep 17 00:00:00 2001 From: sushant-me Date: Thu, 8 Oct 2026 02:19:46 +0545 Subject: [PATCH 1/4] fix(a2a): stop returning exception text to remote peers The A2A executor put str(exception) into the peer-visible failed-task response. A remote caller that can reach the endpoint therefore receives server-side detail: absolute filesystem paths, module locations, configuration-key names and upstream error text - none of which the peer needs, all of which is useful reconnaissance. The throwable is already logged in full. It is now logged under a short opaque correlation id, and the peer gets only: Agent execution failed. (error_id: <12 hex chars>) Ports the behaviour of adk-java a3df463. ADK_DEBUG_ERRORS=1 restores the old peer-visible text, for local debugging only and off by default. Verified: ./pytest tests/unittests/a2a/executor/test_a2a_agent_executor.py 32 passed (30 pre-existing + 2 new) Fixes #7445 --- .../adk/a2a/executor/a2a_agent_executor.py | 51 +++++++++++++++++- .../a2a/executor/test_a2a_agent_executor.py | 54 +++++++++++++++++++ 2 files changed, 103 insertions(+), 2 deletions(-) diff --git a/src/google/adk/a2a/executor/a2a_agent_executor.py b/src/google/adk/a2a/executor/a2a_agent_executor.py index 9b655c39412..5ad6bdfa10f 100644 --- a/src/google/adk/a2a/executor/a2a_agent_executor.py +++ b/src/google/adk/a2a/executor/a2a_agent_executor.py @@ -16,6 +16,7 @@ import inspect import logging +import os from typing import Awaitable from typing import Callable @@ -43,6 +44,44 @@ from .utils import _enqueue_canceled_task_event from .utils import _require_request_context from .utils import execute_after_agent_interceptors + +#: Env var that puts exception text back into the failure message sent to the peer. +#: Off by default, and meant for local debugging only: enabling it on a +#: network-reachable deployment restores the disclosure the opaque id exists to +#: prevent. +_DEBUG_ERRORS_ENV_VAR = 'ADK_DEBUG_ERRORS' + +#: Length of the correlation id, matching ``newErrorId()`` in adk-java. +_ERROR_ID_LENGTH = 12 + +#: Fixed summary the peer receives. It deliberately carries no throwable text. +_FAILURE_SUMMARY = 'Agent execution failed.' + + +def _new_error_id() -> str: + """Returns a short opaque id correlating a peer-visible failure with the log.""" + return platform_uuid.new_uuid().replace('-', '')[:_ERROR_ID_LENGTH] + + +def _debug_errors_enabled() -> bool: + """Whether exception text should be echoed to the peer. Local debugging only.""" + value = os.environ.get(_DEBUG_ERRORS_ENV_VAR, '') + return value.strip().lower() in ('1', 'true', 'yes', 'on') + + +def failure_text(error: Exception, error_id: str) -> str: + """Builds the failure text handed back to the remote peer. + + The peer is not trusted with the throwable: exception text routinely names + absolute filesystem paths, module locations, configuration values and echoed + request payloads, none of which the caller needs and all of which are useful + reconnaissance. Set ``ADK_DEBUG_ERRORS=1`` to restore the old behaviour while + debugging locally. + """ + text = f'{_FAILURE_SUMMARY} (error_id: {error_id})' + if _debug_errors_enabled(): + text = f'{text} {error}' + return text from .utils import execute_after_event_interceptors from .utils import execute_before_agent_interceptors @@ -152,7 +191,15 @@ async def execute( try: await self._handle_request(context, event_queue) except Exception as e: - logger.error('Error handling A2A request: %s', e, exc_info=True) + # Logged in full here, under a short opaque id. The peer receives only that + # id, never the throwable text - see failure_text(). + error_id = _new_error_id() + logger.error( + 'Error handling A2A request [error_id=%s]: %s', + error_id, + e, + exc_info=True, + ) # Publish failure event try: await event_queue.enqueue_event( @@ -164,7 +211,7 @@ async def execute( message=Message( message_id=platform_uuid.new_uuid(), role=_compat.ROLE_AGENT, - parts=[_compat.make_text_part(str(e))], + parts=[_compat.make_text_part(failure_text(e, error_id))], ), ), final=True, diff --git a/tests/unittests/a2a/executor/test_a2a_agent_executor.py b/tests/unittests/a2a/executor/test_a2a_agent_executor.py index ad52123d50d..7a8a7923f20 100644 --- a/tests/unittests/a2a/executor/test_a2a_agent_executor.py +++ b/tests/unittests/a2a/executor/test_a2a_agent_executor.py @@ -13,6 +13,8 @@ # limitations under the License. import asyncio +import os +import re from unittest.mock import AsyncMock from unittest.mock import Mock from unittest.mock import patch @@ -90,6 +92,15 @@ def _final_events(call_args_list): return [e for e in events if getattr(e, "final", False)] +def _part_text(part) -> str: + """Reads the text out of a Part on both A2A v1 (flat) and 0.3.x (union).""" + direct = getattr(part, 'text', None) + if direct: + return direct + root = getattr(part, 'root', None) + return getattr(root, 'text', '') or '' + + class TestA2aAgentExecutor: """Test suite for A2aAgentExecutor class.""" @@ -289,6 +300,49 @@ def test_check_new_version_extension_activation_is_version_aware(self): _NEW_A2A_ADK_INTEGRATION_EXTENSION ) + @pytest.mark.asyncio + async def test_failure_event_does_not_leak_exception_text(self): + """The remote peer must not receive the throwable's message.""" + secret = ( + 'Runner error: /home/victim/.config/adk/credentials.json (No such file)' + ) + self.executor._handle_request = AsyncMock(side_effect=RuntimeError(secret)) + + await self.executor.execute(self.mock_context, self.mock_event_queue) + + events = [c.args[0] for c in self.mock_event_queue.enqueue_event.call_args_list] + statuses = [ + e.status + for e in events + if getattr(e, 'status', None) is not None + ] + assert statuses, 'a failed status event should reach the peer' + parts = statuses[-1].message.parts + text = ''.join(_part_text(p) for p in parts) + + assert re.fullmatch( + r'Agent execution failed\. \(error_id: [0-9a-f]{12}\)', text + ), text + assert secret not in text + assert '/home/victim' not in text + + @pytest.mark.asyncio + async def test_failure_event_leaks_when_debug_errors_enabled(self): + """ADK_DEBUG_ERRORS restores exception text, for local debugging only.""" + secret = 'boom at /home/victim/secret' + self.executor._handle_request = AsyncMock(side_effect=RuntimeError(secret)) + + with patch.dict(os.environ, {'ADK_DEBUG_ERRORS': '1'}): + await self.executor.execute(self.mock_context, self.mock_event_queue) + + events = [c.args[0] for c in self.mock_event_queue.enqueue_event.call_args_list] + statuses = [ + e.status for e in events if getattr(e, 'status', None) is not None + ] + parts = statuses[-1].message.parts + text = ''.join(_part_text(p) for p in parts) + assert secret in text + @pytest.mark.asyncio async def test_execute_no_message_error(self): """Test execution fails when no message is provided.""" From b1415505a014732cd98ba3bdda94cf7e8b4b00f4 Mon Sep 17 00:00:00 2001 From: sushant-me Date: Thu, 8 Oct 2026 02:23:56 +0545 Subject: [PATCH 2/4] fix(tools): do not carry removed parameters' annotations onto the legacy declaration build_function_declaration drops the ignored parameters (tool_context) from the signature rebuilt for the legacy JSON-schema-disabled path, but copied the original __annotations__ mapping wholesale. typing.get_type_hints() then resolved annotations for parameters that were no longer present, so a context parameter annotated with a TYPE_CHECKING-only import raised: NameError: name 'ToolContext' is not defined Only annotations for parameters that survive into the new signature are copied now. This is the legacy-path counterpart of 2ecb3fb0, which fixed the same symptom on the JSON-schema path. Verified: ADK_DISABLE_JSON_SCHEMA_FOR_FUNC_DECL=1 python repro.py -> builds, city only pytest test_function_tool_with_import_annotations.py test_function_tool.py 86 passed (85 pre-existing + 1 new) --- .../tools/_automatic_function_calling_util.py | 11 ++++++- ...t_function_tool_with_import_annotations.py | 29 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/google/adk/tools/_automatic_function_calling_util.py b/src/google/adk/tools/_automatic_function_calling_util.py index 831ee5567d0..02682cbcc9e 100644 --- a/src/google/adk/tools/_automatic_function_calling_util.py +++ b/src/google/adk/tools/_automatic_function_calling_util.py @@ -272,7 +272,16 @@ def build_function_declaration( ) setattr(new_func, '__signature__', new_sig) new_func.__doc__ = original.__doc__ - new_func.__annotations__ = original.__annotations__ + # Only carry over annotations for parameters that survive into new_sig. Copying the + # original mapping wholesale leaves annotations for the ignored parameters in place, + # and typing.get_type_hints() then tries to resolve them - so a context parameter + # annotated with a TYPE_CHECKING-only import raises NameError even though the + # parameter is not part of the declaration. + new_func.__annotations__ = { + name: annotation + for name, annotation in original.__annotations__.items() + if name not in ignore_params + } return from_function_with_options(new_func, variant) diff --git a/tests/unittests/tools/test_function_tool_with_import_annotations.py b/tests/unittests/tools/test_function_tool_with_import_annotations.py index c917bc2ca64..0e98af4af19 100644 --- a/tests/unittests/tools/test_function_tool_with_import_annotations.py +++ b/tests/unittests/tools/test_function_tool_with_import_annotations.py @@ -14,6 +14,7 @@ from __future__ import annotations +import os from typing import Any from typing import Dict from typing import Optional @@ -23,6 +24,7 @@ from google.adk.utils.variant_utils import GoogleLLMVariant from google.genai import types import pydantic +from unittest.mock import patch def test_string_annotation_none_return_vertex(): @@ -284,3 +286,30 @@ def function_with_optional_list( assert all(isinstance(item, ItemModel) for item in processed_args['items']) assert processed_args['items'][0].quantity == 10 assert processed_args['items'][1].quantity == 5 + +def test_context_param_imported_only_under_type_checking_legacy_path(): + """A context parameter annotated via TYPE_CHECKING must not break the legacy path. + + build_function_declaration drops the ignored parameters from the signature. When it + copied every original annotation onto the new function, typing.get_type_hints() then + tried to resolve the removed parameter's annotation too - so a context parameter + typed by a TYPE_CHECKING-only import raised NameError even though it is not part of + the declaration. This is the legacy-path counterpart of the JSON-schema fix. + """ + + def test_function(city: str, tool_context: ToolContext) -> str: # noqa: F821 + """A test function whose context parameter is imported only for type checking.""" + return f'Sunny in {city}' + + # The JSON-schema path is on by default; disable it so this exercises the legacy + # declaration builder, which is where the bug lived. + with patch.dict(os.environ, {'ADK_DISABLE_JSON_SCHEMA_FOR_FUNC_DECL': '1'}): + # signature is (func, ignore_params=None, variant=GEMINI_API) + declaration = _automatic_function_calling_util.build_function_declaration( + test_function, + ignore_params=['tool_context'], + ) + + assert sorted(declaration.parameters.properties) == ['city'] + assert declaration.parameters.properties['city'].type == 'STRING' + assert declaration.parameters.required == ['city'] From 4e7bd8b638a2d6189edbf6e97ea77f702d174b78 Mon Sep 17 00:00:00 2001 From: sushant-me Date: Thu, 8 Oct 2026 02:25:50 +0545 Subject: [PATCH 3/4] test(gke): give the mocked Job the string fields kubernetes 37 requires kubernetes 37.0.0 validates model fields with pydantic. The mock_k8s_clients fixture never configured create_namespaced_job's return value, so it handed back the default MagicMock. GkeCodeExecutor._add_owner_reference copies that Job's api_version, kind, metadata.name and metadata.uid into a V1OwnerReference, and those MagicMock values no longer validate as strings: ValidationError: 4 validation errors for V1OwnerReference api_version Input should be a valid string [input_type=MagicMock] execute_code caught the error and returned 'An unexpected executor error occurred', so five assertions failed and the Unit Tests jobs went red on main for Python 3.11-3.14. The fixture now returns a V1Job carrying the string fields a real cluster returns, which is what the production path sees. No executor code changes. Verified with kubernetes 37.0.0: pytest tests/unittests/code_executors/test_gke_code_executor.py 18 passed (0 failed; previously 5 failed) Fixes #7443 --- tests/unittests/code_executors/test_gke_code_executor.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/unittests/code_executors/test_gke_code_executor.py b/tests/unittests/code_executors/test_gke_code_executor.py index c3230859014..012c46ccab6 100644 --- a/tests/unittests/code_executors/test_gke_code_executor.py +++ b/tests/unittests/code_executors/test_gke_code_executor.py @@ -54,6 +54,15 @@ def mock_k8s_clients(): mock_core_v1 = MagicMock(spec=client.CoreV1Api) mock_client_class.BatchV1Api.return_value = mock_batch_v1 mock_client_class.CoreV1Api.return_value = mock_core_v1 + # _add_owner_reference copies these four fields into a V1OwnerReference, and + # kubernetes 37 validates their types with pydantic. An unconfigured MagicMock + # returns a MagicMock for each, which no longer validates as a string, so give + # the created Job the string fields a real cluster would return. + mock_batch_v1.create_namespaced_job.return_value = client.V1Job( + api_version="batch/v1", + kind="Job", + metadata=client.V1ObjectMeta(name="test-job-name", uid="test-job-uid"), + ) yield { "batch_v1": mock_batch_v1, "core_v1": mock_core_v1, From 932e404b6b653dc98e1fa8be7290c7820e5aa32d Mon Sep 17 00:00:00 2001 From: sushant-me Date: Thu, 8 Oct 2026 02:33:25 +0545 Subject: [PATCH 4/4] fix(litellm): keep the thought_signature on a streamed tool call Gemini thinking models attach a thought_signature to each function call. On the OpenAI-compatible route it rides in extra_content.google.thought_signature (Vertex also uses provider_specific_fields). The non-streaming conversion kept it; the streaming reassembly dropped it, so the tool call ADK stored carried no signature and Gemini rejected the follow-up request: Function call is missing a thought_signature in functionCall parts. The raw streamed delta had the field all along - _model_response_to_chunk simply copied only id/name/args/index into FunctionChunk, which had nowhere to hold it. - FunctionChunk gains extra_content and provider_specific_fields - _model_response_to_chunk copies both off the raw delta - the streaming accumulator seeds and merges them per index - _finalize_tool_call_response passes them onto the reconstructed tool call Verified: the new test fails without this change (AttributeError: 'FunctionChunk' object has no attribute 'extra_content') and passes with it. The full tests/unittests/models/test_litellm.py suite is unchanged at 509 passed / 27 pre-existing errors, with and without the change. Fixes #7438 --- src/google/adk/models/lite_llm.py | 26 ++++- .../test_litellm_stream_thought_signature.py | 100 ++++++++++++++++++ 2 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 tests/unittests/models/test_litellm_stream_thought_signature.py diff --git a/src/google/adk/models/lite_llm.py b/src/google/adk/models/lite_llm.py index 5b8ee90b351..971324ea171 100644 --- a/src/google/adk/models/lite_llm.py +++ b/src/google/adk/models/lite_llm.py @@ -1012,6 +1012,14 @@ class FunctionChunk(BaseModel): name: Optional[str] args: Optional[str] index: Optional[int] = 0 + # Signature-bearing fields: Gemini thinking models attach a thought_signature to + # each function call, and on the OpenAI-compatible route it rides in + # extra_content.google.thought_signature (Vertex also uses + # provider_specific_fields). The streamed delta carries them, so they must be + # captured here or the reassembled tool call loses the signature and the + # follow-up request is rejected. + extra_content: Optional[dict] = None + provider_specific_fields: Optional[dict] = None class TextChunk(BaseModel): @@ -2710,6 +2718,8 @@ def _has_meaningful_signal(message: Message | Delta | None) -> bool: name=func_name, args=func_args, index=func_index, + extra_content=tool_call.get("extra_content"), + provider_specific_fields=tool_call.get("provider_specific_fields"), ), finish_reason if finish_reason and not (message_content or tool_calls or reasoning_parts): @@ -3817,6 +3827,8 @@ def _finalize_tool_call_response( arguments=args, ), index=index, + extra_content=func_data.get("extra_content"), + provider_specific_fields=func_data.get("provider_specific_fields"), ) ) @@ -3927,7 +3939,13 @@ def _reset_stream_buffers() -> None: if isinstance(chunk, FunctionChunk): index = chunk.index or fallback_index if index not in function_calls: - function_calls[index] = {"name": "", "args_parts": [], "id": None} + function_calls[index] = { + "name": "", + "args_parts": [], + "id": None, + "extra_content": None, + "provider_specific_fields": None, + } if chunk.name: function_calls[index]["name"] += chunk.name @@ -3950,6 +3968,12 @@ def _reset_stream_buffers() -> None: function_calls[index]["id"] = ( chunk.id or function_calls[index]["id"] or str(index) ) + if chunk.extra_content: + function_calls[index]["extra_content"] = chunk.extra_content + if chunk.provider_specific_fields: + function_calls[index]["provider_specific_fields"] = ( + chunk.provider_specific_fields + ) partial_args = None if chunk.args: diff --git a/tests/unittests/models/test_litellm_stream_thought_signature.py b/tests/unittests/models/test_litellm_stream_thought_signature.py new file mode 100644 index 00000000000..b39f2c340f6 --- /dev/null +++ b/tests/unittests/models/test_litellm_stream_thought_signature.py @@ -0,0 +1,100 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Streaming must keep the thought_signature Gemini attaches to a tool call. + +Gemini thinking models attach a thought_signature to each function call. On the +OpenAI-compatible route it rides in extra_content.google.thought_signature (Vertex +also uses provider_specific_fields). If the streaming reassembly drops it, the tool +call ADK stores carries no signature and Gemini rejects the follow-up request: + + Function call is missing a thought_signature in functionCall parts. +""" + +from litellm.types.utils import ChatCompletionDeltaToolCall +from litellm.types.utils import Delta +from litellm.types.utils import ModelResponseStream +from litellm.types.utils import StreamingChoices + +from google.adk.models.lite_llm import _model_response_to_chunk +from google.adk.models.lite_llm import FunctionChunk + +_SIGNATURE = "b3BhcXVlLXNpZ25hdHVyZQ==" + + +def _streamed_tool_call_response(**tool_call_extras): + """One streamed chunk carrying a complete tool call.""" + tool_call = ChatCompletionDeltaToolCall( + index=0, + id="call_1", + type="function", + function={"name": "get_weather", "arguments": '{"city": "Paris"}'}, + **tool_call_extras, + ) + return ModelResponseStream( + model="test_model", + choices=[ + StreamingChoices( + finish_reason=None, + delta=Delta(role="assistant", tool_calls=[tool_call]), + ) + ], + ) + + +def _function_chunks(response): + return [ + chunk + for chunk, _ in _model_response_to_chunk(response) + if isinstance(chunk, FunctionChunk) + ] + + +def test_streaming_keeps_extra_content_thought_signature(): + """The OpenAI-compatible route carries the signature in extra_content.google.""" + response = _streamed_tool_call_response( + extra_content={"google": {"thought_signature": _SIGNATURE}} + ) + + chunks = _function_chunks(response) + + assert len(chunks) == 1 + assert chunks[0].name == "get_weather" + # The regression: this was discarded while the streamed call was reassembled. + assert chunks[0].extra_content == {"google": {"thought_signature": _SIGNATURE}} + + +def test_streaming_keeps_provider_specific_fields_signature(): + """The Vertex route carries it in provider_specific_fields instead.""" + response = _streamed_tool_call_response( + provider_specific_fields={"thought_signature": _SIGNATURE} + ) + + chunks = _function_chunks(response) + + assert len(chunks) == 1 + assert chunks[0].provider_specific_fields == { + "thought_signature": _SIGNATURE + } + + +def test_streaming_without_signature_still_works(): + """A plain tool call keeps working; the new fields stay None.""" + response = _streamed_tool_call_response() + + chunks = _function_chunks(response) + + assert len(chunks) == 1 + assert chunks[0].extra_content is None + assert chunks[0].provider_specific_fields is None