From 91f454447a1eacd04729fbfa7446b764a3c1f9c4 Mon Sep 17 00:00:00 2001 From: Sumedh Aerram Date: Sun, 29 Nov 2026 23:15:31 -0800 Subject: [PATCH 1/2] fix(tools): bound the output drain after ExecuteBashTool timeouts Preserve captured output and bound cleanup when escaped descendants retain subprocess pipes. Fixes #8452 --- src/google/adk/tools/bash_tool.py | 35 ++++++++++++- tests/unittests/tools/test_bash_tool.py | 69 +++++++++++++++---------- 2 files changed, 76 insertions(+), 28 deletions(-) diff --git a/src/google/adk/tools/bash_tool.py b/src/google/adk/tools/bash_tool.py index 1bfefcfd93a..ed0a6287e07 100644 --- a/src/google/adk/tools/bash_tool.py +++ b/src/google/adk/tools/bash_tool.py @@ -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 @@ -259,9 +262,10 @@ async def run_async( preexec_fn=lambda: _set_resource_limits(self._policy), ) + communication = asyncio.create_task(process.communicate()) try: stdout, stderr = await asyncio.wait_for( - process.communicate(), timeout=self._policy.timeout_seconds + asyncio.shield(communication), timeout=self._policy.timeout_seconds ) except asyncio.TimeoutError: try: @@ -269,7 +273,30 @@ async def run_async( _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: + stdout, stderr = 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") + transport.close() + stdout, stderr = await asyncio.wait_for( + communication, _OUTPUT_DRAIN_GRACE_SECONDS + ) return { "error": ( f"Command timed out after {self._policy.timeout_seconds}" @@ -288,6 +315,10 @@ async def run_async( "returncode": process.returncode, } finally: + if not communication.done(): + getattr(process, "_transport").close() + communication.cancel() + await asyncio.gather(communication, return_exceptions=True) try: if process.pid: _kill_process_group(process) diff --git a/tests/unittests/tools/test_bash_tool.py b/tests/unittests/tools/test_bash_tool.py index 4ab8e534711..762bca27561 100644 --- a/tests/unittests/tools/test_bash_tool.py +++ b/tests/unittests/tools/test_bash_tool.py @@ -14,8 +14,11 @@ import asyncio import logging +import os +import shlex import signal import sys +import time from unittest import mock import pytest @@ -292,32 +295,6 @@ 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() - mock_process.pid = 12345 - mock_process.communicate.return_value = (b"", b"") - 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() - @pytest.mark.asyncio async def test_cwd_is_workspace(self, workspace, tool_context_confirmed): tool = bash_tool.ExecuteBashTool(workspace=workspace) @@ -397,3 +374,43 @@ 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, tool_context_confirmed, escaped_child +): + """Timeouts return promptly even when an escaped child holds both pipes.""" + pid_file = workspace / "child.pid" + script = ( + "import subprocess, time, pathlib; child = subprocess.Popen(['sleep'," + f" '30'], start_new_session={escaped_child});" + f" pathlib.Path({str(pid_file)!r}).write_text(str(child.pid));" + " print('before timeout', flush=True); import sys; print('stderr before" + " timeout', file=sys.stderr, flush=True); time.sleep(30)" + ) + tool = bash_tool.ExecuteBashTool( + workspace=workspace, policy=bash_tool.BashToolPolicy(timeout_seconds=1) + ) + started = time.monotonic() + try: + result = await asyncio.wait_for( + tool.run_async( + args={"command": shlex.join([sys.executable, "-c", script])}, + tool_context=tool_context_confirmed, + ), + timeout=6, + ) + assert time.monotonic() - started < 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 pid_file.exists(): + try: + os.kill(int(pid_file.read_text()), signal.SIGKILL) + except ProcessLookupError: + pass From 2dbc18ca092d95aa70f7729bc7288d6243d1b6b0 Mon Sep 17 00:00:00 2001 From: Sumedh Aerram Date: Sun, 29 Nov 2026 23:33:24 -0800 Subject: [PATCH 2/2] fix(tools): retain bash output when timeout cleanup stalls Collect output as it is read so a stalled drain can still return partial output and the timeout result. Restore process-group kill coverage and synchronize the real subprocess tests with child readiness. --- src/google/adk/tools/bash_tool.py | 45 ++++++--- tests/unittests/tools/test_bash_tool.py | 125 ++++++++++++++++++++---- 2 files changed, 138 insertions(+), 32 deletions(-) diff --git a/src/google/adk/tools/bash_tool.py b/src/google/adk/tools/bash_tool.py index ed0a6287e07..803d6043b55 100644 --- a/src/google/adk/tools/bash_tool.py +++ b/src/google/adk/tools/bash_tool.py @@ -174,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.""" @@ -250,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), @@ -262,9 +270,14 @@ async def run_async( preexec_fn=lambda: _set_resource_limits(self._policy), ) - communication = asyncio.create_task(process.communicate()) + # 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( + await asyncio.wait_for( asyncio.shield(communication), timeout=self._policy.timeout_seconds ) except asyncio.TimeoutError: @@ -284,7 +297,7 @@ async def run_async( ): await asyncio.sleep(0.01) try: - stdout, stderr = await asyncio.wait_for( + await asyncio.wait_for( asyncio.shield(communication), _OUTPUT_DRAIN_GRACE_SECONDS ) except asyncio.TimeoutError: @@ -292,11 +305,13 @@ async def run_async( # 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") - transport.close() - stdout, stderr = await asyncio.wait_for( - communication, _OUTPUT_DRAIN_GRACE_SECONDS - ) + 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}" @@ -312,11 +327,17 @@ async def run_async( if stderr else "" ), - "returncode": process.returncode, + "returncode": ( + process.returncode + if process.returncode is not None + else -signal.SIGKILL + ), } finally: if not communication.done(): - getattr(process, "_transport").close() + transport = getattr(process, "_transport", None) + if transport is not None: + transport.close() communication.cancel() await asyncio.gather(communication, return_exceptions=True) try: diff --git a/tests/unittests/tools/test_bash_tool.py b/tests/unittests/tools/test_bash_tool.py index 762bca27561..5775bfe968f 100644 --- a/tests/unittests/tools/test_bash_tool.py +++ b/tests/unittests/tools/test_bash_tool.py @@ -15,10 +15,11 @@ import asyncio import logging import os +from pathlib import Path import shlex import signal import sys -import time +from typing import Any from unittest import mock import pytest @@ -295,6 +296,50 @@ async def test_nonzero_returncode(self, workspace, tool_context_confirmed): ) assert result["returncode"] == 42 + @pytest.mark.asyncio + 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.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("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 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): tool = bash_tool.ExecuteBashTool(workspace=workspace) @@ -335,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): @@ -380,37 +426,76 @@ async def test_zero_file_size_limit_blocks_file_writes( @pytest.mark.parametrize("escaped_child", [False, True]) @pytest.mark.asyncio async def test_real_timeout_preserves_output( - workspace, tool_context_confirmed, escaped_child -): + 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 subprocess, time, pathlib; child = subprocess.Popen(['sleep'," - f" '30'], start_new_session={escaped_child});" + "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); import sys; print('stderr before" - " timeout', file=sys.stderr, flush=True); time.sleep(30)" + " 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) ) - started = time.monotonic() try: - result = await asyncio.wait_for( - tool.run_async( - args={"command": shlex.join([sys.executable, "-c", script])}, - tool_context=tool_context_confirmed, - ), - timeout=6, - ) - assert time.monotonic() - started < 6 + 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 pid_file.exists(): + if escaped_child: try: - os.kill(int(pid_file.read_text()), signal.SIGKILL) - except ProcessLookupError: + 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