adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Environment simulation state is shared across sessions and eval runs, so an eval case's result depends on execution order

Open Fruiterer333 opened this issue 3 weeks ago • 1 comments

🔴 Required Information

Describe the Bug: Eval runs that use EnvironmentSimulationPlugin are not independent: the same eval case sees a different simulated environment depending on which runs executed before it.

EnvironmentSimulationEngine._state_store ([L113](https://github.com/google/adk-python/blob/54a6bbbfc59e247c6552555cffcdf2faf4810699/src/google/adk/tools/environment_simulation/environment_simulation_engine.py#L113)) is created once per plugin and never reset. During eval, _build_eval_runner_kwargs copies the plugin list but reuses the plugin instances ([L195-L199](https://github.com/google/adk-python/blob/54a6bbbfc59e247c6552555cffcdf2faf4810699/src/google/adk/evaluation/evaluation_generator.py#L195-L199)). So all sessions, eval cases and num_runs repetitions share one simulated state.

The [docs](https://adk.dev/evaluate/environment_simulation/) say it should "Track a state store of IDs and resources created during the session". Only InjectionConfig.random_seed documents sharing across sessions as intended. No test locks in the shared state store.

Steps to Reproduce:

  1. Install google-adk[eval] from main (54a6bbbfc).
  2. Save the script below as repro.py (fake models, no API key). The fake simulation model prints the state that ToolSpecMockStrategy puts in its prompt.
  3. Run python repro.py and python repro.py --swap (eval set order reversed). Both use num_runs=2, parallelism=1.

Expected Behavior: Each session starts from an empty simulated state, so every call here should print state seen: []. Within one session, state still carries over between turns.

Observed Behavior:

$ python repro.py
call #1  case_a  state seen: []
call #2  case_a  state seen: ['T-1']
call #3  case_b  state seen: ['T-1', 'T-2']
call #4  case_b  state seen: ['T-1', 'T-2', 'T-3']

$ python repro.py --swap
call #1  case_b  state seen: []
call #2  case_b  state seen: ['T-1']
call #3  case_a  state seen: ['T-1', 'T-2']
call #4  case_a  state seen: ['T-1', 'T-2', 'T-3']

Every call sees all tickets created by the calls before it, whichever case they belonged to: case_a sees 0 and 1 leftover tickets in the first output and 2 and 3 in the second. With a real simulation model this can change tool responses, and so the trajectory and the scores. The run order comes from asyncio.as_completed over a set, so it may differ on your machine, and users cannot control it either.

This affects both adk eval and AgentEvaluator, since both run through LocalEvalService with the App's plugins.

The same happens outside eval: with one Runner, a second session's first call already sees the first session's ticket.

Environment Details:

  • ADK Library Version: main at 54a6bbbfc
  • Desktop OS: macOS 26.6.2
  • Python Version: 3.12.7

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used: N/A (fake BaseLlms)

🟡 Optional Information

Minimal Reproduction Code:

# No API key needed: agent model and simulation model are fakes.
# python repro.py          -> eval set [case_a, case_b]
# python repro.py --swap   -> eval set [case_b, case_a]
import asyncio, json, re, sys
from google.adk.agents.llm_agent import LlmAgent
from google.adk.apps.app import App
from google.adk.evaluation.base_eval_service import InferenceConfig, InferenceRequest
from google.adk.evaluation.eval_case import EvalCase, Invocation
from google.adk.evaluation.in_memory_eval_sets_manager import InMemoryEvalSetsManager
from google.adk.evaluation.local_eval_service import LocalEvalService
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.models.registry import LLMRegistry
from google.adk.tools.environment_simulation.environment_simulation_config import EnvironmentSimulationConfig, MockStrategy, ToolSimulationConfig
from google.adk.tools.environment_simulation.environment_simulation_factory import EnvironmentSimulationFactory
from google.genai import types

CALLS = []


def reply(part):
  return LlmResponse(content=types.Content(role="model", parts=[part]))


def text(req):
  return next(p.text for c in reversed(req.contents) for p in c.parts if p.text)


class FakeSimLlm(BaseLlm):

  @classmethod
  def supported_models(cls):
    return ["fake-sim"]

  async def generate_content_async(self, req, stream=False):
    p = text(req)
    if "stateful dependencies" in p:  # ToolConnectionAnalyzer
      body = {"stateful_parameters": [{"parameter_name": "ticket_id",
          "creating_tools": ["create_ticket"], "consuming_tools": []}]}
    else:  # ToolSpecMockStrategy: print the state passed in its prompt
      CALLS.append(p)
      state = re.search(r"current state of all stateful parameters:\s*(.*?)\s*You are now", p, re.S)
      args = re.search(r"Tool Arguments:\s*(\{.*?\})\s*\n\s*\n", p, re.S)
      case = json.loads(args.group(1))["title"]
      seen = sorted(json.loads(state.group(1)).get("ticket_id", {}))
      print(f"call #{len(CALLS)}  {case}  state seen: {seen}")
      body = {"ticket_id": f"T-{len(CALLS)}"}
    yield reply(types.Part(text=json.dumps(body)))


LLMRegistry.register(FakeSimLlm)


class FakeAgentLlm(BaseLlm):  # calls create_ticket once, then answers

  async def generate_content_async(self, req, stream=False):
    if any(p.function_response for p in req.contents[-1].parts):
      yield reply(types.Part(text="done"))
    else:
      fc = types.FunctionCall(name="create_ticket", args={"title": text(req)})
      yield reply(types.Part(function_call=fc))


def create_ticket(title: str) -> dict:
  """Creates a ticket and returns its ticket_id."""


async def main():
  agent = LlmAgent(name="a", model=FakeAgentLlm(model="fake"), tools=[create_ticket])
  plugin = EnvironmentSimulationFactory.create_plugin(EnvironmentSimulationConfig(
      simulation_model="fake-sim",
      tool_simulation_configs=[ToolSimulationConfig(tool_name="create_ticket",
          mock_strategy_type=MockStrategy.MOCK_STRATEGY_TOOL_SPEC)]))
  app = App(name="app", root_agent=agent, plugins=[plugin])
  mgr = InMemoryEvalSetsManager()
  mgr.create_eval_set(app_name="app", eval_set_id="s")
  cases = ["case_b", "case_a"] if "--swap" in sys.argv else ["case_a", "case_b"]
  for cid in cases:  # one turn; the user text is the case id
    msg = types.Content(role="user", parts=[types.Part(text=cid)])
    mgr.add_eval_case(app_name="app", eval_set_id="s", eval_case=EvalCase(
        eval_id=cid, conversation=[Invocation(invocation_id=cid, user_content=msg)]))
  svc = LocalEvalService(root_agent=agent, eval_sets_manager=mgr, app=app)
  req = InferenceRequest(app_name="app", eval_set_id="s",
      inference_config=InferenceConfig(parallelism=1, num_runs=2))
  async for _ in svc.perform_inference(req):
    pass


asyncio.run(main())

How often has this issue occurred?:

  • Always (100%)

Additional Context, possible fixes (which do you prefer?):

  1. Isolate state per session inside the engine. Plugin API unchanged, but we need to agree on when a session's state is released.
  2. Keep the simulated state in session state (tool_context.state). Lifetime follows the session, but simulation data becomes visible in, and persisted with, the user's session state.

I lean towards 1 and am happy to send a PR once the direction is agreed.

Fruiterer333 avatar Nov 08 '26 18:11 Fruiterer333

Hello @Fruiterer333,

Thank you for your request and your contribution. Your PR is currently under review, and we will reach out if we need further information. In the meantime, we appreciate your patience.

llalitkumarrr avatar Nov 12 '26 05:11 llalitkumarrr