Repository navigation
Description
Describe the Bug:
When a parent agent and a helper agent share an environment, the parent can write a file, call the helper through AgentTool, and find the file gone when the helper returns. The helper never touched it. No error and no warning: the next ReadFile just says "File not found". With the default LocalEnvironment() it's a new temp dir, the old one deleted. The calls are sequential; nothing runs in parallel.
AgentTool.run_async calls runner.close() in a finally, the nested runner closes the wrapped agent's toolsets, EnvironmentToolset.close() calls close_if_initialized(environment), and that environment is the parent's too. The parent's next tool call goes through ensure_initialized, initialize() sees no workspace, and makes a new one.
I know both halves are documented: the AgentTool guide says ADK closes the wrapped agent's toolsets after each call, and the environment guide says toolsets sharing an environment close it without checking each other. But the guide's two ways out (separate environments, or closing both at once) don't fit here: the helper exists to work on the parent's files, and AgentTool calls close mid-run, not me. The one-shared-toolset case isn't in either guide.
Steps to Reproduce:
pip install google-adk==2.15.1- Save the script below as
repro.py(it uses a scriptedBaseLlm; no model or sandbox service is called) python repro.py(parent and child share oneEnvironmentToolset)python repro.py two(each has its ownEnvironmentToolsetover the same environment)
Expected Behavior:
The parent's workspace stays until the parent is done, so the second ReadFile returns hello like the first. If sharing an environment this way isn't supported, an explicit error before the helper's cleanup deletes the parent's workspace.
Observed Behavior:
Both ways, on 2.15.0, 2.15.1 and main at 0019b86:
parent ReadFile -> {'status': 'ok', 'content': ' 1\thello'}
parent ReadFile -> {'status': 'error', 'error': 'File not found: notes.txt'}
(plus ADK's "Skipping missing token usage metadata" lines, because the scripted model reports no tokens)
Related to #4045: b5b6e58 added holder counting to Runner and closed #4045. About two hours later, d0f227a removed it again, tests included (same subject and description, a different internal revision; the four files end up exactly as before b5b6e58), so neither main nor 2.15.x has it. I put b5b6e58's runners.py change back on top of main and reran:
- one shared toolset: fixed
- two Runners over one agent ([BUG] When executing Runners(of which agent contains stateful toolset) in parallel, toolset is being released when only one of them has finished #4045's own first case): fixed
- two toolsets over one environment: still a fresh empty workspace, since the count is per toolset and both toolsets close the same environment
Was that removal intentional, and is a replacement planned? Either way #4045 is closed with no fix on main, and PR #7045 was closed on 2026-11-23 as superseded by b5b6e58. Separately, the two-toolsets case needs ownership tracked at the environment level, so neither toolset can close it while the other still needs it. Making initialize() after a close fail loudly would only expose the problem, not prevent the deletion.
With in-memory fakes for their SDK classes, I also got the replaced workspace through E2BEnvironment and through OpenSandboxEnvironment when it owns the sandbox (an OpenSandboxEnvironment attached by sandbox_id reconnects instead). Those were lifecycle checks, not runs against either service.
Environment Details:
- ADK Library Version: 2.15.1 (also 2.15.0, and main at 0019b86)
- Desktop OS: Linux
- Python Version: 3.12.3
Model Information:
- Are you using LiteLLM: No
- Which model is being used: none (a scripted
BaseLlm)
How often has this issue occurred?: Every run of the reproduction, both ways, on each version above
Minimal Reproduction Code:
import asyncio
import sys
from google.adk.agents import LlmAgent
from google.adk.environment import LocalEnvironment
from google.adk.models.base_llm import BaseLlm
from google.adk.models.llm_response import LlmResponse
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools.agent_tool import AgentTool
from google.adk.tools.environment import EnvironmentToolset
from google.genai import types
def call(name, **args):
part = types.Part(function_call=types.FunctionCall(name=name, args=args))
return LlmResponse(content=types.Content(role="model", parts=[part]))
def say(text):
return LlmResponse(content=types.Content(role="model", parts=[types.Part(text=text)]))
class Scripted(BaseLlm):
script: list
async def generate_content_async(self, llm_request, stream=False):
for part in llm_request.contents[-1].parts or []:
if part.function_response and part.function_response.name == "ReadFile":
print("parent ReadFile ->", part.function_response.response)
yield self.script.pop(0)
async def main(two_toolsets: bool):
env = LocalEnvironment()
parent_tools = EnvironmentToolset(environment=env)
child_tools = EnvironmentToolset(environment=env) if two_toolsets else parent_tools
child = LlmAgent(
name="child",
model=Scripted(model="child", script=[say("nothing to do")]),
tools=[child_tools],
)
parent = LlmAgent(
name="parent",
model=Scripted(
model="parent",
script=[
call("WriteFile", path="notes.txt", content="hello"),
call("ReadFile", path="notes.txt"),
call("child", request="hi"),
call("ReadFile", path="notes.txt"),
say("done"),
],
),
tools=[parent_tools, AgentTool(agent=child)],
)
sessions = InMemorySessionService()
runner = Runner(app_name="app", agent=parent, session_service=sessions)
session = await sessions.create_session(app_name="app", user_id="u")
message = types.Content(role="user", parts=[types.Part(text="go")])
async for _ in runner.run_async(user_id="u", session_id=session.id, new_message=message):
pass
await runner.close()
asyncio.run(main(two_toolsets=sys.argv[1:] == ["two"]))I found this while writing an ADK environment for plimsoll, a code sandbox I maintain. The reproduction doesn't depend on it. Happy to help with tests and a fix once the intended ownership is clear.
I used an AI coding assistant to help run the reproduction and draft this; I checked the results and can answer questions about them.
Activity
carrollco commentedon Nov 26, 2026
Another way into this close, with no
AgentTool:adk eval. It's the same race as #4155 (parallel eval Runners closing a sharedMCPToolset, closed in April with the agent-factory workaround), but with an environment the result isn't an error. The eval just scores the wrong workspace.adk evalruns each eval case and repetition in its ownasync with Runner(...)over the one loaded agent (evaluation_generator.pyaround line 949), four at a time by default (parallelismdefaults to 4 inbase_eval_service.py), andRunner.close()cleans up every toolset of that agent (runners.pyaround line 2298). With ADK's ownLocalEnvironmentand a scripted model (no key, nothing called), two cases each write a word tonote.txt, wait,catit, and answer with what they read. Thebetacases wait 0.2 s and thealphacases 2 s, sobeta's Runners close first:Both
keep_alpharuns answered "The note could not be read: ... cat: note.txt: No such file or directory":beta's Runner closed the environment, its temp dir was deleted, andalpha's next call got a new empty one. That's the close from this issue. With both waits at 1 s, thealpharuns instead answer "The note says beta." (the cases share the files). With--parallelism 1everything passes. Output trimmed; the three files are below.I know the sharing is documented:
LocalEnvironmentisSHARED, and the environment guide says a module-level environment is shared by every user of the process, which it calls fine for a single-user command-line agent.adk evalis one, and it runs four sessions at once by default. ASESSION-scoped environment would separate the files, but as I read itclose()takes no context, so the first case to finish would still close every session's workspace. The Eval tab ofadk weblooks like the same path (LocalEvalServiceover the cached agent the chat uses); I read that one, I didn't run it.Would you like the isolation part as its own issue? Happy to send a PR for either.
note_agent/agent.py
evalset.json
{ "eval_set_id": "note", "name": "Two cases that keep a word in note.txt and read it back", "eval_cases": [ { "eval_id": "keep_alpha", "conversation": [ { "invocation_id": "alpha-1", "user_content": {"role": "user", "parts": [{"text": "Keep the word alpha in note.txt, then read it back."}]}, "final_response": {"role": "model", "parts": [{"text": "The note says alpha."}]}, "intermediate_data": { "tool_uses": [ {"name": "WriteFile", "args": {"path": "note.txt", "content": "alpha\n"}}, {"name": "Execute", "args": {"command": "cat note.txt"}} ], "intermediate_responses": [] } } ], "session_input": {"app_name": "note_agent", "user_id": "user", "state": {}} }, { "eval_id": "keep_beta", "conversation": [ { "invocation_id": "beta-1", "user_content": {"role": "user", "parts": [{"text": "Keep the word beta in note.txt, then read it back."}]}, "final_response": {"role": "model", "parts": [{"text": "The note says beta."}]}, "intermediate_data": { "tool_uses": [ {"name": "WriteFile", "args": {"path": "note.txt", "content": "beta\n"}}, {"name": "Execute", "args": {"command": "cat note.txt"}} ], "intermediate_responses": [] } } ], "session_input": {"app_name": "note_agent", "user_id": "user", "state": {}} } ] }test_config.json
{ "criteria": { "tool_trajectory_avg_score": 1.0, "response_match_score": 0.99 } }note_agent/__init__.pyisfrom . import agent.08raviyadav commentedon Nov 26, 2026
Thanks for the thorough report and the repro — both failure modes reproduce exactly as described, and the silent part is the worst of it: the parent's next
ReadFilejust says "File not found" with no error at the point where the workspace was actually deleted.I'd like to take a fix for this, with the ownership question settled first. The shape I'd propose:
Runner-level holder counting from b5b6e58 alongside it, so the [BUG] When executing Runners(of which agent contains stateful toolset) in parallel, toolset is being released when only one of them has finished #4045 case (two Runners over one agent with a stateful toolset) stays fixed too.AgentToolkeeps closing its nested runner after each call — the change is that closing a runner/toolset stops closing an environment another holder still needs. Nothing else aboutAgentTool's lifecycle changes.Regression tests would be the repro from this issue as two cases (one shared toolset; two toolsets over one environment), plus #4045's two-Runners case.
Two questions before I start: was the removal of the holder counting in d0f227a intentional, and is environment-level ownership the direction you'd want, or is there a replacement already planned? Happy to implement it with tests once you confirm — and if you'd rather implement it yourself, I'm glad to review and test instead.