diff --git a/src/agents/sandbox/sandboxes/unix_local.py b/src/agents/sandbox/sandboxes/unix_local.py index 5cc77e2aff..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,6 +118,90 @@ def _restore_pty_child_signal_defaults() -> None: signal.signal(signum, signal.SIG_DFL) +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() + + +# 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: + """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 @@ -1075,51 +1161,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 _run_workspace_io(_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 _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 c8e9c654a1..89cedf4665 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,212 @@ 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() + + +@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