Skip to content

[Feature] Allow conformance replay to use recorded responses without executing selected tools #7592

Description

@SHAI-shivansh-sharma

Is your feature request related to a specific problem?

Conformance replay currently runs ordinary tool bodies even when the complete response is already recorded. For an agent with a tool such as send_notice or create_ticket, replaying a baseline can repeat the external operation. It also still depends on that backend being available: an exception from the live tool prevents the recorded response from being returned.

I reproduced this on upstream main at a6ed85905d4c1d1f285ba9d4f76a9d801b66d17f (Python 3.12.10, Windows). In ReplayPlugin.before_tool_callback, the plugin validates the recorded call, awaits tool.run_async() for non-AgentTool tools, then returns the recorded response.

The existing test_before_tool_still_executes_the_underlying_tool explicitly tests this behavior. This request is therefore for an opt-in capability, not a change to the default.

Describe the Solution You'd Like

Allow a conformance test to select ordinary tools whose recorded responses are replayed without executing their tool bodies, while retaining the existing strict call-name, argument, agent and turn matching.

For example, a proposed addition to spec.yaml (name open to discussion):

description: Verify the notification workflow against its recorded baseline
agent: notification_app
replay_tool_responses:
  agent_a:
    - send_notice
user_messages:
  - text: Notify the support team

The mapping is keyed by the invoking agent name, then tool names. Omitting it preserves current behavior; unselected tools still execute as today.

For a selected tool, a missing/malformed recording or mismatched call must fail the test without falling back to executing the tool. A valid recording should return its response even if the real tool implementation would raise.

Impact on your work

The intended use is to run baseline regression checks in CI for agents that call external services, without repeating those selected operations or requiring those backends at tool-execution time. It would reuse the existing recorded fixtures and conformance comparisons instead of maintaining a second set of mocks. This is a development-workflow improvement; there is no production deadline claimed here.

Willingness to contribute

Yes. I can contribute a focused implementation, regression tests and corresponding documentation after agreement on the scope and configuration.

Describe Alternatives You've Considered

  • Environment simulation: ADK already supports tool-response injection. The gap is consuming the existing conformance recordings with their ordered, per-agent/per-turn matching. Putting a simulation plugin before ReplayPlugin short-circuits its tool verification; putting it after ReplayPlugin does not intercept the direct tool.run_async() call.
  • Custom ReplayPlugin subclass or monkeypatch: feasible, but it duplicates internal recording lookup and validation to change only the execution decision.
  • Separate sandbox backends: useful for integration tests, but still requires credentials, service availability and cleanup for every replay.

Proposed API / Implementation

Keep the first iteration limited to explicitly selected ordinary tools:

  1. Pass the test's selection through the conformance client into the per-invocation replay configuration.
  2. Resolve and validate the existing recording before deciding whether to execute the tool.
  3. For selected tools, return a copy of the recorded response without calling run_async; leave the default path unchanged.
  4. Report the selection in test output so that a passing replay is not mistaken for coverage of those tool implementations.

Scope limits: current ToolRecording stores a call and response, not the tool's state deltas, artifacts, or control-flow actions. A selected tool must be one whose returned response is sufficient for this test; tools that modify ADK state, transfer control, request approval, or write artifacts should continue on the existing path. Existing session/event comparison must remain enabled so differences still fail. Automatic reconstruction of those effects, AgentTool support, and a recording-schema change are outside this initial proposal.

This does not promise a network sandbox: agent imports, dynamic tool discovery and other callbacks can still perform I/O.

Validation and Additional Context

An isolated reproduction with an in-memory counting tool produced:

matched: live_calls=1, returned={'receipt': 'recorded'}
unavailable: live_calls=1, error=RuntimeError
mismatch: live_calls=0, error=ReplayVerificationError

No external tool service or model was called by the reproduction. The existing replay-plugin suite also passes on this checkout: 18 passed.

Proposed acceptance tests: selected tool body is never called; repeated recorded calls retain their order; missing/malformed/mismatched recordings never execute selected tools; agent/turn isolation; SSE and non-streaming fixtures; unselected/default behavior remains unchanged; end-to-end comparison detects state differences.

I searched the repository's open and closed issue/PR titles and targeted body searches on 2026-10-17 for ReplayPlugin, conformance, replay recorded, and replay side-effect. I did not find a matching proposal. Related work: #7290 / #7297 adds live conformance mode, while #7128 / #7129 addresses missing replay recordings. This proposal concerns the tool-execution policy inside existing replay mode.

Would this fit the intended scope of conformance testing, or would you prefer an adapter that reuses the environment-simulation infrastructure?

Standalone reproduction against the checkout above

Run with the checkout installed (pip install -e .):

"""Reproduce real tool execution during conformance replay without external I/O."""

import asyncio
from pathlib import Path
from tempfile import TemporaryDirectory

from google.adk.agents.invocation_context import InvocationContext
from google.adk.agents.llm_agent import LlmAgent
from google.adk.cli.plugins.recordings_schema import Recording, Recordings, ToolRecording
from google.adk.cli.plugins.replay_plugin import ReplayPlugin, ReplayVerificationError
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.adk.tools.base_tool import BaseTool
from google.adk.tools.tool_context import ToolContext
from google.adk.utils.yaml_utils import dump_pydantic_to_yaml
from google.genai import types


class CountingTool(BaseTool):
    def __init__(self, fail=False):
        super().__init__(name="send_notice", description="In-memory test double")
        self.calls = 0
        self.fail = fail

    async def run_async(self, *, args, tool_context):
        self.calls += 1
        if self.fail:
            raise RuntimeError("External service unavailable (simulated)")
        return {"receipt": "live"}


async def run_case(case_dir, label, *, fail=False, mismatch=False):
    service = InMemorySessionService()
    session = await service.create_session(
        app_name="repro", user_id="test", state={
            "_adk_replay_config": {
                "dir": str(case_dir), "user_message_index": 0,
                "streaming_mode": "none",
            }
        },
    )
    invocation = InvocationContext(
        invocation_id=label, session_service=service, session=session,
        agent=LlmAgent(name="agent_a"),
    )
    plugin = ReplayPlugin()
    tool = CountingTool(fail=fail)
    await plugin.before_run_callback(invocation_context=invocation)
    try:
        result = await plugin.before_tool_callback(
            tool=tool, tool_args={"message": "different" if mismatch else "hello"},
            tool_context=ToolContext(invocation),
        )
        assert result == {"receipt": "recorded"}
        assert tool.calls == 1
        print(f"{label}: live_calls={tool.calls}, returned={result}")
    except (RuntimeError, ReplayVerificationError) as exc:
        if mismatch:
            assert isinstance(exc, ReplayVerificationError) and tool.calls == 0
        else:
            assert fail and isinstance(exc, RuntimeError) and tool.calls == 1
        print(f"{label}: live_calls={tool.calls}, error={type(exc).__name__}")
    else:
        assert not fail and not mismatch
    finally:
        await plugin.after_run_callback(invocation_context=invocation)


async def main():
    with TemporaryDirectory() as temp_dir:
        case_dir = Path(temp_dir)
        dump_pydantic_to_yaml(
            Recordings(recordings=[Recording(
                user_message_index=0, agent_name="agent_a",
                tool_recording=ToolRecording(
                    tool_call=types.FunctionCall(
                        id="call-1", name="send_notice", args={"message": "hello"}),
                    tool_response=types.FunctionResponse(
                        id="call-1", name="send_notice", response={"receipt": "recorded"}),
                ),
            )]),
            case_dir / "generated-recordings.yaml", sort_keys=False,
        )
        await run_case(case_dir, "matched")
        await run_case(case_dir, "unavailable", fail=True)
        await run_case(case_dir, "mismatch", mismatch=True)


if __name__ == "__main__":
    asyncio.run(main())

Activity

  1. SHAI-shivansh-sharma commented on Oct 17, 2026

    @SHAI-shivansh-sharma
    ContributorAuthor

    Hi maintainers @ross-p @joefernandez @sanketpatil06 @llalitkumarrr @GWeale @wuliang229 , I opened a small PR for this: #7593. It lets conformance replay use recorded responses for selected tools while still verifying the recorded calls. Thanks for taking a look.

  2. added
    eval
    on Oct 22, 2026
  3. sanketpatil06 commented on Oct 22, 2026

    @sanketpatil06

    Hi @SHAI-shivansh-sharma , Thanks for bringing this and taking time to raise a PR. Your request is currently being reviewed, and we will let you know if anything further is needed. We appreciate your contribution.

  4. added
    needs review
    on Oct 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

evalneeds review

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions