Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 58 additions & 6 deletions src/google/adk/tools/bash_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@

logger = logging.getLogger("google_adk." + __name__)

_PROCESS_EXIT_GRACE_SECONDS = 1.0
_OUTPUT_DRAIN_GRACE_SECONDS = 1.0


class _ResourceModule(Protocol):
RLIMIT_CORE: int
Expand Down Expand Up @@ -171,6 +174,14 @@ def _kill_process_group(process: asyncio.subprocess.Process) -> None:
process.kill()


async def _read_output(
stream: Optional[asyncio.StreamReader], output: bytearray
) -> None:
if stream is not None:
while chunk := await stream.read(65536):
output.extend(chunk)


class ExecuteBashTool(BaseTool):
"""Tool to execute a validated bash command within a workspace directory."""

Expand Down Expand Up @@ -247,8 +258,8 @@ async def run_async(
if os.name != "posix":
return {"error": "ExecuteBashTool is only supported on POSIX systems."}

stdout = None
stderr = None
stdout = bytearray()
stderr = bytearray()
try:
process = await asyncio.create_subprocess_exec(
*shlex.split(command),
Expand All @@ -259,17 +270,48 @@ async def run_async(
preexec_fn=lambda: _set_resource_limits(self._policy),
)

# Keep captured chunks available if the readers must be cancelled.
communication = asyncio.gather(
_read_output(process.stdout, stdout),
_read_output(process.stderr, stderr),
process.wait(),
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(), timeout=self._policy.timeout_seconds
await asyncio.wait_for(
asyncio.shield(communication), timeout=self._policy.timeout_seconds
)
except asyncio.TimeoutError:
try:
if process.pid:
_kill_process_group(process)
except ProcessLookupError:
pass
stdout, stderr = await process.communicate()
# Process.wait() can itself wait for inherited pipes to close. Poll
# returncode to bound the wait for the killed process independently.
deadline = (
asyncio.get_running_loop().time() + _PROCESS_EXIT_GRACE_SECONDS
)
while (
process.returncode is None
and asyncio.get_running_loop().time() < deadline
):
await asyncio.sleep(0.01)
try:
await asyncio.wait_for(
asyncio.shield(communication), _OUTPUT_DRAIN_GRACE_SECONDS
)
except asyncio.TimeoutError:
# An escaped descendant may still own the write ends. Closing the
# subprocess transport closes our pipe ends and feeds EOF to the
# existing readers, preserving bytes consumed before the timeout.
# asyncio.Process has no public transport-close API.
transport = getattr(process, "_transport", None)
if transport is not None:
transport.close()
try:
await asyncio.wait_for(communication, _OUTPUT_DRAIN_GRACE_SECONDS)
except asyncio.TimeoutError:
pass
return {
"error": (
f"Command timed out after {self._policy.timeout_seconds}"
Expand All @@ -285,9 +327,19 @@ async def run_async(
if stderr
else "<no stderr captured>"
),
"returncode": process.returncode,
"returncode": (
process.returncode
if process.returncode is not None
else -signal.SIGKILL
),
}
finally:
if not communication.done():
transport = getattr(process, "_transport", None)
if transport is not None:
transport.close()
communication.cancel()
await asyncio.gather(communication, return_exceptions=True)
try:
if process.pid:
_kill_process_group(process)
Expand Down
124 changes: 113 additions & 11 deletions tests/unittests/tools/test_bash_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@

import asyncio
import logging
import os
from pathlib import Path
import shlex
import signal
import sys
from typing import Any
from unittest import mock

import pytest
Expand Down Expand Up @@ -293,30 +297,48 @@ async def test_nonzero_returncode(self, workspace, tool_context_confirmed):
assert result["returncode"] == 42

@pytest.mark.asyncio
async def test_timeout(self, workspace, tool_context_confirmed):
tool = bash_tool.ExecuteBashTool(workspace=workspace)
mock_process = mock.AsyncMock()
async def test_timeout(
self,
workspace: Path,
tool_context_confirmed: tool_context.ToolContext,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A stalled drain still reports the timeout and bytes already read."""
policy = bash_tool.BashToolPolicy(timeout_seconds=0)
tool = bash_tool.ExecuteBashTool(workspace=workspace, policy=policy)
mock_process = mock.create_autospec(
asyncio.subprocess.Process, instance=True
)
mock_process.pid = 12345
mock_process.communicate.return_value = (b"", b"")
mock_process.returncode = None
mock_process.stdout = asyncio.StreamReader()
mock_process.stdout.feed_data(b"partial stdout")
mock_process.stderr = asyncio.StreamReader()
mock_process.stderr.feed_data(b"partial stderr")
monkeypatch.setattr(bash_tool, "_PROCESS_EXIT_GRACE_SECONDS", 0)
monkeypatch.setattr(bash_tool, "_OUTPUT_DRAIN_GRACE_SECONDS", 0.01)

with (
mock.patch.object(
asyncio,
"create_subprocess_exec",
autospec=True,
return_value=mock_process,
),
mock.patch.object(
asyncio, "wait_for", autospec=True, side_effect=asyncio.TimeoutError
),
mock.patch("os.killpg") as mock_killpg,
):
result = await tool.run_async(
args={"command": "python scripts/do_thing.py"},
tool_context=tool_context_confirmed,
)
mock_killpg.assert_called_with(12345, signal.SIGKILL)
assert "error" in result
assert "timed out" in result["error"].lower()

mock_killpg.assert_called_with(12345, signal.SIGKILL)
assert result == {
"error": "Command timed out after 0 seconds.",
"stdout": "partial stdout",
"stderr": "partial stderr",
"returncode": -signal.SIGKILL,
}

@pytest.mark.asyncio
async def test_cwd_is_workspace(self, workspace, tool_context_confirmed):
Expand Down Expand Up @@ -358,7 +380,8 @@ async def test_resource_limits_set(
tool = bash_tool.ExecuteBashTool(workspace=workspace, policy=policy)
mock_process = mock.AsyncMock()
mock_process.pid = None # Ensure finally block doesn't try to kill it
mock_process.communicate.return_value = (b"", b"")
mock_process.stdout = None
mock_process.stderr = None
mock_exec = mock.AsyncMock(return_value=mock_process)

with mock.patch("asyncio.create_subprocess_exec", mock_exec):
Expand Down Expand Up @@ -397,3 +420,82 @@ async def test_zero_file_size_limit_blocks_file_writes(

assert result["returncode"] != 0
assert (workspace / "out.bin").stat().st_size == 0


@pytest.mark.skipif(os.name != "posix", reason="requires POSIX process groups")
@pytest.mark.parametrize("escaped_child", [False, True])
@pytest.mark.asyncio
async def test_real_timeout_preserves_output(
workspace: Path,
tool_context_confirmed: tool_context.ToolContext,
escaped_child: bool,
) -> None:
"""Timeouts return promptly even when an escaped child holds both pipes."""
pid_file = workspace / "child.pid"
ready_file = workspace / "ready"
script = (
"import pathlib, subprocess, sys, time;"
" child = subprocess.Popen(['sleep', '30'],"
f" start_new_session={escaped_child});"
f" pathlib.Path({str(pid_file)!r}).write_text(str(child.pid));"
" print('before timeout', flush=True);"
" print('stderr before timeout', file=sys.stderr, flush=True);"
f" pathlib.Path({str(ready_file)!r}).touch();"
" time.sleep(30)"
)
create_subprocess_exec = asyncio.create_subprocess_exec
loop = asyncio.get_running_loop()
ready_at = 0.0

async def launch_and_wait_until_ready(
*args: Any, **kwargs: Any
) -> asyncio.subprocess.Process:
nonlocal ready_at
process = await create_subprocess_exec(*args, **kwargs)

async def wait_until_ready() -> None:
while not await asyncio.to_thread(ready_file.exists):
await asyncio.sleep(0.01)

try:
await asyncio.wait_for(wait_until_ready(), timeout=10)
except (asyncio.TimeoutError, asyncio.CancelledError):
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
transport = getattr(process, "_transport", None)
if transport is not None:
transport.close()
await process.wait()
raise
ready_at = loop.time()
return process

tool = bash_tool.ExecuteBashTool(
workspace=workspace, policy=bash_tool.BashToolPolicy(timeout_seconds=1)
)
try:
with mock.patch(
"asyncio.create_subprocess_exec", launch_and_wait_until_ready
):
result = await asyncio.wait_for(
tool.run_async(
args={"command": shlex.join([sys.executable, "-c", script])},
tool_context=tool_context_confirmed,
),
timeout=16,
)
assert loop.time() - ready_at < 6
assert result["error"] == "Command timed out after 1 seconds."
assert "before timeout" in result["stdout"]
assert "stderr before timeout" in result["stderr"]
assert result["returncode"] == -signal.SIGKILL
finally:
if escaped_child:
try:
pid = int(await asyncio.to_thread(pid_file.read_text))
if pid > 0 and os.getpgid(pid) == pid:
os.kill(pid, signal.SIGKILL)
except (FileNotFoundError, ValueError, ProcessLookupError):
pass