From 5ca1ed227ba25b58ee127cd100e46a9bb1e7a4ec Mon Sep 17 00:00:00 2001 From: Shivansh Sharma <286232336+SHAI-shivansh-sharma@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:42:33 +0530 Subject: [PATCH] feat(cli): replay selected tool responses in conformance tests Allow test specs to select agent tools whose recorded responses are returned without executing their bodies. Preserve verification of call order and arguments, reject missing recordings and missing ReplayPlugin before execution, and leave default replay behavior unchanged. Closes #7592 --- src/google/adk/cli/api_server.py | 27 +++ .../cli/conformance/adk_web_server_client.py | 6 + src/google/adk/cli/conformance/cli_test.py | 18 +- src/google/adk/cli/conformance/test_case.py | 3 + src/google/adk/cli/plugins/replay_plugin.py | 39 +++++ .../conformance/test_adk_web_server_client.py | 53 ++++++ .../cli/conformance/test_cli_test.py | 59 +++++++ .../conformance/test_generated_file_utils.py | 21 +++ .../cli/plugins/test_replay_plugin.py | 164 ++++++++++++++++++ tests/unittests/cli/test_fast_api.py | 33 ++++ 10 files changed, 422 insertions(+), 1 deletion(-) diff --git a/src/google/adk/cli/api_server.py b/src/google/adk/cli/api_server.py index 407b9892c56..a1d12178db7 100644 --- a/src/google/adk/cli/api_server.py +++ b/src/google/adk/cli/api_server.py @@ -2081,6 +2081,31 @@ def _set_telemetry_context_if_needed(runner: Runner) -> None: else: _is_visual_builder.set(False) + def _require_replay_plugin_for_recorded_responses( + runner: Runner, state_delta: Optional[dict[str, Any]] + ) -> None: + """Reject recorded tool replay before a run if its plugin is absent.""" + config = (state_delta or {}).get("_adk_replay_config") + if not isinstance(config, dict) or not config.get( + "replay_tool_responses" + ): + return + + from .plugins.replay_plugin import ReplayPlugin + + if not any( + isinstance(plugin, ReplayPlugin) + for plugin in runner.plugin_manager.plugins + ): + raise HTTPException( + status_code=400, + detail=( + "Recorded tool responses require ReplayPlugin. Start the" + " server with --extra_plugins" + " google.adk.cli.plugins.replay_plugin.ReplayPlugin." + ), + ) + @app.post( "/run", response_model=list[Event], response_model_exclude_none=True ) @@ -2094,6 +2119,7 @@ async def run_agent(req: RunAgentRequest, request: Request) -> Response: req.app_name = app_name self.current_app_name_ref.value = req.app_name runner = await self.get_runner_async(req.app_name) + _require_replay_plugin_for_recorded_responses(runner, req.state_delta) _set_telemetry_context_if_needed(runner) run_config = None if ( @@ -2186,6 +2212,7 @@ async def run_agent_sse(req: RunAgentRequest) -> StreamingResponse: self.current_app_name_ref.value = req.app_name stream_mode = StreamingMode.SSE if req.streaming else StreamingMode.NONE runner = await self.get_runner_async(req.app_name) + _require_replay_plugin_for_recorded_responses(runner, req.state_delta) _set_telemetry_context_if_needed(runner) # Build the run config before the response starts. Constructing it diff --git a/src/google/adk/cli/conformance/adk_web_server_client.py b/src/google/adk/cli/conformance/adk_web_server_client.py index bc1189617d1..8963f2768a4 100644 --- a/src/google/adk/cli/conformance/adk_web_server_client.py +++ b/src/google/adk/cli/conformance/adk_web_server_client.py @@ -235,6 +235,7 @@ async def run_agent( mode: Optional[Literal["record", "replay"]] = None, test_case_dir: Optional[str] = None, user_message_index: Optional[int] = None, + replay_tool_responses: Optional[dict[str, list[str]]] = None, ) -> AsyncGenerator[Event, None]: """Run an agent with streaming Server-Sent Events response. @@ -243,6 +244,7 @@ async def run_agent( mode: Optional conformance mode ("record" or "replay") to trigger recording test_case_dir: Optional test case directory path for conformance recording user_message_index: Optional user message index for conformance recording + replay_tool_responses: Agent tools that use recorded responses during replay Yields: Event objects streamed from the agent execution @@ -271,6 +273,10 @@ async def run_agent( "dir": str(test_case_dir), "user_message_index": user_message_index, } + if mode == "replay" and replay_tool_responses: + request.state_delta["_adk_replay_config"][ + "replay_tool_responses" + ] = replay_tool_responses if request.streaming: request.state_delta["_adk_replay_config"]["streaming_mode"] = "sse" else: diff --git a/src/google/adk/cli/conformance/cli_test.py b/src/google/adk/cli/conformance/cli_test.py index d7a5f645f89..dd4a6c1c8d6 100644 --- a/src/google/adk/cli/conformance/cli_test.py +++ b/src/google/adk/cli/conformance/cli_test.py @@ -184,6 +184,7 @@ async def _run_user_messages( mode="replay", test_case_dir=str(test_case.dir), user_message_index=user_message_index, + replay_tool_responses=test_case.test_spec.replay_tool_responses, ): if getattr(event, "partial", False): continue @@ -308,7 +309,22 @@ async def run_all_tests(self) -> _ConformanceTestSummary: results: list[_TestResult] = [] for test_case in test_cases: - click.echo(f"Running {test_case.category}/{test_case.name}...", nl=False) + replayed_tools = [ + f"{agent_name}.{tool_name}" + for agent_name, tool_names in ( + test_case.test_spec.replay_tool_responses.items() + ) + for tool_name in tool_names + ] + replay_detail = ( + f" (recorded tool responses: {', '.join(replayed_tools)})" + if self.mode == "replay" and replayed_tools + else "" + ) + click.echo( + f"Running {test_case.category}/{test_case.name}{replay_detail}...", + nl=False, + ) if self.mode == "replay": result = await self._run_test_case_replay(test_case) else: diff --git a/src/google/adk/cli/conformance/test_case.py b/src/google/adk/cli/conformance/test_case.py index a563dd4927d..0e849a88c98 100644 --- a/src/google/adk/cli/conformance/test_case.py +++ b/src/google/adk/cli/conformance/test_case.py @@ -59,6 +59,9 @@ class TestSpec(BaseModel): initial_state: dict[str, Any] = Field(default_factory=dict) """The initial state key-value pairs in the creation_session request.""" + replay_tool_responses: dict[str, list[str]] = Field(default_factory=dict) + """Agent names and tools that use recorded responses during replay.""" + user_messages: list[UserMessage] = Field(default_factory=list) """Sequence of user messages to send to the agent during test execution.""" diff --git a/src/google/adk/cli/plugins/replay_plugin.py b/src/google/adk/cli/plugins/replay_plugin.py index 39893bfbfcc..c1666e7e8d5 100644 --- a/src/google/adk/cli/plugins/replay_plugin.py +++ b/src/google/adk/cli/plugins/replay_plugin.py @@ -16,6 +16,7 @@ from __future__ import annotations +from copy import deepcopy import logging from pathlib import Path from typing import Any @@ -59,6 +60,7 @@ class _InvocationReplayState(BaseModel): test_case_path: str user_message_index: int recordings: Recordings + replay_tool_responses: dict[str, list[str]] = Field(default_factory=dict) # Per-agent replay indices for parallel execution # key: agent_name -> current tool replay index for that agent @@ -112,6 +114,24 @@ async def before_tool_callback( from google.adk.tools.agent_tool import AgentTool + use_recorded_response = tool.name in state.replay_tool_responses.get( + agent_name, () + ) + if use_recorded_response: + if isinstance(tool, AgentTool): + raise ReplayConfigError( + "Recorded response replay is not supported for AgentTool" + f" '{tool.name}'." + ) + if ( + recording.tool_response is None + or recording.tool_response.response is None + ): + raise ReplayVerificationError( + f"Tool recording for agent '{agent_name}' has no tool_response." + ) + return deepcopy(recording.tool_response.response) + if not isinstance(tool, AgentTool): # TODO: support replay requests and responses from AgentTool. await tool.run_async(args=tool_args, tool_context=tool_context) @@ -207,7 +227,26 @@ def _load_invocation_state( test_case_path=case_dir, user_message_index=msg_index, recordings=recordings, + replay_tool_responses=config.get("replay_tool_responses", {}), ) + recorded_tools = { + (recording.agent_name, recording.tool_recording.tool_call.name) + for recording in recordings.recordings + if recording.tool_recording and recording.tool_recording.tool_call + } + unknown_tools = { + (agent_name, tool_name) + for agent_name, tool_names in state.replay_tool_responses.items() + for tool_name in tool_names + } - recorded_tools + if unknown_tools: + raise ReplayConfigError( + "Recorded response replay selected tools absent from recordings: " + + ", ".join( + f"{agent_name}.{tool_name}" + for agent_name, tool_name in sorted(unknown_tools) + ) + ) self._invocation_states[invocation_id] = state logger.debug( "Loaded replay state for invocation %s: case_dir=%s, msg_index=%s, " diff --git a/tests/unittests/cli/conformance/test_adk_web_server_client.py b/tests/unittests/cli/conformance/test_adk_web_server_client.py index 531ebb7af4e..bb7e44d38ea 100644 --- a/tests/unittests/cli/conformance/test_adk_web_server_client.py +++ b/tests/unittests/cli/conformance/test_adk_web_server_client.py @@ -225,6 +225,59 @@ def mock_stream(*_args, **_kwargs): assert events[1].invocation_id == "test_invocation_2" +@pytest.mark.parametrize("streaming_mode", [False, True]) +async def test_replay_tool_selection_is_sent_to_server(streaming_mode): + """Replay selection reaches the server in the per-turn state delta.""" + client = AdkWebServerClient() + sent_requests = [] + + class EmptyStreamResponse: + + def raise_for_status(self): + pass + + async def aiter_lines(self): + if False: + yield "data:" + + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + pass + + def mock_stream(*_args, **kwargs): + sent_requests.append(kwargs["json"]) + return EmptyStreamResponse() + + with patch("httpx.AsyncClient") as mock_client_class: + mock_client = AsyncMock() + mock_client.stream = mock_stream + mock_client_class.return_value = mock_client + request = RunAgentRequest( + app_name="app", + user_id="user", + session_id="session", + streaming=streaming_mode, + ) + + async for _ in client.run_agent( + request, + mode="replay", + test_case_dir="case", + user_message_index=0, + replay_tool_responses={"agent_a": ["send_notice"]}, + ): + pass + + assert sent_requests[0]["stateDelta"]["_adk_replay_config"] == { + "dir": "case", + "user_message_index": 0, + "streaming_mode": "sse" if streaming_mode else "none", + "replay_tool_responses": {"agent_a": ["send_notice"]}, + } + + @pytest.mark.asyncio async def test_run_agent_raises_on_streamed_error(): client = AdkWebServerClient() diff --git a/tests/unittests/cli/conformance/test_cli_test.py b/tests/unittests/cli/conformance/test_cli_test.py index 7d4427bc4cf..8cd79f8d960 100644 --- a/tests/unittests/cli/conformance/test_cli_test.py +++ b/tests/unittests/cli/conformance/test_cli_test.py @@ -109,6 +109,65 @@ async def fake_run_agent(req, **kwargs): ) +async def test_run_user_messages_passes_selected_tools_to_replay_client(): + """The spec selection reaches every turn through the conformance client.""" + client = MagicMock() + received = [] + + async def fake_run_agent(request, **kwargs): + received.append(kwargs) + yield Event(author="agent_a") + + client.run_agent = fake_run_agent + runner = ConformanceTestRunner([], client) + test_case = TestCase( + category="cat", + name="tc", + dir=None, + test_spec=TestSpec( + description="replay notifications", + agent="app", + replay_tool_responses={"agent_a": ["send_notice"]}, + user_messages=[UserMessage(text="first"), UserMessage(text="second")], + ), + ) + + await runner._run_user_messages("session", test_case) + + assert [call["replay_tool_responses"] for call in received] == [ + {"agent_a": ["send_notice"]}, + {"agent_a": ["send_notice"]}, + ] + + +async def test_run_all_tests_reports_selected_tools(capsys): + """The test output makes skipped tool execution visible to the operator.""" + runner = ConformanceTestRunner([], MagicMock()) + test_case = TestCase( + category="cat", + name="tc", + dir=None, + test_spec=TestSpec( + description="replay notifications", + agent="app", + replay_tool_responses={"agent_a": ["send_notice"]}, + ), + ) + runner._discover_test_cases = lambda: [test_case] + + async def replay_case(_): + return _TestResult(category="cat", name="tc", success=True) + + runner._run_test_case_replay = replay_case + + await runner.run_all_tests() + + assert ( + "Running cat/tc (recorded tool responses: agent_a.send_notice)..." + in capsys.readouterr().out + ) + + @pytest.mark.asyncio async def test_run_user_messages_sse_partial_event_without_id_does_not_mask_final_id(): client = MagicMock() diff --git a/tests/unittests/cli/conformance/test_generated_file_utils.py b/tests/unittests/cli/conformance/test_generated_file_utils.py index 36ffbdd55b2..531d2de6a83 100644 --- a/tests/unittests/cli/conformance/test_generated_file_utils.py +++ b/tests/unittests/cli/conformance/test_generated_file_utils.py @@ -57,11 +57,32 @@ def test_load_test_case_parses_spec_and_applies_declared_defaults(tmp_path): assert spec.agent == 'dice_agent' # Omitted field falls back to its documented empty default. assert spec.initial_state == {} + assert spec.replay_tool_responses == {} assert [m.text for m in spec.user_messages] == ['roll a die', 'roll again'] assert spec.user_messages[0].state_delta is None assert spec.user_messages[1].state_delta == {'rolls': 1} +def test_load_test_case_reads_recorded_tool_selection(tmp_path): + """A per-agent tool selection can be declared in spec.yaml.""" + _write_spec( + tmp_path, + """\ + description: replay notifications + agent: app + replay_tool_responses: + agent_a: + - send_notice + user_messages: + - text: notify + """, + ) + + spec = load_test_case(tmp_path) + + assert spec.replay_tool_responses == {'agent_a': ['send_notice']} + + def test_load_test_case_rejects_unknown_spec_field(tmp_path): """TestSpec forbids extras so a typo in a hand-written spec is not silent.""" _write_spec( diff --git a/tests/unittests/cli/plugins/test_replay_plugin.py b/tests/unittests/cli/plugins/test_replay_plugin.py index 326d862cef1..ea6bc031b57 100644 --- a/tests/unittests/cli/plugins/test_replay_plugin.py +++ b/tests/unittests/cli/plugins/test_replay_plugin.py @@ -24,6 +24,7 @@ from google.adk.cli.plugins.replay_plugin import ReplayConfigError from google.adk.cli.plugins.replay_plugin import ReplayPlugin from google.adk.cli.plugins.replay_plugin import ReplayVerificationError +from google.adk.tools.agent_tool import AgentTool from google.adk.tools.base_tool import BaseTool from google.adk.utils.yaml_utils import dump_pydantic_to_yaml from google.genai import types @@ -87,6 +88,7 @@ async def _make_invocation( user_message_index: int = 0, streaming_mode: Optional[str] = 'none', agent_names: tuple[str, ...] = ('agent_a',), + replay_tool_responses: Optional[dict[str, list[str]]] = None, ): """Builds one invocation plus a per-agent context sharing its session.""" invocation_context = await testing_utils.create_invocation_context( @@ -99,6 +101,8 @@ async def _make_invocation( } if streaming_mode is not None: config['streaming_mode'] = streaming_mode + if replay_tool_responses is not None: + config['replay_tool_responses'] = replay_tool_responses invocation_context.session.state['_adk_replay_config'] = config contexts = {agent_names[0]: CallbackContext(invocation_context)} @@ -182,6 +186,166 @@ async def test_before_tool_still_executes_the_underlying_tool(tmp_path): assert tool.live_calls == [{'sides': 6}] +@pytest.mark.parametrize( + ('streaming_mode', 'file_name'), + [('none', _NON_STREAMING_FILE), ('sse', _STREAMING_FILE)], +) +async def test_selected_tool_uses_recorded_response_without_executing( + tmp_path, streaming_mode, file_name +): + """Selected tools use the verified response without contacting a backend.""" + _write_recordings( + tmp_path, [_recording(response={'result': 4})], file_name=file_name + ) + plugin = ReplayPlugin() + invocation_context, contexts = await _make_invocation( + case_dir=tmp_path, + streaming_mode=streaming_mode, + replay_tool_responses={'agent_a': ['roll_die']}, + ) + tool = _SpyTool() + + await plugin.before_run_callback(invocation_context=invocation_context) + replayed = await plugin.before_tool_callback( + tool=tool, tool_args={'sides': 6}, tool_context=contexts['agent_a'] + ) + + assert replayed == {'result': 4} + assert tool.live_calls == [] + + +async def test_selected_tool_replays_repeated_calls_in_recorded_order(tmp_path): + """Repeated selected calls return their recorded responses in order.""" + _write_recordings( + tmp_path, + [ + _recording(response={'result': 4}), + _recording(response={'result': 7}, call_id='fc-2'), + ], + ) + plugin = ReplayPlugin() + invocation_context, contexts = await _make_invocation( + case_dir=tmp_path, + replay_tool_responses={'agent_a': ['roll_die']}, + ) + tool = _SpyTool() + + await plugin.before_run_callback(invocation_context=invocation_context) + first = await plugin.before_tool_callback( + tool=tool, tool_args={'sides': 6}, tool_context=contexts['agent_a'] + ) + second = await plugin.before_tool_callback( + tool=tool, tool_args={'sides': 6}, tool_context=contexts['agent_a'] + ) + + assert [first, second] == [{'result': 4}, {'result': 7}] + assert tool.live_calls == [] + + +async def test_selection_is_scoped_to_agent(tmp_path): + """A tool selected for one agent still executes for a sibling agent.""" + _write_recordings( + tmp_path, + [_recording(agent_name='agent_a'), _recording(agent_name='agent_b')], + ) + plugin = ReplayPlugin() + invocation_context, contexts = await _make_invocation( + case_dir=tmp_path, + agent_names=('agent_a', 'agent_b'), + replay_tool_responses={'agent_a': ['roll_die']}, + ) + selected_tool = _SpyTool() + other_tool = _SpyTool() + + await plugin.before_run_callback(invocation_context=invocation_context) + selected_result = await plugin.before_tool_callback( + tool=selected_tool, + tool_args={'sides': 6}, + tool_context=contexts['agent_a'], + ) + other_result = await plugin.before_tool_callback( + tool=other_tool, + tool_args={'sides': 6}, + tool_context=contexts['agent_b'], + ) + + assert selected_result == other_result == {'result': 4} + assert selected_tool.live_calls == [] + assert other_tool.live_calls == [{'sides': 6}] + + +async def test_selected_tool_with_mismatched_args_never_executes(tmp_path): + """A mismatched recorded call fails before a selected tool runs.""" + _write_recordings(tmp_path, [_recording(args={'sides': 6})]) + plugin = ReplayPlugin() + invocation_context, contexts = await _make_invocation( + case_dir=tmp_path, + replay_tool_responses={'agent_a': ['roll_die']}, + ) + tool = _SpyTool() + + await plugin.before_run_callback(invocation_context=invocation_context) + with pytest.raises(ReplayVerificationError, match='Tool args mismatch'): + await plugin.before_tool_callback( + tool=tool, tool_args={'sides': 20}, tool_context=contexts['agent_a'] + ) + + assert tool.live_calls == [] + + +async def test_unknown_selected_tool_fails_before_agent_runs(tmp_path): + """A typo in the selection cannot silently leave a live tool enabled.""" + _write_recordings(tmp_path, [_recording()]) + plugin = ReplayPlugin() + invocation_context, _ = await _make_invocation( + case_dir=tmp_path, + replay_tool_responses={'agent_a': ['roll_dice']}, + ) + + with pytest.raises(ReplayConfigError, match='agent_a.roll_dice'): + await plugin.before_run_callback(invocation_context=invocation_context) + + +async def test_selected_tool_without_recorded_response_never_executes(tmp_path): + """A missing recorded response fails without falling back to a live tool.""" + recording = _recording() + recording.tool_recording.tool_response = None + _write_recordings(tmp_path, [recording]) + plugin = ReplayPlugin() + invocation_context, contexts = await _make_invocation( + case_dir=tmp_path, + replay_tool_responses={'agent_a': ['roll_die']}, + ) + tool = _SpyTool() + + await plugin.before_run_callback(invocation_context=invocation_context) + with pytest.raises(ReplayVerificationError, match='no tool_response'): + await plugin.before_tool_callback( + tool=tool, tool_args={'sides': 6}, tool_context=contexts['agent_a'] + ) + + assert tool.live_calls == [] + + +async def test_selected_agent_tool_is_rejected(tmp_path): + """AgentTool has different execution semantics and cannot be response-only.""" + _write_recordings(tmp_path, [_recording(tool_name='child')]) + plugin = ReplayPlugin() + invocation_context, contexts = await _make_invocation( + case_dir=tmp_path, + replay_tool_responses={'agent_a': ['child']}, + ) + child_tool = AgentTool(agent=testing_utils.create_test_agent(name='child')) + + await plugin.before_run_callback(invocation_context=invocation_context) + with pytest.raises(ReplayConfigError, match='AgentTool'): + await plugin.before_tool_callback( + tool=child_tool, + tool_args={'sides': 6}, + tool_context=contexts['agent_a'], + ) + + async def test_before_run_reads_the_sse_file_in_sse_streaming_mode(tmp_path): """streaming_mode selects which recordings file is authoritative.""" _write_recordings( diff --git a/tests/unittests/cli/test_fast_api.py b/tests/unittests/cli/test_fast_api.py index d754a35fa8c..70bd9fcaf7c 100755 --- a/tests/unittests/cli/test_fast_api.py +++ b/tests/unittests/cli/test_fast_api.py @@ -2458,6 +2458,39 @@ def test_agent_run_passes_state_delta(test_app, create_test_session): assert data[3]["actions"]["stateDelta"] == payload["state_delta"] +@pytest.mark.parametrize("endpoint", ["/run", "/run_sse"]) +def test_recorded_tool_replay_requires_plugin( + test_app, create_test_session, monkeypatch, endpoint +): + """A missing replay plugin rejects the request before running any tool.""" + info = create_test_session + run_called = False + + async def unexpected_run(*args, **kwargs): + nonlocal run_called + run_called = True + yield None + + monkeypatch.setattr(Runner, "run_async", unexpected_run) + payload = { + "app_name": info["app_name"], + "user_id": info["user_id"], + "session_id": info["session_id"], + "new_message": {"role": "user", "parts": [{"text": "Hello"}]}, + "state_delta": { + "_adk_replay_config": { + "replay_tool_responses": {"agent_a": ["roll_die"]} + } + }, + } + + response = test_app.post(endpoint, json=payload) + + assert response.status_code == 400 + assert "ReplayPlugin" in response.json()["detail"] + assert not run_called + + def test_agent_run_passes_invocation_id( test_app, create_test_session, monkeypatch ):