Skip to content

fix(tools): keep environment simulation state per session - #8041

Open
Fruiterer333 wants to merge 1 commit into
google:mainfrom
Fruiterer333:fix/env-sim-session-state
Open

Fruiterer333 wants to merge 1 commit into
google:mainfrom
Fruiterer333:fix/env-sim-session-state

Conversation

@Fruiterer333

@Fruiterer333 Fruiterer333 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Link to Issue or Description of Change

1. Link to an existing issue (if applicable):

Problem:
EnvironmentSimulationEngine kept one _state_store per engine. Every session served by the same plugin, including every eval case and every num_runs repetition, read and wrote the same simulated state. A run therefore saw tickets, orders, etc. "created" by earlier runs, so eval runs were not independent and an eval case's result depended on execution order.

Solution:
The engine now keeps one state store per session and passes the current session's store to the mock strategy. Turns of the same session still share their store, so multi-turn consistency is unchanged. The MockStrategy.mock() interface is unchanged: it still receives a plain dict and updates it in place.

Design

  • Key: (app_name, user_id, session_id), read from tool_context.session. A session id is only unique within an app and user (InMemorySessionService nests sessions by app and user, and the database schema uses the three columns as a composite primary key), so the session id alone could merge two different sessions.

  • Release: stores live as long as the engine. There is no session-end hook to release them on. I considered the alternatives:

    • Clearing in close(): during eval, each run's Runner closes the shared plugin when the run ends (I counted 4 close() calls on the same plugin instance for 4 runs of the repro from Environment simulation state is shared across sessions and eval runs, so an eval case's result depends on execution order #8040). With parallelism > 1, this would wipe the state of runs that are still in progress.
    • Clearing in after_run_callback: that fires after every invocation (user turn), so it would break consistency between turns of one session.
    • A cap on the number of stored sessions (LRU): bounds memory, but silently resets a long-running session once it is evicted, and needs a size that no default fits well.

    Environment simulation is a testing tool, and in eval one store per run holds only that run's simulated responses, so keeping them for the engine's lifetime is the simplest behavior that is correct. If you would prefer a bound or an explicit release method, I am happy to add it.

  • Why not per invocation: an invocation is one user turn. Isolating per invocation would make turn 2 forget the entities created in turn 1, which is exactly the consistency the state store exists for.

  • Why not session state (tool_context.state): its lifetime would follow the session automatically, but simulated data would be mixed into the agent's own session state, where the agent can read it, and be persisted by the session service. Keeping it inside the engine leaves the agent's observable state untouched.

Out of scope: the tool connection analysis (_is_analyzed / _tool_connection_map) is still cached once per engine. It is not session state, so I left it out of this change.

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change.
  • All unit tests pass locally.

New tests (all failed before the fix, except the multi-turn guard which passes both before and after):

  • test_environment_simulation_engine.py::TestEnvironmentSimulationEngineStateStore
    • test_new_session_starts_with_empty_state (parametrized: different session_id, user_id, app_name)
    • test_state_is_kept_across_turns_of_one_session
  • test_environment_simulation_plugin.py::test_eval_runs_do_not_share_simulated_state: end-to-end through LocalEvalService.perform_inference with 2 eval cases × num_runs=2, using the real ToolSpecMockStrategy and a fake simulation model. Every simulated call must see an empty state store.
$ pytest tests/unittests/tools/environment_simulation/ -k "StateStore or eval_runs_do_not_share"
# before the fix
4 failed, 1 passed, 67 deselected
# after the fix
5 passed, 67 deselected

$ pytest tests/unittests/tools/environment_simulation/ tests/unittests/evaluation/ tests/unittests/plugins/
3291 passed, 2 skipped

pyink, isort and mypy (on src/google/adk/tools/environment_simulation/) pass.

Manual End-to-End (E2E) Tests:

Using the repro script from #8040 (fake models, no API key):

Before (the run order differs from the output in #8040; it comes from asyncio.as_completed):

$ python repro.py
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']

After:

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

python repro.py --swap gives the same result: every call sees [].

Checklist

  • I have read the [CONTRIBUTING.md](https://github.com/google/adk-python/blob/main/CONTRIBUTING.md) document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules. (N/A: no dependent changes)

Additional context

I used Claude Code to help investigate the code and draft the change and tests. I reproduced the issue and verified the fix myself.

@mangeshraut712 mangeshraut712 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Per-session stores are the right fix, and the tests (new session / other user / other app, plus the eval isolation test) cover the bug well. Two follow-ups on the new lookup and on store lifetime.

def _state_store_for(self, tool_context: Any) -> dict[str, Any]:
"""Returns the simulated state store of the tool call's session."""
session = tool_context.session
key = (session.app_name, session.user_id, session.id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tool_context.session is now required. The previous process-wide _state_store did not touch the session at all, so a context with session is None (or a missing app_name / user_id / id) used to simulate and now raises AttributeError in the fallback mock path. If a session-less context is still a valid simulate() caller, I'd fall back to a dedicated key (or refuse with a clear error) rather than crashing here. A unit test with session=None would lock that down.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review! A session-less context shouldn't reach simulate() in practice: ToolContext.session is typed Session (not Optional) and comes from InvocationContext.session, which is a required field. Both callers (the plugin's before_tool_callback and the factory callback) run inside an invocation, so they always have one.

That said, if the maintainers would like simulate() to fail with a clear error instead of an AttributeError for a malformed context, I'm happy to add that with a session=None test.

# and their repeated runs, do not see each other's simulated resources.
# Turns of one session share their store. Stores are kept for the
# engine's lifetime: there is no session-end signal to release them on.
self._state_stores: dict[tuple[str, str, str], dict[str, Any]] = {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment is honest: stores are never released. A long-lived engine used for many eval cases or user sessions will grow _state_stores without bound (every unique (app, user, session) keeps its ticket map). A clear_session(...) / evict-on-session-end hook, or at least an optional max size, would keep this from becoming a quiet leak in a shared process. Not blocking for the isolation fix itself, but it is now part of the engine's contract.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, this is the trade-off I called out in the PR description. I kept this PR to the isolation fix, since there's no session-end hook to release on, and clearing in close() would wipe in-progress runs during eval (each run closes the shared plugin).

If the maintainers want a bound, I see two options: an explicit clear_session_state(app_name, user_id, session_id) on the engine, or an optional cap on the number of stored sessions. I'm happy to add whichever they prefer, here or in a follow-up.

@Fruiterer333

Copy link
Copy Markdown
Contributor Author

@xuanyang15 Rebased onto latest main to resolve the merge conflict; the environment simulation tests pass. I've also replied to the two review points above. Happy to make any changes when you get a chance to look.

@Fruiterer333

Copy link
Copy Markdown
Contributor Author

@xuanyang15 Just a quick follow-up: this still rebases cleanly onto current main, and the environment simulation tests pass locally. #8307 (the seeded fault-injection fix for #8288) is stacked on this PR and is ready for review, so landing this would unblock that review as well. Happy to make any changes if anything comes up.

EnvironmentSimulationEngine kept a single state store per engine, so
every session served by one plugin, including every eval case and
num_runs repetition, shared the same simulated state. Key the store by
(app_name, user_id, session_id) so each session starts empty while
turns of one session still share their state.

Closes google#8040
@Fruiterer333
Fruiterer333 force-pushed the fix/env-sim-session-state branch from 76676d5 to 2af329a Compare December 2, 2026 01:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants