Backtestsopenai-agents-pythonrun-20261024-184640#4749

Issue #4749 Merged fix PR #4750 Run 24 Oct 2026 · run-20261024-184640 openai/openai-agents-python

PTY startup cancellation can leak unregistered UnixLocal and Blaxel resources

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Patch B covers all three asks in the issue; Patch A covers only two. The issue explicitly asks UnixLocal to "track whether registration committed and cleanup-settle the entry if cancellation occurs before insertion" around the contended `_pty_lock` acquisition. Patch B wraps the `async with self._pty_lock:` block in a `registered` flag plus a `BaseException` handler that settles `_terminate_pty_entry(entry)` before re-raising. Patch A leaves that block untouched, so a cancellation while waiting on a held registry lock still leaks the spawned process, pump tasks, and wait task. The independent tests confirm this directly: both `test_cancel_while_waiting_for_registry_lock_terminates_process` variants (pipes and tty) still FAIL-ASSERT on Patch A with "unregistered PTY process kept running after cancellation", while all six independent tests pass on Patch B. Both patches correctly fix the Blaxel cancellation gap and widen the TTY fd-close handler to `BaseException`. On craft, B's `settle_cleanup_despite_cancellation` is a clearly named, documented public utility in a dedicated `util/cancellation.py` module with a straightforward `asyncio.wait` loop, whereas A exports an underscore-prefixed `_settle_pty_cleanup` from `pty_types.py` and imports it across packages, using a more convoluted shield-plus-wrapper-task construction. B's `BaseException` handler placed after the `Exception` handler is a sound ordering and matches the Docker/Daytona precedent the issue cites. On tests, A has no test for the missing UnixLocal registration fix (unsurprisingly); B adds one, though its `requires_native_macos_sandbox` marker may limit where it runs, and B also adds a contended-lock Blaxel test and a real-fd TTY cancellation test. Correctness is decisive here: A leaves a reported leak path broken.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

14m 10s

Wall-clock time in the container

Full test suite

No new failures

1,549 passed · 3 skipped · 1,552 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

290vs 265 merged

Changed lines, ours vs merged

Please read this first

  • Have you searched for related issues? Yes. I searched for pty_exec_start cancellation, unregistered PTY cleanup, Blaxel WebSocket cancellation, UnixLocal PTY cancellation, and PTY registration cancellation. I did not find an issue for this pre-registration ownership boundary.
  • Scope: current main at 89c02c828ee8510fe9a84ee6675608193aa13b02.
  • Relationship to #4747: distinct. #4747 covers teardown after an entry has been removed from a registry. This report covers resources that exist but have not been registered yet.

Describe the bug

Two PTY startup paths can leak resources on ordinary caller cancellation before registration.

Blaxel

pty_exec_start creates an aiohttp.ClientSession, opens the WebSocket, starts the reader task and sends the command before inserting the entry into _pty_sessions.

Its cleanup handlers are:

except asyncio.TimeoutError:
    if not registered:
        await self._terminate_pty_entry(entry)
    ...
except Exception:
    if not registered:
        await self._terminate_pty_entry(entry)
    ...

asyncio.CancelledError derives from BaseException, so cancellation during ws_connect, command send, or a contended _pty_lock acquisition bypasses both handlers. The entry is not in the registry, so pty_terminate_all() cannot recover it.

Concrete resources at risk are the WebSocket, aiohttp.ClientSession, and reader task.

UnixLocal

Once create_subprocess_exec succeeds, the process entry, pump task(s), and wait task exist. Registration then awaits:

async with self._pty_lock:
    ...
    self._pty_processes[process_id] = entry

There is no cancellation cleanup around this ownership transfer. If the map lock is contended and the caller is cancelled, the process entry and background tasks remain unregistered and unreachable from pty_terminate_all().

The TTY creation path has a related gap: its fd-close handler catches only Exception around create_subprocess_exec, so cancellation during that await can also bypass the PTY fd cleanup.

Deterministic control-flow reproduction

I modeled the exact ownership boundaries without provider/network dependencies:

blaxel_current_cleaned=False
blaxel_reference_cleaned=True
unix_current_cleaned=False
unix_reference_cleaned=True
V46_PTY_STARTUP_CANCELLATION_REPRO=PASS

For Blaxel, cancellation bypasses the Exception handlers. For UnixLocal, cancellation while waiting for a held map lock exits after local resource creation but before registration.

Other backends checked

I checked all seven PTY implementations rather than generalizing the claim:

  • Docker catches BaseException and attempts cleanup of an unregistered entry.
  • Cloudflare has an explicit CancelledError cleanup path.
  • Daytona catches BaseException and shields startup cleanup.
  • E2B has an explicit CancelledError cleanup path.
  • Modal has an explicit CancelledError cleanup path.

So the direct single-cancellation claim here is intentionally limited to UnixLocal and Blaxel.

Expected behavior

Once a process/provider resource exists, either:

  1. registration commits and the session registry owns cleanup; or
  2. cancellation before registration settles cleanup before propagating.

A narrow fix can reuse the cancellation-settled cleanup primitive discussed in #4747.

For Blaxel, add a cancellation/BaseException path that cleanup-settles the unregistered entry before re-raising.

For UnixLocal, track whether registration committed and cleanup-settle the entry if cancellation occurs before insertion. The TTY fd-close handler should also cover BaseException so cancellation cannot bypass descriptor cleanup.

Debug information

  • Repository: openai/openai-agents-python
  • Main SHA: 89c02c828ee8510fe9a84ee6675608193aa13b02
  • Provider integration execution: not required / not claimed
  • Reproduction type: deterministic asyncio ownership/control-flow

The two patches

Our patch+281 −9
src/agents/extensions/sandbox/blaxel/sandbox.pyindex aee3211f..229e69ee 100644@@ -61,6 +61,7 @@ from ....sandbox.session.sandbox_client import BaseSandboxClient from ....sandbox.session.tar_workspace import shell_tar_exclude_args from ....sandbox.snapshot import SnapshotBase, SnapshotSpec, resolve_snapshot from ....sandbox.types import ExecResult, ExposedPortEndpoint, User+from ....sandbox.util.cancellation import settle_cleanup_despite_cancellation from ....sandbox.util.retry import (     TRANSIENT_HTTP_STATUS_CODES,     exception_chain_contains_type,@@ -839,12 +840,17 @@ class BlaxelSandboxSession(BaseSandboxSession):                 registered = True         except asyncio.TimeoutError as e:             if not registered:-                await self._terminate_pty_entry(entry)+                await settle_cleanup_despite_cancellation(self._terminate_pty_entry(entry))             raise ExecTimeoutError(command=command, timeout_s=exec_timeout, cause=e) from e         except Exception as e:             if not registered:-                await self._terminate_pty_entry(entry)+                await settle_cleanup_despite_cancellation(self._terminate_pty_entry(entry))             raise _blaxel_exec_transport_error(command=command, cause=e) from e+        except BaseException:+            # Cancellation before registration: pty_terminate_all() cannot reach this entry.+            if not registered:+                await settle_cleanup_despite_cancellation(self._terminate_pty_entry(entry))+            raise          if pruned is not None:             await self._terminate_pty_entry(pruned)src/agents/sandbox/sandboxes/unix_local.pyindex ea7f83e9..5b4d3ed3 100644@@ -63,6 +63,7 @@ from ..session.workspace_payloads import coerce_write_payload from ..snapshot import SnapshotBase, SnapshotSpec, resolve_snapshot from ..types import ExecResult, ExposedPortEndpoint, Permissions, User from ..util.blocking_io import run_blocking_workspace_io+from ..util.cancellation import settle_cleanup_despite_cancellation from ..util.tar_utils import (     UnsafeTarMemberError,     safe_extract_tarfile,@@ -354,7 +355,7 @@ class UnixLocalSandboxSession(BaseSandboxSession):                     env=env,                     preexec_fn=_preexec,                 )-            except Exception:+            except BaseException:                 with suppress(OSError):                     os.close(primary_fd)                 with suppress(OSError):@@ -383,12 +384,20 @@ class UnixLocalSandboxSession(BaseSandboxSession):         entry.wait_task = asyncio.create_task(self._watch_process_exit(entry))          pruned_entry: _UnixPtyProcessEntry | None = None-        async with self._pty_lock:-            process_id = allocate_pty_process_id(self._reserved_pty_process_ids)-            self._reserved_pty_process_ids.add(process_id)-            pruned_entry = self._prune_pty_processes_if_needed()-            self._pty_processes[process_id] = entry-            process_count = len(self._pty_processes)+        registered = False+        try:+            async with self._pty_lock:+                process_id = allocate_pty_process_id(self._reserved_pty_process_ids)+                self._reserved_pty_process_ids.add(process_id)+                pruned_entry = self._prune_pty_processes_if_needed()+                self._pty_processes[process_id] = entry+                process_count = len(self._pty_processes)+                registered = True+        except BaseException:+            # Until the entry is in the registry, pty_terminate_all() cannot reach it.+            if not registered:+                await settle_cleanup_despite_cancellation(self._terminate_pty_entry(entry))+            raise          if pruned_entry is not None:             await self._terminate_pty_entry(pruned_entry)src/agents/sandbox/util/cancellation.pynew file mode 100644index 00000000..11019b23@@ -0,0 +1,35 @@+"""Settle cleanup work even when the awaiting task is cancelled.++Resources created before they are handed to an owner (for example a PTY process that has not+been inserted into a session registry yet) are only reachable from the coroutine that created+them. If that coroutine is cancelled while cleaning them up, the cleanup must still run to+completion, or nothing else will ever release them.+"""++from __future__ import annotations++import asyncio+from collections.abc import Awaitable+++async def settle_cleanup_despite_cancellation(cleanup: Awaitable[None]) -> None:+    """Run `cleanup` to completion, then re-raise any cancellation received while waiting."""+    task = asyncio.ensure_future(cleanup)+    cancellation: asyncio.CancelledError | None = None+    while not task.done():+        try:+            # Unlike awaiting the task directly, asyncio.wait() leaves it running when this+            # caller is cancelled and never raises the cleanup's own outcome here.+            await asyncio.wait({task})+        except asyncio.CancelledError as exc:+            if cancellation is None:+                cancellation = exc++    try:+        task.result()+    except BaseException:+        if cancellation is not None:+            raise cancellation from None+        raise+    if cancellation is not None:+        raise cancellation from Nonetests/extensions/sandbox/test_blaxel.pyindex 3fe1d0d9..6daa566d 100644@@ -1906,6 +1906,76 @@ class TestPtyExec:             with pytest.raises(ExecTransportError):                 await session.pty_exec_start("echo", "hello") +    @pytest.mark.asyncio+    async def test_pty_exec_start_cancelled_before_registration_cleans_up(+        self, fake_sandbox: _FakeSandboxInstance+    ) -> None:+        from agents.extensions.sandbox.blaxel import sandbox as mod++        session = _make_session(fake_sandbox)+        ws = _FakeWS()+        http_sessions: list[_FakeHTTPSession] = []++        class _TrackingAiohttp(_FakeAiohttp):+            def ClientSession(self) -> _FakeHTTPSession:+                http_session = super().ClientSession()+                http_sessions.append(http_session)+                return http_session++        with patch.object(mod, "_import_aiohttp", return_value=_TrackingAiohttp(ws=ws)):+            await session._pty_lock.acquire()+            try:+                task = asyncio.create_task(session.pty_exec_start("echo", "hello"))+                for _ in range(20):+                    if ws._sent:+                        break+                    await asyncio.sleep(0)+                assert ws._sent, "command should be sent before waiting on the registry lock"+                task.cancel()+                with pytest.raises(asyncio.CancelledError):+                    await task+            finally:+                session._pty_lock.release()++        assert session._pty_sessions == {}+        assert ws._closed is True+        assert len(http_sessions) == 1+        assert http_sessions[0]._closed is True++    @pytest.mark.asyncio+    async def test_pty_exec_start_cancelled_during_connect_closes_http_session(+        self, fake_sandbox: _FakeSandboxInstance+    ) -> None:+        from agents.extensions.sandbox.blaxel import sandbox as mod++        session = _make_session(fake_sandbox)+        connect_started = asyncio.Event()+        closed: list[bool] = []++        class _HangingAiohttp:+            WSMsgType = _FakeAiohttp.WSMsgType++            def ClientSession(self) -> Any:+                class _HangingSession:+                    async def ws_connect(self, url: str) -> None:+                        connect_started.set()+                        await asyncio.sleep(100)++                    async def close(self) -> None:+                        closed.append(True)++                return _HangingSession()++        with patch.object(mod, "_import_aiohttp", return_value=_HangingAiohttp()):+            task = asyncio.create_task(session.pty_exec_start("echo", "hello", timeout=100))+            await connect_started.wait()+            task.cancel()+            with pytest.raises(asyncio.CancelledError):+                await task++        assert closed == [True]+        assert session._pty_sessions == {}+     @pytest.mark.parametrize(         ("chars", "expected_send_count"),         [tests/sandbox/test_cancellation_util.pynew file mode 100644index 00000000..41982c28@@ -0,0 +1,60 @@+from __future__ import annotations++import asyncio++import pytest++from agents.sandbox.util.cancellation import settle_cleanup_despite_cancellation+++@pytest.mark.asyncio+async def test_cleanup_completes_despite_repeated_cancellation() -> None:+    cleanup_started = asyncio.Event()+    release_cleanup = asyncio.Event()+    finished: list[bool] = []++    async def cleanup() -> None:+        cleanup_started.set()+        await release_cleanup.wait()+        finished.append(True)++    task = asyncio.create_task(settle_cleanup_despite_cancellation(cleanup()))+    await cleanup_started.wait()+    task.cancel()+    await asyncio.sleep(0)+    task.cancel()+    await asyncio.sleep(0)+    assert not task.done()++    release_cleanup.set()+    with pytest.raises(asyncio.CancelledError):+        await task+    assert finished == [True]+++@pytest.mark.asyncio+async def test_cleanup_error_propagates_without_cancellation() -> None:+    async def cleanup() -> None:+        raise RuntimeError("cleanup failed")++    with pytest.raises(RuntimeError, match="cleanup failed"):+        await settle_cleanup_despite_cancellation(cleanup())+++@pytest.mark.asyncio+async def test_cancellation_wins_over_cleanup_error() -> None:+    cleanup_started = asyncio.Event()+    release_cleanup = asyncio.Event()++    async def cleanup() -> None:+        cleanup_started.set()+        await release_cleanup.wait()+        raise RuntimeError("cleanup failed")++    task = asyncio.create_task(settle_cleanup_despite_cancellation(cleanup()))+    await cleanup_started.wait()+    task.cancel()+    await asyncio.sleep(0)+    release_cleanup.set()+    with pytest.raises(asyncio.CancelledError):+        await tasktests/sandbox/test_unix_local.pyindex fb13be3c..3a89784d 100644@@ -429,6 +429,98 @@ class TestUnixLocalPty:         with pytest.raises(PtySessionNotFoundError):             await session.pty_write_stdin(session_id=started.process_id, chars="") +    @pytest.mark.asyncio+    @pytest.mark.requires_native_macos_sandbox+    @pytest.mark.parametrize("tty", [True, False], ids=["tty", "pipes"])+    async def test_pty_exec_start_cancelled_before_registration_cleans_up(+        self,+        tmp_path: Path,+        monkeypatch: pytest.MonkeyPatch,+        tty: bool,+    ) -> None:+        client = UnixLocalSandboxClient()+        manifest = Manifest(root=str(tmp_path / "workspace"))+        spawned: list[asyncio.subprocess.Process] = []+        real_create_subprocess_exec = asyncio.create_subprocess_exec++        async def recording_create_subprocess_exec(+            *args: object, **kwargs: object+        ) -> asyncio.subprocess.Process:+            process = await real_create_subprocess_exec(*args, **kwargs)  # type: ignore[arg-type]+            spawned.append(process)+            return process++        async with await client.create(manifest=manifest, snapshot=None, options=None) as sandbox:+            session = cast(UnixLocalSandboxSession, sandbox._inner)+            monkeypatch.setattr(asyncio, "create_subprocess_exec", recording_create_subprocess_exec)+            await session._pty_lock.acquire()+            try:+                task = asyncio.create_task(+                    session.pty_exec_start(+                        "sh", "-c", "sleep 30", shell=False, tty=tty, yield_time_s=0.05+                    )+                )+                for _ in range(500):+                    if spawned:+                        break+                    await asyncio.sleep(0.01)+                assert spawned, "process should be spawned before waiting on the registry lock"+                await asyncio.sleep(0.05)+                task.cancel()+                with pytest.raises(asyncio.CancelledError):+                    await task+            finally:+                session._pty_lock.release()++            assert session._pty_processes == {}+            await asyncio.wait_for(spawned[0].wait(), timeout=5)+            assert spawned[0].returncode == -signal.SIGKILL++    @pytest.mark.asyncio+    async def test_tty_fds_closed_when_cancelled_during_spawn(+        self,+        tmp_path: Path,+        monkeypatch: pytest.MonkeyPatch,+    ) -> None:+        session = _RecordingUnixLocalSession(tmp_path)+        opened: list[int] = []+        closed: list[int] = []+        spawn_started = asyncio.Event()+        real_openpty = unix_local_module.os.openpty+        real_close = unix_local_module.os.close++        def recording_openpty() -> tuple[int, int]:+            fds = real_openpty()+            opened.extend(fds)+            return fds++        def recording_close(fd: int) -> None:+            closed.append(fd)+            real_close(fd)++        async def hanging_create_subprocess_exec(+            *args: object, **kwargs: object+        ) -> asyncio.subprocess.Process:+            _ = (args, kwargs)+            spawn_started.set()+            await asyncio.sleep(3600)+            raise AssertionError("unreachable")++        monkeypatch.setattr(unix_local_module.os, "openpty", recording_openpty)+        monkeypatch.setattr(unix_local_module.os, "close", recording_close)+        monkeypatch.setattr(asyncio, "create_subprocess_exec", hanging_create_subprocess_exec)++        task = asyncio.create_task(+            session.pty_exec_start("sh", "-c", "true", shell=False, tty=True)+        )+        await asyncio.wait_for(spawn_started.wait(), timeout=5)+        task.cancel()+        with pytest.raises(asyncio.CancelledError):+            await task++        assert len(opened) == 2+        assert sorted(closed) == sorted(opened)+  class TestUnixLocalUserScopedFilesystem:     @pytest.mark.asyncio 
Merged fix · PR #4750+261 −4
src/agents/extensions/sandbox/blaxel/sandbox.pyindex aee3211fb..a54bc4790 100644@@ -51,6 +51,7 @@ from ....sandbox.session.pty_types import (     PTY_PROCESSES_MAX,     PTY_PROCESSES_WARNING,     PtyExecUpdate,+    _settle_pty_cleanup,     allocate_pty_process_id,     clamp_pty_yield_time_ms,     process_id_to_prune_from_meta,@@ -839,11 +840,18 @@ class BlaxelSandboxSession(BaseSandboxSession):                 registered = True         except asyncio.TimeoutError as e:             if not registered:-                await self._terminate_pty_entry(entry)+                await _settle_pty_cleanup(self._terminate_pty_entry(entry))             raise ExecTimeoutError(command=command, timeout_s=exec_timeout, cause=e) from e+        except asyncio.CancelledError as cancellation:+            if not registered:+                await _settle_pty_cleanup(+                    self._terminate_pty_entry(entry),+                    initial_cancellation=cancellation,+                )+            raise         except Exception as e:             if not registered:-                await self._terminate_pty_entry(entry)+                await _settle_pty_cleanup(self._terminate_pty_entry(entry))             raise _blaxel_exec_transport_error(command=command, cause=e) from e          if pruned is not None:src/agents/sandbox/sandboxes/unix_local.pyindex ea7f83e9d..308f6038e 100644@@ -354,7 +354,7 @@ class UnixLocalSandboxSession(BaseSandboxSession):                     env=env,                     preexec_fn=_preexec,                 )-            except Exception:+            except BaseException:                 with suppress(OSError):                     os.close(primary_fd)                 with suppress(OSError):src/agents/sandbox/session/pty_types.pyindex 3f4dab04b..65d816353 100644@@ -1,7 +1,8 @@ from __future__ import annotations +import asyncio import random-from collections.abc import Sequence+from collections.abc import Awaitable, Sequence from dataclasses import dataclass  from ..util.token_truncation import formatted_truncate_text_with_token_count@@ -18,6 +19,32 @@ PTY_PROCESS_ID_MIN = 1_000 PTY_PROCESS_ID_MAX_EXCLUSIVE = 100_000  +async def _settle_pty_cleanup(+    cleanup: Awaitable[None],+    *,+    initial_cancellation: asyncio.CancelledError | None = None,+) -> None:+    cleanup_task = asyncio.ensure_future(cleanup)+    completion = asyncio.create_task(asyncio.wait((cleanup_task,)))+    cancellation = initial_cancellation+    while not completion.done():+        try:+            await asyncio.shield(completion)+        except asyncio.CancelledError as error:+            if cancellation is None:+                cancellation = error++    completion.result()+    try:+        cleanup_task.result()+    except BaseException:+        if cancellation is not None:+            raise cancellation from None+        raise+    if cancellation is not None:+        raise cancellation from None++ @dataclass(frozen=True) class PtyExecUpdate:     process_id: int | Nonetests/extensions/sandbox/test_blaxel.pyindex 3fe1d0d93..4916a3a97 100644@@ -5,6 +5,7 @@ import io import json import logging import shlex+import sys import tarfile import time import uuid@@ -1745,6 +1746,157 @@ class _FakeAiohttp:   class TestPtyExec:+    @pytest.mark.asyncio+    async def test_pty_exec_start_cancellation_closes_unregistered_http_session(+        self, fake_sandbox: _FakeSandboxInstance+    ) -> None:+        from agents.extensions.sandbox.blaxel import sandbox as mod++        connect_started = asyncio.Event()++        class _BlockingSession:+            def __init__(self) -> None:+                self._closed = False++            async def ws_connect(self, url: str) -> None:+                _ = url+                connect_started.set()+                await asyncio.Event().wait()++            async def close(self) -> None:+                self._closed = True++        class _BlockingAiohttp:+            WSMsgType = _FakeAiohttp.WSMsgType++            def __init__(self) -> None:+                self.session: _BlockingSession | None = None++            def ClientSession(self) -> _BlockingSession:+                self.session = _BlockingSession()+                return self.session++        fake_aiohttp = _BlockingAiohttp()+        session = _make_session(fake_sandbox)++        with patch.object(mod, "_import_aiohttp", return_value=fake_aiohttp):+            task = asyncio.create_task(session.pty_exec_start("echo", "hello"))+            await connect_started.wait()+            task.cancel("connect-cancel")++            with pytest.raises(asyncio.CancelledError) as exc_info:+                await task++            if sys.version_info >= (3, 11):+                assert exc_info.value.args == ("connect-cancel",)+            assert task.cancelled()++        assert fake_aiohttp.session is not None+        assert fake_aiohttp.session._closed+        assert session._pty_sessions == {}+        assert session._reserved_pty_process_ids == set()++    @pytest.mark.asyncio+    async def test_pty_exec_start_preserves_cancellation_during_cleanup(+        self, fake_sandbox: _FakeSandboxInstance+    ) -> None:+        from agents.extensions.sandbox.blaxel import sandbox as mod++        cleanup_started = asyncio.Event()+        allow_cleanup = asyncio.Event()++        class _TimeoutSession:+            def __init__(self) -> None:+                self._closed = False++            async def ws_connect(self, url: str) -> None:+                _ = url+                raise asyncio.TimeoutError()++            async def close(self) -> None:+                cleanup_started.set()+                await allow_cleanup.wait()+                self._closed = True++        class _TimeoutAiohttp:+            WSMsgType = _FakeAiohttp.WSMsgType++            def __init__(self) -> None:+                self.session: _TimeoutSession | None = None++            def ClientSession(self) -> _TimeoutSession:+                self.session = _TimeoutSession()+                return self.session++        fake_aiohttp = _TimeoutAiohttp()+        session = _make_session(fake_sandbox)++        with patch.object(mod, "_import_aiohttp", return_value=fake_aiohttp):+            task = asyncio.create_task(session.pty_exec_start("echo", "hello"))+            await cleanup_started.wait()+            task.cancel("cleanup-cancel")+            allow_cleanup.set()++            with pytest.raises(asyncio.CancelledError) as exc_info:+                await task++            if sys.version_info >= (3, 11):+                assert exc_info.value.args == ("cleanup-cancel",)+        assert fake_aiohttp.session is not None+        assert fake_aiohttp.session._closed+        assert session._pty_sessions == {}+        assert session._reserved_pty_process_ids == set()++    @pytest.mark.asyncio+    async def test_pty_exec_start_preserves_cancellation_when_cleanup_fails(+        self, fake_sandbox: _FakeSandboxInstance+    ) -> None:+        from agents.extensions.sandbox.blaxel import sandbox as mod++        cleanup_started = asyncio.Event()+        allow_cleanup = asyncio.Event()++        class _FailingCleanupSession:+            def __init__(self) -> None:+                self._closed = False++            async def ws_connect(self, url: str) -> None:+                _ = url+                raise asyncio.TimeoutError()++            async def close(self) -> None:+                cleanup_started.set()+                await allow_cleanup.wait()+                self._closed = True+                raise RuntimeError("synthetic cleanup failure")++        class _FailingCleanupAiohttp:+            WSMsgType = _FakeAiohttp.WSMsgType++            def __init__(self) -> None:+                self.session: _FailingCleanupSession | None = None++            def ClientSession(self) -> _FailingCleanupSession:+                self.session = _FailingCleanupSession()+                return self.session++        fake_aiohttp = _FailingCleanupAiohttp()+        session = _make_session(fake_sandbox)++        with patch.object(mod, "_import_aiohttp", return_value=fake_aiohttp):+            task = asyncio.create_task(session.pty_exec_start("echo", "hello"))+            await cleanup_started.wait()+            task.cancel()+            allow_cleanup.set()++            with pytest.raises(asyncio.CancelledError):+                await task++        assert fake_aiohttp.session is not None+        assert fake_aiohttp.session._closed+        assert session._pty_sessions == {}+        assert session._reserved_pty_process_ids == set()+     @pytest.mark.parametrize(         ("messages", "expected_output"),         [tests/sandbox/test_pty_types.pyindex a8c6db282..4b09515e6 100644@@ -1,8 +1,14 @@ from __future__ import annotations +import asyncio+import sys++import pytest+ from agents.sandbox.session.pty_types import (     PTY_EMPTY_YIELD_TIME_MS_MIN,     PTY_YIELD_TIME_MS_MIN,+    _settle_pty_cleanup,     allocate_pty_process_id,     clamp_pty_yield_time_ms,     process_id_to_prune_from_meta,@@ -37,3 +43,39 @@ def test_process_id_to_prune_from_meta_prefers_exited_unprotected_sessions() ->     meta.append((2002, 2.0, False))      assert process_id_to_prune_from_meta(meta) == 2001+++@pytest.mark.asyncio+async def test_settle_pty_cleanup_preserves_cancel_reason_when_cleanup_fails() -> None:+    cleanup_started = asyncio.Event()+    cleanup_release = asyncio.Event()++    async def cleanup() -> None:+        cleanup_started.set()+        await cleanup_release.wait()+        raise RuntimeError("synthetic cleanup failure")++    task = asyncio.create_task(_settle_pty_cleanup(cleanup()))+    await cleanup_started.wait()+    task.cancel("route-A")+    cleanup_release.set()++    with pytest.raises(asyncio.CancelledError) as exc_info:+        await task++    if sys.version_info >= (3, 11):+        assert exc_info.value.args == ("route-A",)+++@pytest.mark.asyncio+async def test_settle_pty_cleanup_preserves_initial_cancel_reason_when_cleanup_fails() -> None:+    async def cleanup() -> None:+        raise RuntimeError("synthetic cleanup failure")++    with pytest.raises(asyncio.CancelledError) as exc_info:+        await _settle_pty_cleanup(+            cleanup(),+            initial_cancellation=asyncio.CancelledError("startup-cancel"),+        )++    assert exc_info.value.args == ("startup-cancel",)tests/sandbox/test_unix_local.pyindex fb13be3c5..f2482be90 100644@@ -216,6 +216,34 @@ async def test_unix_local_rejects_host_path_before_creating_workspace(  @pytest.mark.review_optional class TestUnixLocalPty:+    @pytest.mark.asyncio+    async def test_tty_start_cancellation_closes_open_file_descriptors(+        self,+        tmp_path: Path,+        monkeypatch: pytest.MonkeyPatch,+    ) -> None:+        monkeypatch.setattr(unix_local_module.sys, "platform", "linux")+        workspace = tmp_path / "workspace"+        workspace.mkdir()+        session = _RecordingUnixLocalSession(workspace)+        close_calls: list[int] = []++        def openpty() -> tuple[int, int]:+            return 101, 102++        async def create_subprocess(*args: object, **kwargs: object) -> None:+            _ = (args, kwargs)+            raise asyncio.CancelledError()++        monkeypatch.setattr(unix_local_module.os, "openpty", openpty)+        monkeypatch.setattr(unix_local_module.os, "close", close_calls.append)+        monkeypatch.setattr(unix_local_module.asyncio, "create_subprocess_exec", create_subprocess)++        with pytest.raises(asyncio.CancelledError):+            await session.pty_exec_start("echo", "hello", shell=False, tty=True)++        assert close_calls == [101, 102]+     @pytest.mark.asyncio     async def test_tty_fd_close_is_owned_without_blocking_termination(         self,