Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

fix(sdk-python): map transport errors raised while reading a download body

Maohaoeb1f69a6a557
diff --git a/docs/sdks/python.md b/docs/sdks/python.md
index 2783e6188..9cbadd8f0 100644
--- a/docs/sdks/python.md
+++ b/docs/sdks/python.md
@@ -417,7 +417,7 @@ await sandbox.files.delete_files(["/tmp/hello.txt"])
For binary data, pass `bytes` to `WriteEntry.data` and use `read_bytes()`; use `read_bytes_stream()` for large downloads. `read_file()` and `read_bytes()` also accept `offset` and `limit` for partial reads.
-Async download iterators release their HTTP response when iteration finishes, fails, or is cancelled. If you stop consuming a download early, close the started iterator with `aclose()` (for example, using `contextlib.aclosing`) to release the connection promptly. This applies to both `sandbox.files` and isolated-session files.
+Async download iterators release their HTTP response when iteration finishes, fails, or is cancelled. A connection failure while reading a download body raises the same SDK exception as a failed request (for example `SandboxConnectionException`), with the underlying `httpx` error as its `__cause__`; this applies to the sync streams too. If you stop consuming a download early, close the started iterator with `aclose()` (for example, using `contextlib.aclosing`) to release the connection promptly. This applies to both `sandbox.files` and isolated-session files.
```python
from contextlib import aclosing
diff --git a/sdks/sandbox/python/src/opensandbox/adapters/download_response.py b/sdks/sandbox/python/src/opensandbox/adapters/download_response.py
index 2df19bf94..7432fd2a4 100644
--- a/sdks/sandbox/python/src/opensandbox/adapters/download_response.py
+++ b/sdks/sandbox/python/src/opensandbox/adapters/download_response.py
@@ -19,6 +19,7 @@ from typing import TypeVar
import httpx
+from opensandbox.adapters.converter.exception_converter import ExceptionConverter
from opensandbox.models.filesystem import (
AsyncReadBytesStream,
ByteRange,
@@ -93,8 +94,11 @@ class _AsyncResponseByteStream:
raise StopAsyncIteration
try:
return await self._iterator.__anext__()
- except BaseException:
+ except BaseException as e:
await self.aclose()
+ if isinstance(e, Exception) and not isinstance(e, StopAsyncIteration):
+ # Same mapping as the request itself, e.g. a reset mid-body.
+ raise ExceptionConverter.to_sandbox_exception(e) from e
raise
async def aclose(self) -> None:
@@ -127,8 +131,11 @@ class _ResponseByteStream:
raise StopIteration
try:
return next(self._iterator)
- except BaseException:
+ except BaseException as e:
self.close()
+ if isinstance(e, Exception) and not isinstance(e, StopIteration):
+ # Same mapping as the request itself, e.g. a reset mid-body.
+ raise ExceptionConverter.to_sandbox_exception(e) from e
raise
def close(self) -> None:
diff --git a/sdks/sandbox/python/tests/test_filesystem_download_cleanup.py b/sdks/sandbox/python/tests/test_filesystem_download_cleanup.py
index 4119de38f..c99ec338a 100644
--- a/sdks/sandbox/python/tests/test_filesystem_download_cleanup.py
+++ b/sdks/sandbox/python/tests/test_filesystem_download_cleanup.py
@@ -24,7 +24,7 @@ import pytest
from opensandbox.adapters.filesystem_adapter import FilesystemAdapter
from opensandbox.adapters.isolated_filesystem_adapter import IsolatedFilesystemAdapter
from opensandbox.config import ConnectionConfig
-from opensandbox.exceptions import SandboxApiException
+from opensandbox.exceptions import SandboxApiException, SandboxConnectionException
from opensandbox.models.sandboxes import SandboxEndpoint
_AdapterFactory = Callable[
@@ -112,9 +112,9 @@ async def test_download_read_failure_releases_response(download_adapter: _Adapte
try:
chunks = await adapter.read_bytes_stream("/tmp/file", chunk_size=4)
assert await anext(chunks) == b"abcd"
- with pytest.raises(httpx.ReadError) as exc:
+ with pytest.raises(SandboxConnectionException) as exc:
await anext(chunks)
- assert exc.value is failure
+ assert exc.value.__cause__ is failure
assert source.closed
assert response.is_closed
finally:
diff --git a/sdks/sandbox/python/tests/test_filesystem_download_response.py b/sdks/sandbox/python/tests/test_filesystem_download_response.py
index 2cbde695b..2d211fda1 100644
--- a/sdks/sandbox/python/tests/test_filesystem_download_response.py
+++ b/sdks/sandbox/python/tests/test_filesystem_download_response.py
@@ -21,8 +21,10 @@ import httpx
import pytest
from opensandbox.adapters.filesystem_adapter import FilesystemAdapter
+from opensandbox.adapters.isolated_filesystem_adapter import IsolatedFilesystemAdapter
from opensandbox.config import ConnectionConfig
from opensandbox.config.connection_sync import ConnectionConfigSync
+from opensandbox.exceptions import SandboxConnectionException
from opensandbox.models import ByteRange
from opensandbox.models.sandboxes import SandboxEndpoint
from opensandbox.services import DownloadFilesystem
@@ -344,3 +346,64 @@ def test_sync_line_reads_report_unknown_total_size(options) -> None:
response.body.close()
finally:
adapter._httpx_client.close()
+
+
+_SESSION_ID = "12345678-1234-5678-1234-567812345678"
+
+
+class _ResetMidBody(httpx.SyncByteStream):
+ def __iter__(self):
+ yield b"a"
+ raise httpx.ReadError("connection reset")
+
+
+class _AsyncResetMidBody(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ yield b"a"
+ raise httpx.ReadError("connection reset")
+
+
[email protected]("isolated", [False, True])
+def test_sync_stream_maps_errors_while_reading_the_body(isolated: bool) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, request=request, stream=_ResetMidBody())
+
+ config = ConnectionConfigSync(protocol="http", transport=httpx.MockTransport(handler))
+ if isolated:
+ adapter = IsolatedFilesystemAdapterSync(config, _endpoint(), _SESSION_ID)
+ else:
+ adapter = FilesystemAdapterSync(config, _endpoint())
+
+ # The request succeeds; the reset only surfaces while iterating.
+ for body in (
+ adapter.read_bytes_stream_detailed("/data.bin").body,
+ adapter.read_bytes_stream("/data.bin"),
+ ):
+ with pytest.raises(SandboxConnectionException) as exc:
+ for _chunk in body:
+ pass
+ assert isinstance(exc.value.__cause__, httpx.ReadError)
+ adapter._httpx_client.close()
+
+
[email protected]("isolated", [False, True])
+async def test_async_stream_maps_errors_while_reading_the_body(isolated: bool) -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, request=request, stream=_AsyncResetMidBody())
+
+ config = ConnectionConfig(protocol="http", transport=httpx.MockTransport(handler))
+ if isolated:
+ adapter = IsolatedFilesystemAdapter(config, _endpoint(), _SESSION_ID)
+ else:
+ adapter = FilesystemAdapter(config, _endpoint())
+
+ for body in (
+ (await adapter.read_bytes_stream_detailed("/data.bin")).body,
+ await adapter.read_bytes_stream("/data.bin"),
+ ):
+ with pytest.raises(SandboxConnectionException) as exc:
+ async for _chunk in body:
+ pass
+ assert isinstance(exc.value.__cause__, httpx.ReadError)
+ await adapter._httpx_client.aclose()