Skip to content

AgentTool closes an environment its caller is still using; the caller's next tool call silently gets a fresh empty workspace #8368

Todo

Description

@carrollco

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:

  1. pip install google-adk==2.15.1
  2. Save the script below as repro.py (it uses a scripted BaseLlm; no model or sandbox service is called)
  3. python repro.py (parent and child share one EnvironmentToolset)
  4. python repro.py two (each has its own EnvironmentToolset over 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:

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

  1. added
    tools
    on Nov 26, 2026
  2. carrollco commented on Nov 26, 2026

    @carrollco
    Author

    Another way into this close, with no AgentTool: adk eval. It's the same race as #4155 (parallel eval Runners closing a shared MCPToolset, 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 eval runs each eval case and repetition in its own async with Runner(...) over the one loaded agent (evaluation_generator.py around line 949), four at a time by default (parallelism defaults to 4 in base_eval_service.py), and Runner.close() cleans up every toolset of that agent (runners.py around line 2298). With ADK's own LocalEnvironment and a scripted model (no key, nothing called), two cases each write a word to note.txt, wait, cat it, and answer with what they read. The beta cases wait 0.2 s and the alpha cases 2 s, so beta's Runners close first:

    $ pip install "google-adk[eval]==2.15.1"
    $ adk eval note_agent evalset.json --config_file_path test_config.json --num_runs 2
      keep_alpha  FAILED  FF  0/2 (0%)
      keep_beta   PASSED  PP  2/2 (100%)
    

    Both keep_alpha runs 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, and alpha's next call got a new empty one. That's the close from this issue. With both waits at 1 s, the alpha runs instead answer "The note says beta." (the cases share the files). With --parallelism 1 everything passes. Output trimmed; the three files are below.

    I know the sharing is documented: LocalEnvironment is SHARED, 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 eval is one, and it runs four sessions at once by default. A SESSION-scoped environment would separate the files, but as I read it close() takes no context, so the first case to finish would still close every session's workspace. The Eval tab of adk web looks like the same path (LocalEvalService over 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
    """adk eval runs eval cases concurrently over one agent; its LocalEnvironment is shared and closed under them.
    
    A scripted model (no API key): write the case's word to note.txt, wait (2 s for alpha, 0.2 s for beta), `cat note.txt`, answer with the output.
    """
    import asyncio
    import re
    
    from google.adk import Agent
    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.tools.environment import EnvironmentToolset
    from google.genai import types
    
    
    class ScriptedModel(BaseLlm):
      model: str = "scripted"
    
      async def generate_content_async(self, llm_request, stream=False):
        word, turns, last = "nothing", 0, {}
        for c in llm_request.contents:
          for p in c.parts or []:
            if c.role == "user" and p.text:
              m = re.search(r"the word (\w+)", p.text)
              word, turns = (m.group(1) if m else word), 0
            if p.function_response is not None:
              last = dict(p.function_response.response or {})
          if c.role == "model":
            turns += 1
        if turns == 0:
          part = types.Part(function_call=types.FunctionCall(
              name="WriteFile", args={"path": "note.txt", "content": word + "\n"}))
        elif turns == 1:
          await asyncio.sleep(2.0 if word == "alpha" else 0.2)
          part = types.Part(function_call=types.FunctionCall(name="Execute", args={"command": "cat note.txt"}))
        else:
          seen = (last.get("stdout") or "").strip()
          part = types.Part(text=f"The note says {seen}." if seen else f"The note could not be read: {last}")
        yield LlmResponse(content=types.Content(role="model", parts=[part]))
    
    
    root_agent = Agent(
        name="note_agent",
        model=ScriptedModel(),
        instruction="Keep the word in note.txt and read it back.",
        tools=[EnvironmentToolset(environment=LocalEnvironment())],
    )
    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__.py is from . import agent.

  3. 08raviyadav commented on Nov 26, 2026

    @08raviyadav

    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 ReadFile just 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:

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

tools

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions