From dc50e52e5c3b303245018e9d208a6704c00b0c61 Mon Sep 17 00:00:00 2001 From: Andrea Bruno Date: Mon, 14 Sep 2026 14:52:31 +0200 Subject: [PATCH] fix: bound sandbox resource use on host and in container Commands run through `execute()` are agent-controlled, so their output and lifetime have to be bounded. Several paths were unbounded: - `run_docker` buffered all stdout/stderr in host memory via `capture_output=True`; `max_output_bytes` was only applied afterwards, so `dd if=/dev/zero | cat` could exhaust host RAM. Output is now streamed in chunks and the process killed at the cap. - The per-command timeout only killed the host-side `docker exec` client; the command kept running in the container, burning its CPU and PID budget. Each exec now records its process group (docker exec is a session leader, so descendants keep the pgid) and timeouts and cap kills reap the whole group. - Reaped children became zombies because PID 1 was `sleep infinity`; the container now runs with `--init`. - `docker info` and `docker run` had no timeout, so a wedged daemon hung the constructor forever, and a timed-out `docker run` leaked its container. Both are bounded and failed starts are cleaned up. - `atexit.register(self.close)` held a strong reference, so an abandoned sandbox was never collected and its container and temp dir survived until process exit. The hook now holds a weakref and is unregistered on close. - `max_output_bytes` is validated like the other limits. Co-Authored-By: Claude Opus 5 (1M context) --- README.md | 3 +- src/deepagents_docker/_docker.py | 155 ++++++++++++++++++++++++++++++- src/deepagents_docker/backend.py | 111 +++++++++++++++++++--- tests/test_docker_helpers.py | 74 +++++++++++++++ tests/test_docker_sandbox.py | 121 ++++++++++++++++++++++++ uv.lock | 2 +- 6 files changed, 448 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index b1d5a24..cdc9423 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,8 @@ DockerSandbox( allow_outbound_traffic=True, # False → no network; True (default) → allow outbound traffic shared_dir="/path/to/project", # host folder shared with the container; see note below timeout=120, # per-command timeout (seconds) - max_output_bytes=100_000, # combined stdout/stderr cap per command + max_output_bytes=100_000, # per-stream stdout/stderr cap; output is streamed + # and the command is killed once it is reached memory="256m", # default memory limit cpus=0.5, # default CPU limit pids_limit=128, diff --git a/src/deepagents_docker/_docker.py b/src/deepagents_docker/_docker.py index 9308898..0e8de99 100644 --- a/src/deepagents_docker/_docker.py +++ b/src/deepagents_docker/_docker.py @@ -1,10 +1,17 @@ +import contextlib import json import subprocess +import threading +import time from collections.abc import Sequence from dataclasses import dataclass +from typing import IO from .errors import DockerError +_READ_CHUNK_BYTES = 65_536 +_POLL_INTERVAL = 0.05 + @dataclass(frozen=True) class DockerRunResult: @@ -13,6 +20,7 @@ class DockerRunResult: returncode: int stdout: str stderr: str + truncated: bool = False def run_docker( @@ -20,11 +28,25 @@ def run_docker( *, timeout: float | None = None, input_text: str | None = None, + max_output_bytes: int | None = None, ) -> DockerRunResult: - """Run `docker` with the given arguments.""" + """Run `docker` with the given arguments. + + When ``max_output_bytes`` is set, stdout and stderr are streamed and each is capped at + that many bytes, killing the subprocess once the cap is hit. This keeps a command that + writes unbounded output (for example ``dd if=/dev/zero``) from exhausting host memory. + """ + if max_output_bytes is not None: + return _run_docker_capped( + args, + timeout=timeout, + input_text=input_text, + max_output_bytes=max_output_bytes, + ) + try: completed = subprocess.run( # noqa: S603 - ["docker", *args], + ["docker", *args], # noqa: S607 check=False, capture_output=True, text=True, @@ -45,9 +67,132 @@ def run_docker( ) -def docker_available() -> bool: - """Return True when the Docker daemon responds to `docker info`.""" - result = run_docker(["info", "--format", "{{.ServerVersion}}"]) +def _drain(stream: IO[bytes], chunks: list[bytes], limit: int, hit_cap: threading.Event) -> None: + """Read `stream` into `chunks`, stopping once `limit` bytes have been collected.""" + total = 0 + try: + while True: + chunk = stream.read(_READ_CHUNK_BYTES) + if not chunk: + return + chunks.append(chunk) + total += len(chunk) + if total >= limit: + hit_cap.set() + return + except (OSError, ValueError): + return + finally: + with contextlib.suppress(Exception): + stream.close() + + +def _write_stdin(stream: IO[bytes], payload: bytes) -> None: + try: + stream.write(payload) + except (OSError, ValueError): + pass + finally: + with contextlib.suppress(Exception): + stream.close() + + +def _run_docker_capped( + args: Sequence[str], + *, + timeout: float | None, + input_text: str | None, + max_output_bytes: int, +) -> DockerRunResult: + try: + process = subprocess.Popen( # noqa: S603 + ["docker", *args], # noqa: S607 + stdin=subprocess.PIPE if input_text is not None else subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + except FileNotFoundError as exc: + msg = "docker executable not found on PATH" + raise DockerError(msg) from exc + + stdout_chunks: list[bytes] = [] + stderr_chunks: list[bytes] = [] + hit_cap = threading.Event() + workers = [ + threading.Thread( + target=_drain, + args=(process.stdout, stdout_chunks, max_output_bytes, hit_cap), + daemon=True, + ), + threading.Thread( + target=_drain, + args=(process.stderr, stderr_chunks, max_output_bytes, hit_cap), + daemon=True, + ), + ] + if input_text is not None and process.stdin is not None: + workers.append( + threading.Thread( + target=_write_stdin, + args=(process.stdin, input_text.encode()), + daemon=True, + ), + ) + for worker in workers: + worker.start() + + deadline = None if timeout is None else time.monotonic() + timeout + timed_out = False + try: + while any(worker.is_alive() for worker in workers): + if hit_cap.is_set(): + break + if deadline is not None and time.monotonic() >= deadline: + timed_out = True + break + time.sleep(_POLL_INTERVAL) + finally: + if hit_cap.is_set() or timed_out: + _terminate(process) + try: + returncode = process.wait(timeout=10) + except subprocess.TimeoutExpired: + _terminate(process) + returncode = process.wait() + for worker in workers: + worker.join(timeout=1) + + if timed_out: + msg = f"docker command timed out after {timeout} seconds" + raise DockerError(msg) + + stdout = _decode(stdout_chunks, max_output_bytes) + stderr = _decode(stderr_chunks, max_output_bytes) + return DockerRunResult( + returncode=returncode, + stdout=stdout, + stderr=stderr, + truncated=hit_cap.is_set(), + ) + + +def _terminate(process: subprocess.Popen[bytes]) -> None: + if process.poll() is not None: + return + with contextlib.suppress(Exception): + process.kill() + + +def _decode(chunks: list[bytes], limit: int) -> str: + return b"".join(chunks)[:limit].decode("utf-8", errors="replace") + + +def docker_available(*, timeout: float | None = None) -> bool: + """Return True when the Docker daemon responds to `docker info` within `timeout`.""" + try: + result = run_docker(["info", "--format", "{{.ServerVersion}}"], timeout=timeout) + except DockerError: + return False return result.returncode == 0 diff --git a/src/deepagents_docker/backend.py b/src/deepagents_docker/backend.py index 7fb2bef..76c6a10 100644 --- a/src/deepagents_docker/backend.py +++ b/src/deepagents_docker/backend.py @@ -3,6 +3,9 @@ import atexit import tempfile import uuid +import weakref +from collections.abc import Callable +from functools import partial from pathlib import Path from deepagents.backends.filesystem import FilesystemBackend @@ -18,6 +21,36 @@ DEFAULT_EXECUTE_TIMEOUT = 120 DEFAULT_IMAGE = "python:3.12-bookworm" CONTAINER_WORKDIR = "/shared" +DOCKER_INFO_TIMEOUT = 30 +DOCKER_START_TIMEOUT = 600 +CLEANUP_TIMEOUT = 15 + +# `docker exec` makes each exec its own session/process-group leader, so the wrapper records +# its PID (== the process group id) and a later `kill -9 -` reaps the whole tree, +# including children reparented to PID 1. $1 is the pid file, $2 the user command. +_EXEC_WRAPPER = """ +echo $$ > "$1" 2>/dev/null +sh -c "$2" +status=$? +rm -f "$1" 2>/dev/null +exit $status +""" + +# Kill the process group recorded by `_EXEC_WRAPPER`. $1 is the pid file. +_KILL_WRAPPER = """ +pgid="" +[ -f "$1" ] && read pgid < "$1" +rm -f "$1" 2>/dev/null +[ -n "$pgid" ] && kill -9 -"$pgid" 2>/dev/null +exit 0 +""" + + +def _atexit_close(ref: weakref.ReferenceType[DockerSandbox]) -> None: + """Close a sandbox at interpreter exit without keeping it alive until then.""" + sandbox = ref() + if sandbox is not None: + sandbox.close() class DockerSandbox(FilesystemBackend, SandboxBackendProtocol): @@ -45,7 +78,9 @@ def __init__( shared_dir: Host directory shared with the container. A temporary directory is created when omitted. timeout: Default command timeout in seconds. - max_output_bytes: Maximum combined stdout/stderr captured per command. + max_output_bytes: Maximum stdout/stderr captured per command. Output is streamed + and the command is killed once a stream reaches this cap, so a command writing + unbounded output cannot exhaust host memory. memory: Docker memory limit (for example ``"256m"``). cpus: Docker CPU limit. pids_limit: Maximum number of PIDs inside the container. @@ -61,6 +96,9 @@ def __init__( if pids_limit <= 0: msg = f"pids_limit must be positive, got {pids_limit}" raise ValueError(msg) + if max_output_bytes <= 0: + msg = f"max_output_bytes must be positive, got {max_output_bytes}" + raise ValueError(msg) self._owns_shared_dir = shared_dir is None self._shared_dir = Path( @@ -85,9 +123,11 @@ def __init__( self._container_id: str = f"{uuid.uuid4().hex[:12]}" self._container_name = f"deepagents-docker-{self._container_id}" self._closed = False + self._atexit_hook: Callable[[], None] | None = None self._start_container() - atexit.register(self.close) + self._atexit_hook = partial(_atexit_close, weakref.ref(self)) + atexit.register(self._atexit_hook) @property def shared_dir(self) -> Path: @@ -100,7 +140,7 @@ def id(self) -> str: return self._container_id def _start_container(self) -> None: - if not docker_available(): + if not docker_available(timeout=DOCKER_INFO_TIMEOUT): msg = ( "Docker is not available. Install Docker, ensure the daemon is running, " f"and pull the default image with `docker pull {DEFAULT_IMAGE}`" @@ -110,6 +150,9 @@ def _start_container(self) -> None: run_args = [ "run", "-d", + # Docker's init process reaps orphaned children, so killed commands do not + # pile up as zombies against `--pids-limit`. + "--init", "--name", self._container_name, "--network", @@ -129,11 +172,35 @@ def _start_container(self) -> None: "sleep", "infinity", ] - result = run_docker(run_args) + try: + result = run_docker(run_args, timeout=DOCKER_START_TIMEOUT) + except DockerError: + # A timed-out `docker run` may still have created the container. + self._force_remove_container() + raise if result.returncode != 0: + self._force_remove_container() msg = format_docker_error(result) raise DockerError(f"failed to start sandbox container: {msg}") + def _force_remove_container(self) -> None: + """Best-effort `docker rm -f`, used on failed startup and on close.""" + try: + run_docker(["rm", "-f", self._container_name], timeout=CLEANUP_TIMEOUT) + except DockerError: + pass + + def _kill_exec_group(self, pid_file: str) -> None: + """Kill the in-container process group left behind by a timed-out/killed exec.""" + try: + run_docker( + ["exec", self._container_name, "sh", "-c", _KILL_WRAPPER, "sh", pid_file], + timeout=CLEANUP_TIMEOUT, + max_output_bytes=4096, + ) + except DockerError: + pass + def execute( self, command: str, @@ -160,19 +227,31 @@ def execute( msg = f"timeout must be positive, got {effective_timeout}" raise ValueError(msg) + pid_file = f"/tmp/.deepagents-exec-{uuid.uuid4().hex}" # noqa: S108 docker_args = [ "exec", self._container_name, "sh", "-c", + _EXEC_WRAPPER, + "sh", + pid_file, command, ] try: - completed = run_docker(docker_args, timeout=effective_timeout) + completed = run_docker( + docker_args, + timeout=effective_timeout, + max_output_bytes=self._max_output_bytes, + ) except DockerError as exc: detail = str(exc) if "timed out" in detail: + # Killing the `docker exec` client leaves the command running in the + # container; reap its process group so it cannot burn the container's + # CPU/PID budget forever. + self._kill_exec_group(pid_file) if timeout is not None: msg = ( f"Error: Command timed out after {effective_timeout} seconds " @@ -199,6 +278,9 @@ def execute( truncated=False, ) + if completed.truncated: + self._kill_exec_group(pid_file) + output_parts: list[str] = [] if completed.stdout: output_parts.append(completed.stdout) @@ -207,11 +289,14 @@ def execute( output_parts.extend(f"[stderr] {line}" for line in stderr_lines) output = "\n".join(output_parts) if output_parts else "" - truncated = False + truncated = completed.truncated if len(output) > self._max_output_bytes: output = output[: self._max_output_bytes] - output += f"\n\n... Output truncated at {self._max_output_bytes} bytes." truncated = True + if truncated: + output += f"\n\n... Output truncated at {self._max_output_bytes} bytes." + if completed.truncated: + output += " The command was terminated after exceeding the output limit." if completed.returncode != 0: output = f"{output.rstrip()}\n\nExit code: {completed.returncode}" @@ -228,13 +313,17 @@ def close(self) -> None: return self._closed = True - stop = run_docker(["stop", "-t", "2", self._container_name], timeout=30) - if stop.returncode != 0 and "No such container" not in stop.stderr: - # Best-effort shutdown; container may already be gone. + if self._atexit_hook is not None: + atexit.unregister(self._atexit_hook) + + # Best-effort shutdown; the container may already be gone. + try: + run_docker(["stop", "-t", "2", self._container_name], timeout=30) + except DockerError: pass if self._auto_remove: - run_docker(["rm", "-f", self._container_name], timeout=30) + self._force_remove_container() if self._owns_shared_dir: import shutil diff --git a/tests/test_docker_helpers.py b/tests/test_docker_helpers.py index fbeb433..fd26109 100644 --- a/tests/test_docker_helpers.py +++ b/tests/test_docker_helpers.py @@ -77,3 +77,77 @@ def test_run_docker_raises_when_docker_missing(subprocess_run: MagicMock) -> Non with pytest.raises(DockerError, match="not found on PATH"): run_docker(["info"]) + + +def _fake_docker_script(body: str) -> list[str]: + """Build args that make the patched `docker` binary run a python snippet.""" + return ["-c", body] + + +@patch("deepagents_docker._docker.subprocess.Popen") +def test_run_docker_capped_raises_when_docker_missing(popen: MagicMock) -> None: + popen.side_effect = FileNotFoundError + + with pytest.raises(DockerError, match="not found on PATH"): + run_docker(["info"], max_output_bytes=1024) + + +def test_run_docker_capped_returns_output(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "deepagents_docker._docker.subprocess.Popen", + _popen_shim(["sh", "-c", "printf hello; printf oops >&2"]), + ) + + result = run_docker(["exec", "cid", "true"], max_output_bytes=1024) + + assert result.returncode == 0 + assert result.stdout == "hello" + assert result.stderr == "oops" + assert result.truncated is False + + +def test_run_docker_capped_kills_process_on_unbounded_output( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # `yes` writes forever; the cap must stop us long before the host buffers it all. + monkeypatch.setattr( + "deepagents_docker._docker.subprocess.Popen", + _popen_shim(["sh", "-c", "yes aaaaaaaaaaaaaaaa"]), + ) + + result = run_docker(["exec", "cid", "true"], timeout=30, max_output_bytes=4096) + + assert result.truncated is True + assert len(result.stdout.encode()) == 4096 + assert result.returncode != 0 + + +def test_run_docker_capped_forwards_stdin(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "deepagents_docker._docker.subprocess.Popen", + _popen_shim(["sh", "-c", "cat"]), + ) + + result = run_docker(["exec", "-i", "cid", "cat"], input_text="ping", max_output_bytes=1024) + + assert result.stdout == "ping" + + +def test_run_docker_capped_times_out(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "deepagents_docker._docker.subprocess.Popen", + _popen_shim(["sh", "-c", "sleep 30"]), + ) + + with pytest.raises(DockerError, match="timed out after 1 seconds"): + run_docker(["exec", "cid", "sleep"], timeout=1, max_output_bytes=1024) + + +def _popen_shim(replacement: list[str]): + """Replace the `docker ...` argv with a real local command, keeping Popen behavior.""" + real_popen = subprocess.Popen + + def _factory(_args: list[str], **kwargs: object) -> subprocess.Popen: + return real_popen(replacement, **kwargs) + + return _factory diff --git a/tests/test_docker_sandbox.py b/tests/test_docker_sandbox.py index 8ff04c9..2e24b26 100644 --- a/tests/test_docker_sandbox.py +++ b/tests/test_docker_sandbox.py @@ -1,3 +1,5 @@ +import gc +import weakref from pathlib import Path from unittest.mock import MagicMock, patch @@ -136,6 +138,7 @@ def test_raises_when_container_start_fails( ({"timeout": 0}, "timeout must be positive"), ({"cpus": 0}, "cpus must be positive"), ({"pids_limit": -1}, "pids_limit must be positive"), + ({"max_output_bytes": 0}, "max_output_bytes must be positive"), ], ) @patch("deepagents_docker.backend.docker_available", return_value=True) @@ -476,3 +479,121 @@ def test_context_manager_closes_sandbox( assert len(sandbox.id) == 12 assert len(run_docker.call_args_list) == 3 + + +def _exec_calls(run_docker: MagicMock) -> list[list[str]]: + return [call[0][0] for call in run_docker.call_args_list if call[0][0][0] == "exec"] + + +@patch("deepagents_docker.backend.run_docker") +@patch("deepagents_docker.backend.docker_available", return_value=True) +def test_container_runs_with_init_process( + _available: MagicMock, + run_docker: MagicMock, + tmp_path: Path, +) -> None: + run_docker.return_value = _docker_run_ok() + + sandbox = DockerSandbox(shared_dir=tmp_path) + try: + assert "--init" in run_docker.call_args_list[0][0][0] + finally: + sandbox.close() + + +@patch("deepagents_docker.backend.run_docker") +@patch("deepagents_docker.backend.docker_available", return_value=True) +def test_failed_start_removes_container( + _available: MagicMock, + run_docker: MagicMock, + tmp_path: Path, +) -> None: + run_docker.return_value = DockerRunResult(returncode=1, stdout="", stderr="boom") + + with pytest.raises(DockerError): + DockerSandbox(shared_dir=tmp_path) + + assert any(call[0][0][:2] == ["rm", "-f"] for call in run_docker.call_args_list) + + +@patch("deepagents_docker.backend.run_docker") +@patch("deepagents_docker.backend.docker_available", return_value=True) +def test_execute_caps_output_at_the_source( + _available: MagicMock, + run_docker: MagicMock, + tmp_path: Path, +) -> None: + run_docker.side_effect = _make_run_docker_side_effect() + + sandbox = DockerSandbox(shared_dir=tmp_path, max_output_bytes=4096) + try: + sandbox.execute("echo hi") + exec_kwargs = run_docker.call_args_list[1][1] + assert exec_kwargs["max_output_bytes"] == 4096 + finally: + sandbox.close() + + +@patch("deepagents_docker.backend.run_docker") +@patch("deepagents_docker.backend.docker_available", return_value=True) +def test_execute_reaps_process_group_after_timeout( + _available: MagicMock, + run_docker: MagicMock, + tmp_path: Path, +) -> None: + run_docker.side_effect = _make_run_docker_side_effect( + error=DockerError("docker command timed out after 1 seconds"), + ) + + sandbox = DockerSandbox(shared_dir=tmp_path) + try: + result = sandbox.execute("sleep 100", timeout=1) + assert result.exit_code == 124 + + command_exec, cleanup_exec = _exec_calls(run_docker) + pid_file = command_exec[-2] + assert pid_file.startswith("/tmp/.deepagents-exec-") + assert "kill -9" in cleanup_exec[4] + assert cleanup_exec[-1] == pid_file + finally: + sandbox.close() + + +@patch("deepagents_docker.backend.run_docker") +@patch("deepagents_docker.backend.docker_available", return_value=True) +def test_execute_reaps_process_group_when_output_capped( + _available: MagicMock, + run_docker: MagicMock, + tmp_path: Path, +) -> None: + run_docker.side_effect = _make_run_docker_side_effect( + exec=DockerRunResult(returncode=-9, stdout="x" * 60, stderr="", truncated=True), + ) + + sandbox = DockerSandbox(shared_dir=tmp_path, max_output_bytes=50) + try: + result = sandbox.execute("yes") + assert result.truncated is True + assert "terminated after exceeding the output limit" in result.output + + command_exec, cleanup_exec = _exec_calls(run_docker) + assert "kill -9" in cleanup_exec[4] + assert cleanup_exec[-1] == command_exec[-2] + finally: + sandbox.close() + + +@patch("deepagents_docker.backend.run_docker") +@patch("deepagents_docker.backend.docker_available", return_value=True) +def test_abandoned_sandbox_is_not_kept_alive_by_atexit( + _available: MagicMock, + run_docker: MagicMock, + tmp_path: Path, +) -> None: + run_docker.return_value = _docker_run_ok() + + ref = weakref.ref(DockerSandbox(shared_dir=tmp_path)) + gc.collect() + + assert ref() is None + assert any(call[0][0][:2] == ["rm", "-f"] for call in run_docker.call_args_list) diff --git a/uv.lock b/uv.lock index cd1d8be..519791e 100644 --- a/uv.lock +++ b/uv.lock @@ -286,7 +286,7 @@ wheels = [ [[package]] name = "deepagents-docker" -version = "0.0.2" +version = "0.1.1" source = { editable = "." } dependencies = [ { name = "deepagents" },