Repository navigation
fix(tools): keep environment simulation state per session - #8041
Fruiterer333 wants to merge 1 commit into
Conversation
mangeshraut712
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]] = {} |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
58fca3e to
76676d5
Compare
|
@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. |
|
@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
76676d5 to
2af329a
Compare
Link to Issue or Description of Change
1. Link to an existing issue (if applicable):
Problem:
EnvironmentSimulationEnginekept one_state_storeper engine. Every session served by the same plugin, including every eval case and everynum_runsrepetition, 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 fromtool_context.session. A session id is only unique within an app and user (InMemorySessionServicenests 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:
close(): during eval, each run'sRunnercloses the shared plugin when the run ends (I counted 4close()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). Withparallelism > 1, this would wipe the state of runs that are still in progress.after_run_callback: that fires after every invocation (user turn), so it would break consistency between turns of one session.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:
New tests (all failed before the fix, except the multi-turn guard which passes both before and after):
test_environment_simulation_engine.py::TestEnvironmentSimulationEngineStateStoretest_new_session_starts_with_empty_state(parametrized: differentsession_id,user_id,app_name)test_state_is_kept_across_turns_of_one_sessiontest_environment_simulation_plugin.py::test_eval_runs_do_not_share_simulated_state: end-to-end throughLocalEvalService.perform_inferencewith 2 eval cases ×num_runs=2, using the realToolSpecMockStrategyand a fake simulation model. Every simulated call must see an empty state store.pyink,isortandmypy(onsrc/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):After:
python repro.py --swapgives the same result: every call sees[].Checklist
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.