From 17e8806a72b4b7dcd3a55c700a741ea57c89eee8 Mon Sep 17 00:00:00 2001 From: rajashidattapy Date: Wed, 26 Aug 2026 09:20:46 +0530 Subject: [PATCH 1/2] fix(sandbox): keep UnixLocal filesystem and tar work off the event loop `UnixLocalSandboxSession` called synchronous `pathlib` and `tarfile` APIs directly from `async def` methods, so the loop was held for the full duration of the I/O. `persist_workspace` and `hydrate_workspace` are the costly ones: both sit on the snapshot path and tar or extract the entire workspace tree, so a workspace holding a `node_modules` or a build directory stalled every other task on the loop for seconds to minutes. Move the blocking bodies into module-level helpers invoked through `asyncio.to_thread`, matching what the rest of this module already does for PTY reads and fd cleanup. Session state is read on the loop and only plain values cross into the worker thread. `_resolved_exec_context` now performs its existence check and resolves the workspace root in a single thread hop and returns that root, so the three exec paths no longer each repeat `Path(cwd).resolve()` for themselves. That removes the remaining loop-blocking syscalls and a redundant path walk per exec. Error types and messages are unchanged; the helpers keep the same guards and raise the same `WorkspaceArchiveReadError` / `WorkspaceArchiveWriteError` / `WorkspaceRootNotFoundError` as before. --- src/agents/sandbox/sandboxes/unix_local.py | 123 ++++++++++++--------- tests/sandbox/test_unix_local.py | 83 +++++++++++++- 2 files changed, 154 insertions(+), 52 deletions(-) diff --git a/src/agents/sandbox/sandboxes/unix_local.py b/src/agents/sandbox/sandboxes/unix_local.py index 5cc77e2aff..c30a5a5421 100644 --- a/src/agents/sandbox/sandboxes/unix_local.py +++ b/src/agents/sandbox/sandboxes/unix_local.py @@ -116,6 +116,65 @@ def _restore_pty_child_signal_defaults() -> None: signal.signal(signum, signal.SIG_DFL) +# The helpers below do the blocking filesystem work for this backend. Each one is called +# through ``asyncio.to_thread`` so the archive, extraction, and path syscalls stay off the +# event loop; keeping them at module level keeps that boundary obvious and keeps session +# state access on the loop side of it. + + +def _resolve_existing_workspace(workspace: Path) -> Path: + """Confirm the workspace root exists and resolve it.""" + if not workspace.exists(): + raise WorkspaceRootNotFoundError(path=workspace) + return workspace.resolve() + + +def _archive_workspace(root: Path, skip: set[Path]) -> io.BytesIO: + """Tar the whole workspace tree into an in-memory archive.""" + if not root.exists(): + raise WorkspaceArchiveReadError(path=root, context={"reason": "workspace_root_not_found"}) + + buf = io.BytesIO() + try: + with tarfile.open(fileobj=buf, mode="w") as tar: + tar.add( + root, + arcname=".", + filter=lambda ti: ( + None + if should_skip_tar_member( + ti.name, + skip_rel_paths=skip, + root_name=None, + ) + else ti + ), + ) + except (tarfile.TarError, OSError) as e: + raise WorkspaceArchiveReadError(path=root, cause=e) from e + + buf.seek(0) + return buf + + +def _extract_workspace_archive(root: Path, data: io.IOBase) -> None: + """Extract an archive over the workspace tree.""" + try: + root.mkdir(parents=True, exist_ok=True) + with tarfile.open(fileobj=data, mode="r:*") as tar: + safe_extract_tarfile( + tar, + root=root, + allow_external_symlink_targets=False, + ) + except UnsafeTarMemberError as e: + raise WorkspaceArchiveWriteError( + path=root, context={"reason": e.reason, "member": e.member}, cause=e + ) from e + except (tarfile.TarError, OSError) as e: + raise WorkspaceArchiveWriteError(path=root, cause=e) from e + + class UnixLocalSandboxSessionState(SandboxSessionState): type: Literal["unix_local"] = "unix_local" workspace_root_owned: bool = False @@ -196,7 +255,7 @@ async def _validate_manifest_application( async def _prepare_backend_workspace(self) -> None: workspace = Path(self.state.manifest.root) try: - workspace.mkdir(parents=True, exist_ok=True) + await asyncio.to_thread(workspace.mkdir, parents=True, exist_ok=True) except OSError as e: raise WorkspaceStartError(path=workspace, cause=e) from e @@ -265,8 +324,7 @@ def _prepare_exec_command( async def _exec_internal( self, *command: str | Path, timeout: float | None = None ) -> ExecResult: - env, cwd = await self._resolved_exec_context() - workspace_root = Path(cwd).resolve() + env, cwd, workspace_root = await self._resolved_exec_context() command_parts = self._workspace_relative_command_parts(command, workspace_root) process_cwd, command_parts = self._shell_workspace_process_context( command_parts=command_parts, @@ -318,8 +376,7 @@ async def pty_exec_start( max_output_tokens: int | None = None, ) -> PtyExecUpdate: _ = timeout - env, cwd = await self._resolved_exec_context() - workspace_root = Path(cwd).resolve() + env, cwd, workspace_root = await self._resolved_exec_context() sanitized_command = self._prepare_exec_command(*command, shell=shell, user=user) command_parts = self._workspace_relative_command_parts(sanitized_command, workspace_root) process_cwd, command_parts = self._shell_workspace_process_context( @@ -465,7 +522,7 @@ async def pty_terminate_all(self) -> None: for entry in entries: await self._terminate_pty_entry(entry) - async def _resolved_exec_context(self) -> tuple[dict[str, str], str]: + async def _resolved_exec_context(self) -> tuple[dict[str, str], str, Path]: if self._host_environment_allowlist is None: env = dict(os.environ) else: @@ -477,11 +534,12 @@ async def _resolved_exec_context(self) -> tuple[dict[str, str], str]: env.update(await self.state.manifest.environment.resolve()) workspace = Path(self.state.manifest.root) - if not workspace.exists(): - raise WorkspaceRootNotFoundError(path=workspace) + # One thread hop covers both filesystem calls: the existence check, and the resolve + # that each of the three exec paths used to repeat for itself. + workspace_root = await asyncio.to_thread(_resolve_existing_workspace, workspace) env["HOME"] = str(workspace) - return env, str(workspace) + return env, str(workspace), workspace_root async def _pump_process_stream( self, @@ -1018,8 +1076,7 @@ async def _write_stream_with_exec( *, user: str | User, ) -> None: - env, cwd = await self._resolved_exec_context() - workspace_root = Path(cwd).resolve() + env, cwd, workspace_root = await self._resolved_exec_context() command_parts = self._prepare_exec_command( "sh", "-c", @@ -1075,51 +1132,15 @@ async def running(self) -> bool: return self._running async def persist_workspace(self) -> io.IOBase: + # Archiving the whole workspace tree is unbounded work, so it runs on a worker + # thread. Session state is read here, on the loop, and only plain values cross over. root = Path(self.state.manifest.root) - if not root.exists(): - raise WorkspaceArchiveReadError( - path=root, context={"reason": "workspace_root_not_found"} - ) - skip = self._persist_workspace_skip_relpaths() - buf = io.BytesIO() - try: - with tarfile.open(fileobj=buf, mode="w") as tar: - tar.add( - root, - arcname=".", - filter=lambda ti: ( - None - if should_skip_tar_member( - ti.name, - skip_rel_paths=skip, - root_name=None, - ) - else ti - ), - ) - except (tarfile.TarError, OSError) as e: - raise WorkspaceArchiveReadError(path=root, cause=e) from e - - buf.seek(0) - return buf + return await asyncio.to_thread(_archive_workspace, root, skip) async def hydrate_workspace(self, data: io.IOBase) -> None: root = Path(self.state.manifest.root) - try: - root.mkdir(parents=True, exist_ok=True) - with tarfile.open(fileobj=data, mode="r:*") as tar: - safe_extract_tarfile( - tar, - root=root, - allow_external_symlink_targets=False, - ) - except UnsafeTarMemberError as e: - raise WorkspaceArchiveWriteError( - path=root, context={"reason": e.reason, "member": e.member}, cause=e - ) from e - except (tarfile.TarError, OSError) as e: - raise WorkspaceArchiveWriteError(path=root, cause=e) from e + await asyncio.to_thread(_extract_workspace_archive, root, data) class UnixLocalSandboxClient(BaseSandboxClient[UnixLocalSandboxClientOptions | None]): diff --git a/tests/sandbox/test_unix_local.py b/tests/sandbox/test_unix_local.py index c8e9c654a1..501f4b15a0 100644 --- a/tests/sandbox/test_unix_local.py +++ b/tests/sandbox/test_unix_local.py @@ -1,7 +1,9 @@ from __future__ import annotations import asyncio +import io import signal +import threading from pathlib import Path from types import SimpleNamespace from typing import cast @@ -9,7 +11,7 @@ import pytest from agents.sandbox import SandboxPathGrant -from agents.sandbox.errors import PtySessionNotFoundError +from agents.sandbox.errors import PtySessionNotFoundError, WorkspaceArchiveReadError from agents.sandbox.manifest import Environment, Manifest from agents.sandbox.sandboxes import unix_local as unix_local_module from agents.sandbox.sandboxes.unix_local import ( @@ -464,3 +466,82 @@ async def test_rm_as_user_checks_permissions_then_uses_local_fs( assert session.exec_commands[0][4:6] == ("sh", "-lc") assert session.exec_commands[0][-2:] == (str(target), "0") assert not any(part.startswith("rm ") for part in session.exec_commands[0]) + + +@pytest.mark.asyncio +async def test_persist_workspace_archives_off_the_event_loop( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Archiving the workspace must not hold the loop for the length of the tar. + + The stub returns only after a coroutine scheduled alongside it has run, so archiving on + the event loop deadlocks here instead of completing. + """ + session = _RecordingUnixLocalSession(tmp_path) + released = threading.Event() + archived: list[tuple[Path, set[Path]]] = [] + + def blocking_archive(root: Path, skip: set[Path]) -> io.BytesIO: + if not released.wait(timeout=5): + raise AssertionError("the event loop was blocked while archiving the workspace") + archived.append((root, skip)) + return io.BytesIO(b"archive") + + monkeypatch.setattr(unix_local_module, "_archive_workspace", blocking_archive) + + async def release() -> None: + released.set() + + archive, _ = await asyncio.gather(session.persist_workspace(), release()) + + assert archived == [(Path(tmp_path), session._persist_workspace_skip_relpaths())] + assert archive.read() == b"archive" + + +@pytest.mark.asyncio +async def test_hydrate_workspace_extracts_off_the_event_loop( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Extraction is unbounded too, so it runs on a worker thread for the same reason.""" + session = _RecordingUnixLocalSession(tmp_path) + released = threading.Event() + extracted: list[Path] = [] + + def blocking_extract(root: Path, data: io.IOBase) -> None: + if not released.wait(timeout=5): + raise AssertionError("the event loop was blocked while extracting the archive") + extracted.append(root) + + monkeypatch.setattr(unix_local_module, "_extract_workspace_archive", blocking_extract) + + async def release() -> None: + released.set() + + await asyncio.gather(session.hydrate_workspace(io.BytesIO(b"")), release()) + + assert extracted == [Path(tmp_path)] + + +@pytest.mark.asyncio +async def test_persist_then_hydrate_round_trips_workspace_contents(tmp_path: Path) -> None: + """Moving the tar work into helpers must not change what the archive carries.""" + source = tmp_path / "source" + (source / "nested").mkdir(parents=True) + (source / "nested" / "file.txt").write_text("payload", encoding="utf-8") + + archive = await _RecordingUnixLocalSession(source).persist_workspace() + + target = tmp_path / "target" + await _RecordingUnixLocalSession(target).hydrate_workspace(archive) + + assert (target / "nested" / "file.txt").read_text(encoding="utf-8") == "payload" + + +@pytest.mark.asyncio +async def test_persist_workspace_reports_a_missing_root(tmp_path: Path) -> None: + session = _RecordingUnixLocalSession(tmp_path / "absent") + + with pytest.raises(WorkspaceArchiveReadError): + await session.persist_workspace() From 5ae25734f0e2e5c5ca6214f786ba4c63a304f88b Mon Sep 17 00:00:00 2001 From: rajashidattapy Date: Wed, 26 Aug 2026 09:30:31 +0530 Subject: [PATCH 2/2] fix(sandbox): narrow to the archive paths and own worker cancellation Review feedback: keep this change to the two operations with a demonstrated defect, and make cancellation ownership explicit. Revert the bounded sites. `_prepare_backend_workspace`, `_resolved_exec_context` and the three `Path(cwd).resolve()` callers go back to their original form. An ASYNC240 report alone does not establish a user-visible defect for them, and reverting keeps this change off the exec confinement path. Own the worker's lifetime. `asyncio.to_thread` cannot interrupt the thread it starts, so a cancelled caller previously returned while the worker was still walking or writing the workspace. Callers act on that return immediately: the snapshot lifecycle closes the archive stream in a `finally`, and resume clears the workspace root, so either would land on a live worker. `_run_workspace_io` now records the cancellation, waits for the worker to settle, and only then propagates it. Repeated cancellation is absorbed the same way, and a worker failure arriving after cancellation is consumed rather than reported. This follows `memory.sqlite_session._await_mutation`. Cancellation coverage is deterministic: three tests hold the worker open, cancel the task, and assert it has neither completed nor let the worker settle before the worker is released. All three fail against the plain `to_thread` version. --- src/agents/sandbox/sandboxes/unix_local.py | 73 ++++++++---- tests/sandbox/test_unix_local.py | 130 +++++++++++++++++++++ 2 files changed, 181 insertions(+), 22 deletions(-) diff --git a/src/agents/sandbox/sandboxes/unix_local.py b/src/agents/sandbox/sandboxes/unix_local.py index c30a5a5421..c4ea0ee4cb 100644 --- a/src/agents/sandbox/sandboxes/unix_local.py +++ b/src/agents/sandbox/sandboxes/unix_local.py @@ -21,12 +21,12 @@ import time import uuid from collections import deque -from collections.abc import Collection, Mapping, Sequence +from collections.abc import Callable, Collection, Mapping, Sequence from contextlib import suppress from dataclasses import dataclass, field from functools import partial from pathlib import Path -from typing import Literal, cast +from typing import Any, Literal, TypeVar, cast from ...logger import log_tool_action_warning from .._mount_security import redact_mount_error_data @@ -73,6 +73,8 @@ _DEFAULT_MANIFEST_ROOT = cast(str, Manifest.model_fields["root"].default) _PTY_READ_CHUNK_BYTES = 16_384 _PTY_CHILD_SIGNAL_DEFAULTS = (signal.SIGINT, signal.SIGQUIT) + +_WorkspaceIOResultT = TypeVar("_WorkspaceIOResultT") _PTY_FD_CLOSE_GRACE_SECONDS = 0.1 _HOST_ENVIRONMENT_ALLOWLIST = frozenset( { @@ -116,17 +118,42 @@ def _restore_pty_child_signal_defaults() -> None: signal.signal(signum, signal.SIG_DFL) -# The helpers below do the blocking filesystem work for this backend. Each one is called -# through ``asyncio.to_thread`` so the archive, extraction, and path syscalls stay off the -# event loop; keeping them at module level keeps that boundary obvious and keeps session -# state access on the loop side of it. +async def _run_workspace_io( + func: Callable[..., _WorkspaceIOResultT], + *args: Any, +) -> _WorkspaceIOResultT: + """Run blocking workspace I/O on a worker thread and own that worker's lifetime. + + ``asyncio.to_thread`` cannot interrupt the thread it starts, so returning as soon as the + caller is cancelled would report the operation as stopped while the worker is still + walking or writing the workspace. Callers act on that immediately: the snapshot + lifecycle closes the archive stream in a ``finally`` as soon as the await returns, and a + resume clears the workspace root. Either would land on a live worker. + + So the cancellation is recorded, the worker is allowed to settle, and only then does the + cancellation propagate. Repeated cancellation is absorbed the same way. This mirrors + ``memory.sqlite_session._await_mutation``, which owns cancellation for session writes. + """ + task = asyncio.ensure_future(asyncio.to_thread(func, *args)) + cancellation: asyncio.CancelledError | None = None + while not task.done(): + try: + await asyncio.wait({task}) + except asyncio.CancelledError as exc: + if cancellation is None: + cancellation = exc + + if cancellation is not None: + # Consume any worker failure so it is not reported as never retrieved. The caller + # asked to stop, so the cancellation is what it hears about. + task.exception() + raise cancellation from None + return task.result() -def _resolve_existing_workspace(workspace: Path) -> Path: - """Confirm the workspace root exists and resolve it.""" - if not workspace.exists(): - raise WorkspaceRootNotFoundError(path=workspace) - return workspace.resolve() +# The two helpers below carry the unbounded workspace I/O. They run on a worker thread via +# ``_run_workspace_io`` so archiving and extraction do not hold the event loop; keeping them +# at module level makes that boundary obvious and keeps session state on the loop side of it. def _archive_workspace(root: Path, skip: set[Path]) -> io.BytesIO: @@ -255,7 +282,7 @@ async def _validate_manifest_application( async def _prepare_backend_workspace(self) -> None: workspace = Path(self.state.manifest.root) try: - await asyncio.to_thread(workspace.mkdir, parents=True, exist_ok=True) + workspace.mkdir(parents=True, exist_ok=True) except OSError as e: raise WorkspaceStartError(path=workspace, cause=e) from e @@ -324,7 +351,8 @@ def _prepare_exec_command( async def _exec_internal( self, *command: str | Path, timeout: float | None = None ) -> ExecResult: - env, cwd, workspace_root = await self._resolved_exec_context() + env, cwd = await self._resolved_exec_context() + workspace_root = Path(cwd).resolve() command_parts = self._workspace_relative_command_parts(command, workspace_root) process_cwd, command_parts = self._shell_workspace_process_context( command_parts=command_parts, @@ -376,7 +404,8 @@ async def pty_exec_start( max_output_tokens: int | None = None, ) -> PtyExecUpdate: _ = timeout - env, cwd, workspace_root = await self._resolved_exec_context() + env, cwd = await self._resolved_exec_context() + workspace_root = Path(cwd).resolve() sanitized_command = self._prepare_exec_command(*command, shell=shell, user=user) command_parts = self._workspace_relative_command_parts(sanitized_command, workspace_root) process_cwd, command_parts = self._shell_workspace_process_context( @@ -522,7 +551,7 @@ async def pty_terminate_all(self) -> None: for entry in entries: await self._terminate_pty_entry(entry) - async def _resolved_exec_context(self) -> tuple[dict[str, str], str, Path]: + async def _resolved_exec_context(self) -> tuple[dict[str, str], str]: if self._host_environment_allowlist is None: env = dict(os.environ) else: @@ -534,12 +563,11 @@ async def _resolved_exec_context(self) -> tuple[dict[str, str], str, Path]: env.update(await self.state.manifest.environment.resolve()) workspace = Path(self.state.manifest.root) - # One thread hop covers both filesystem calls: the existence check, and the resolve - # that each of the three exec paths used to repeat for itself. - workspace_root = await asyncio.to_thread(_resolve_existing_workspace, workspace) + if not workspace.exists(): + raise WorkspaceRootNotFoundError(path=workspace) env["HOME"] = str(workspace) - return env, str(workspace), workspace_root + return env, str(workspace) async def _pump_process_stream( self, @@ -1076,7 +1104,8 @@ async def _write_stream_with_exec( *, user: str | User, ) -> None: - env, cwd, workspace_root = await self._resolved_exec_context() + env, cwd = await self._resolved_exec_context() + workspace_root = Path(cwd).resolve() command_parts = self._prepare_exec_command( "sh", "-c", @@ -1136,11 +1165,11 @@ async def persist_workspace(self) -> io.IOBase: # thread. Session state is read here, on the loop, and only plain values cross over. root = Path(self.state.manifest.root) skip = self._persist_workspace_skip_relpaths() - return await asyncio.to_thread(_archive_workspace, root, skip) + return await _run_workspace_io(_archive_workspace, root, skip) async def hydrate_workspace(self, data: io.IOBase) -> None: root = Path(self.state.manifest.root) - await asyncio.to_thread(_extract_workspace_archive, root, data) + await _run_workspace_io(_extract_workspace_archive, root, data) class UnixLocalSandboxClient(BaseSandboxClient[UnixLocalSandboxClientOptions | None]): diff --git a/tests/sandbox/test_unix_local.py b/tests/sandbox/test_unix_local.py index 501f4b15a0..89cedf4665 100644 --- a/tests/sandbox/test_unix_local.py +++ b/tests/sandbox/test_unix_local.py @@ -545,3 +545,133 @@ async def test_persist_workspace_reports_a_missing_root(tmp_path: Path) -> None: with pytest.raises(WorkspaceArchiveReadError): await session.persist_workspace() + + +@pytest.mark.asyncio +async def test_persist_workspace_cancellation_waits_for_the_worker( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Cancellation must not be reported while the worker still holds the workspace. + + ``asyncio.to_thread`` cannot interrupt the thread, and the snapshot lifecycle closes + the archive stream as soon as the await returns, so returning early would leave a live + worker reading a closed stream. + """ + session = _RecordingUnixLocalSession(tmp_path) + started = threading.Event() + release = threading.Event() + settled = threading.Event() + + def blocking_archive(root: Path, skip: set[Path]) -> io.BytesIO: + started.set() + release.wait(timeout=5) + settled.set() + return io.BytesIO(b"archive") + + monkeypatch.setattr(unix_local_module, "_archive_workspace", blocking_archive) + + task = asyncio.create_task(session.persist_workspace()) + assert await asyncio.to_thread(started.wait, 5) + + task.cancel() + await asyncio.sleep(0.1) + assert not task.done() + assert not settled.is_set() + + release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert settled.is_set() + + +@pytest.mark.asyncio +async def test_hydrate_workspace_cancellation_waits_for_the_worker( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Same ownership for extraction, which mutates the workspace as it runs.""" + session = _RecordingUnixLocalSession(tmp_path) + started = threading.Event() + release = threading.Event() + settled = threading.Event() + + def blocking_extract(root: Path, data: io.IOBase) -> None: + started.set() + release.wait(timeout=5) + settled.set() + + monkeypatch.setattr(unix_local_module, "_extract_workspace_archive", blocking_extract) + + task = asyncio.create_task(session.hydrate_workspace(io.BytesIO(b""))) + assert await asyncio.to_thread(started.wait, 5) + + task.cancel() + await asyncio.sleep(0.1) + assert not task.done() + assert not settled.is_set() + + release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert settled.is_set() + + +@pytest.mark.asyncio +async def test_repeated_cancellation_still_waits_for_the_worker( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A caller that cancels more than once does not get to skip the wait.""" + session = _RecordingUnixLocalSession(tmp_path) + started = threading.Event() + release = threading.Event() + settled = threading.Event() + + def blocking_archive(root: Path, skip: set[Path]) -> io.BytesIO: + started.set() + release.wait(timeout=5) + settled.set() + return io.BytesIO(b"archive") + + monkeypatch.setattr(unix_local_module, "_archive_workspace", blocking_archive) + + task = asyncio.create_task(session.persist_workspace()) + assert await asyncio.to_thread(started.wait, 5) + + for _ in range(3): + task.cancel() + await asyncio.sleep(0.02) + assert not task.done() + assert not settled.is_set() + + release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert settled.is_set() + + +@pytest.mark.asyncio +async def test_cancellation_wins_over_a_failing_worker( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A worker that fails after the caller cancelled still reports as cancelled.""" + session = _RecordingUnixLocalSession(tmp_path) + started = threading.Event() + release = threading.Event() + + def failing_archive(root: Path, skip: set[Path]) -> io.BytesIO: + started.set() + release.wait(timeout=5) + raise OSError("workspace went away") + + monkeypatch.setattr(unix_local_module, "_archive_workspace", failing_archive) + + task = asyncio.create_task(session.persist_workspace()) + assert await asyncio.to_thread(started.wait, 5) + + task.cancel() + release.set() + with pytest.raises(asyncio.CancelledError): + await task