Skip to content

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

fix(sdks/python): expose download response metadata

wenmoub17fa9d48059
diff --git a/docs/sdks/python.md b/docs/sdks/python.md
index 08695f9a2..0ae3cfe80 100644
--- a/docs/sdks/python.md
+++ b/docs/sdks/python.md
@@ -428,6 +428,8 @@ async with aclosing(await sandbox.files.read_bytes_stream("/tmp/large.bin")) as
break
```
+Use `read_bytes_detailed` or `read_bytes_stream_detailed` when Range response metadata is required. Close a detailed stream body if it is not fully consumed.
+
#### File operations with an explicit identity
Bind a filesystem client to a Linux UID and GID:
diff --git a/sdks/sandbox/python/src/opensandbox/adapters/download_response.py b/sdks/sandbox/python/src/opensandbox/adapters/download_response.py
new file mode 100644
index 000000000..2daba37b9
--- /dev/null
+++ b/sdks/sandbox/python/src/opensandbox/adapters/download_response.py
@@ -0,0 +1,176 @@
+#
+# Copyright 2026 Alibaba Group Holding Ltd.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import re
+from typing import TypeVar
+
+import httpx
+
+from opensandbox.models.filesystem import (
+ AsyncReadBytesStream,
+ ByteRange,
+ ReadBytesResponse,
+ ReadBytesStream,
+)
+
+_BodyT = TypeVar("_BodyT")
+_CONTENT_RANGE_RE = re.compile(r"^bytes\s+(\d+)-(\d+)/(\d+|\*)$", re.IGNORECASE)
+
+
+def _parse_header_integer(raw: str | None) -> int:
+ if raw is None or not raw.isdigit():
+ return -1
+ return int(raw)
+
+
+def _parse_content_range(raw: str | None) -> ByteRange | None:
+ if not raw:
+ return None
+
+ invalid = ByteRange(start=-1, end=-1, total=-1, raw=raw)
+ match = _CONTENT_RANGE_RE.fullmatch(raw)
+ if match is None:
+ return invalid
+
+ start = int(match.group(1))
+ end = int(match.group(2))
+ total = -1 if match.group(3) == "*" else int(match.group(3))
+ if end < start or (total != -1 and total <= end):
+ return invalid
+ return ByteRange(start=start, end=end, total=total, raw=raw)
+
+
+def create_read_bytes_response(
+ response: httpx.Response, body: _BodyT
+) -> ReadBytesResponse[_BodyT]:
+ """Map an HTTP download response to the stable SDK response model."""
+ content_length = _parse_header_integer(response.headers.get("content-length"))
+ content_range = (
+ _parse_content_range(response.headers.get("content-range"))
+ if response.status_code == 206
+ else None
+ )
+ total_size = (
+ (content_range.total if content_range is not None else -1)
+ if response.status_code == 206
+ else content_length
+ )
+
+ return ReadBytesResponse(
+ body=body,
+ status_code=response.status_code,
+ content_type=response.headers.get("content-type"),
+ content_disposition=response.headers.get("content-disposition"),
+ content_length=content_length,
+ total_size=total_size,
+ content_range=content_range,
+ )
+
+
+class _AsyncResponseByteStream:
+ def __init__(self, response: httpx.Response, chunk_size: int) -> None:
+ self._response = response
+ self._iterator = response.aiter_bytes(chunk_size=chunk_size).__aiter__()
+ self._closed = False
+
+ def __aiter__(self) -> "_AsyncResponseByteStream":
+ return self
+
+ async def __anext__(self) -> bytes:
+ if self._closed:
+ raise StopAsyncIteration
+ try:
+ return await self._iterator.__anext__()
+ except StopAsyncIteration:
+ await self.aclose()
+ raise
+ except BaseException:
+ await self.aclose()
+ raise
+
+ async def aclose(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ close_iterator = getattr(self._iterator, "aclose", None)
+ if close_iterator is not None:
+ await close_iterator()
+ await self._response.aclose()
+
+ async def __aenter__(self) -> "_AsyncResponseByteStream":
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: object | None,
+ ) -> None:
+ await self.aclose()
+
+
+class _ResponseByteStream:
+ def __init__(self, response: httpx.Response, chunk_size: int) -> None:
+ self._response = response
+ self._iterator = response.iter_bytes(chunk_size=chunk_size)
+ self._closed = False
+
+ def __iter__(self) -> "_ResponseByteStream":
+ return self
+
+ def __next__(self) -> bytes:
+ if self._closed:
+ raise StopIteration
+ try:
+ return next(self._iterator)
+ except StopIteration:
+ self.close()
+ raise
+ except BaseException:
+ self.close()
+ raise
+
+ def close(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ close_iterator = getattr(self._iterator, "close", None)
+ if close_iterator is not None:
+ close_iterator()
+ self._response.close()
+
+ def __enter__(self) -> "_ResponseByteStream":
+ return self
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: object | None,
+ ) -> None:
+ self.close()
+
+
+def iter_async_response_bytes(
+ response: httpx.Response, chunk_size: int
+) -> AsyncReadBytesStream:
+ return _AsyncResponseByteStream(response, chunk_size)
+
+
+def iter_response_bytes(
+ response: httpx.Response, chunk_size: int
+) -> ReadBytesStream:
+ return _ResponseByteStream(response, chunk_size)
diff --git a/sdks/sandbox/python/src/opensandbox/adapters/filesystem_adapter.py b/sdks/sandbox/python/src/opensandbox/adapters/filesystem_adapter.py
index 9be39f2db..f10507c5c 100644
--- a/sdks/sandbox/python/src/opensandbox/adapters/filesystem_adapter.py
+++ b/sdks/sandbox/python/src/opensandbox/adapters/filesystem_adapter.py
@@ -24,7 +24,7 @@ import json
import logging
import os
import time
-from collections.abc import AsyncGenerator, AsyncIterator
+from collections.abc import AsyncIterator
from io import IOBase, TextIOBase
from typing import TypedDict
@@ -41,15 +41,21 @@ from opensandbox.adapters.converter.response_handler import (
extract_request_id,
handle_api_error,
)
+from opensandbox.adapters.download_response import (
+ create_read_bytes_response,
+ iter_async_response_bytes,
+)
from opensandbox.adapters.filesystem_identity import filesystem_identity_path
from opensandbox.config import ConnectionConfig
from opensandbox.exceptions import InvalidArgumentException, SandboxApiException
from opensandbox.models.filesystem import (
+ AsyncReadBytesStream,
ContentReplaceEntry,
ContentReplaceResult,
DirectoryListEntry,
EntryInfo,
MoveEntry,
+ ReadBytesResponse,
SearchEntry,
SetPermissionEntry,
WriteEntry,
@@ -73,6 +79,8 @@ def _rewind_seekable_stream(stream: IOBase) -> None:
if not stream.seekable():
return
stream.seek(0)
+
+
class _DownloadRequest(TypedDict):
url: str
params: dict[str, str]
@@ -174,6 +182,21 @@ class FilesystemAdapter(Filesystem):
offset: int | None = None,
limit: int | None = None,
) -> bytes:
+ """Read file content as bytes."""
+ return (
+ await self.read_bytes_detailed(
+ path, range_header=range_header, offset=offset, limit=limit
+ )
+ ).body
+
+ async def read_bytes_detailed(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[bytes]:
"""Read file content as bytes with support for range and line-based requests.
Args:
@@ -193,7 +216,9 @@ class FilesystemAdapter(Filesystem):
"""
logger.debug(f"Reading file as bytes: {path}")
try:
- request_data = self._build_download_request(path, range_header, offset=offset, limit=limit)
+ request_data = self._build_download_request(
+ path, range_header, offset=offset, limit=limit
+ )
client = await self._get_httpx_client()
response = await client.get(
@@ -202,24 +227,46 @@ class FilesystemAdapter(Filesystem):
params=request_data["params"],
)
response.raise_for_status()
- return response.content
+ return create_read_bytes_response(response, response.content)
except Exception as e:
logger.error(f"Failed to read file {path}", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e
async def read_bytes_stream(
- self,
- path: str,
- *,
- chunk_size: int = 64 * 1024,
- range_header: str | None = None,
- offset: int | None = None,
- limit: int | None = None,
- ) -> AsyncGenerator[bytes, None]:
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> AsyncIterator[bytes]:
+ """Stream file content as byte chunks."""
+ return (
+ await self.read_bytes_stream_detailed(
+ path,
+ chunk_size=chunk_size,
+ range_header=range_header,
+ offset=offset,
+ limit=limit,
+ )
+ ).body
+
+ async def read_bytes_stream_detailed(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[AsyncReadBytesStream]:
"""Stream file content as bytes chunks via HTTP (true streaming)."""
logger.debug(f"Streaming file as bytes: {path} (chunk_size={chunk_size})")
try:
- request_data = self._build_download_request(path, range_header, offset=offset, limit=limit)
+ request_data = self._build_download_request(
+ path, range_header, offset=offset, limit=limit
+ )
client = await self._get_httpx_client()
url = request_data["url"]
@@ -246,15 +293,9 @@ class FilesystemAdapter(Filesystem):
status_code=response.status_code,
request_id=extract_request_id(response.headers),
)
-
- async def _iter() -> AsyncGenerator[bytes, None]:
- try:
- async for chunk in response.aiter_bytes(chunk_size=chunk_size):
- yield chunk
- finally:
- await response.aclose()
-
- return _iter()
+ return create_read_bytes_response(
+ response, iter_async_response_bytes(response, chunk_size)
+ )
except Exception as e:
logger.error(f"Failed to stream file {path}", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e
diff --git a/sdks/sandbox/python/src/opensandbox/adapters/isolated_filesystem_adapter.py b/sdks/sandbox/python/src/opensandbox/adapters/isolated_filesystem_adapter.py
index ff537b5dc..7abf244ed 100644
--- a/sdks/sandbox/python/src/opensandbox/adapters/isolated_filesystem_adapter.py
+++ b/sdks/sandbox/python/src/opensandbox/adapters/isolated_filesystem_adapter.py
@@ -36,14 +36,20 @@ from opensandbox.adapters.converter.response_handler import (
extract_request_id,
handle_api_error,
)
+from opensandbox.adapters.download_response import (
+ create_read_bytes_response,
+ iter_async_response_bytes,
+)
from opensandbox.config import ConnectionConfig
from opensandbox.exceptions import InvalidArgumentException, SandboxApiException
from opensandbox.models.filesystem import (
+ AsyncReadBytesStream,
ContentReplaceEntry,
ContentReplaceResult,
DirectoryListEntry,
EntryInfo,
MoveEntry,
+ ReadBytesResponse,
SearchEntry,
SetPermissionEntry,
WriteEntry,
@@ -126,6 +132,20 @@ class IsolatedFilesystemAdapter(Filesystem):
offset: int | None = None,
limit: int | None = None,
) -> bytes:
+ return (
+ await self.read_bytes_detailed(
+ path, range_header=range_header, offset=offset, limit=limit
+ )
+ ).body
+
+ async def read_bytes_detailed(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[bytes]:
try:
url = self._get_url(self.DOWNLOAD_PATH)
params: dict[str, str] = {"path": path}
@@ -139,7 +159,7 @@ class IsolatedFilesystemAdapter(Filesystem):
response = await self._httpx_client.get(url, headers=headers, params=params)
response.raise_for_status()
- return response.content
+ return create_read_bytes_response(response, response.content)
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
@@ -151,7 +171,26 @@ class IsolatedFilesystemAdapter(Filesystem):
range_header: str | None = None,
offset: int | None = None,
limit: int | None = None,
- ) -> AsyncGenerator[bytes, None]:
+ ) -> AsyncIterator[bytes]:
+ return (
+ await self.read_bytes_stream_detailed(
+ path,
+ chunk_size=chunk_size,
+ range_header=range_header,
+ offset=offset,
+ limit=limit,
+ )
+ ).body
+
+ async def read_bytes_stream_detailed(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[AsyncReadBytesStream]:
try:
url = self._get_url(self.DOWNLOAD_PATH)
params: dict[str, str] = {"path": path}
@@ -178,15 +217,9 @@ class IsolatedFilesystemAdapter(Filesystem):
status_code=response.status_code,
request_id=extract_request_id(response.headers),
)
-
- async def _iter() -> AsyncGenerator[bytes, None]:
- try:
- async for chunk in response.aiter_bytes(chunk_size=chunk_size):
- yield chunk
- finally:
- await response.aclose()
-
- return _iter()
+ return create_read_bytes_response(
+ response, iter_async_response_bytes(response, chunk_size)
+ )
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
diff --git a/sdks/sandbox/python/src/opensandbox/models/__init__.py b/sdks/sandbox/python/src/opensandbox/models/__init__.py
index e9eb26c14..cb8378276 100644
--- a/sdks/sandbox/python/src/opensandbox/models/__init__.py
+++ b/sdks/sandbox/python/src/opensandbox/models/__init__.py
@@ -32,11 +32,15 @@ from opensandbox.models.execd import (
OutputMessage,
)
from opensandbox.models.filesystem import (
+ AsyncReadBytesStream,
+ ByteRange,
ContentReplaceEntry,
ContentReplaceResult,
DirectoryListEntry,
EntryInfo,
MoveEntry,
+ ReadBytesResponse,
+ ReadBytesStream,
SearchEntry,
SetPermissionEntry,
WriteEntry,
@@ -121,6 +125,10 @@ __all__ = [
"IsolatedSessionSummary",
"IsolatedWorkspaceSpec",
# Filesystem models
+ "ByteRange",
+ "AsyncReadBytesStream",
+ "ReadBytesResponse",
+ "ReadBytesStream",
"EntryInfo",
"WriteEntry",
"MoveEntry",
diff --git a/sdks/sandbox/python/src/opensandbox/models/filesystem.py b/sdks/sandbox/python/src/opensandbox/models/filesystem.py
index 9e585f12b..9bdcce860 100644
--- a/sdks/sandbox/python/src/opensandbox/models/filesystem.py
+++ b/sdks/sandbox/python/src/opensandbox/models/filesystem.py
@@ -19,11 +19,82 @@ Filesystem-related data models.
Models for file operations, directory listings, and filesystem metadata.
"""
+from collections.abc import AsyncIterator, Iterator
+from dataclasses import dataclass
from datetime import datetime
from io import IOBase
+from typing import Generic, Protocol, TypeVar
from pydantic import BaseModel, ConfigDict, Field, field_validator
+_BodyT = TypeVar("_BodyT")
+
+
+@dataclass(frozen=True)
+class ByteRange:
+ """Parsed Content-Range response header."""
+
+ start: int
+ end: int
+ total: int
+ raw: str
+
+
+@dataclass(frozen=True)
+class ReadBytesResponse(Generic[_BodyT]):
+ """Downloaded body and its HTTP response metadata."""
+
+ body: _BodyT
+ status_code: int
+ content_type: str | None
+ content_disposition: str | None
+ content_length: int
+ total_size: int
+ content_range: ByteRange | None
+
+ @property
+ def is_partial(self) -> bool:
+ """Whether the server returned 206 Partial Content."""
+ return self.status_code == 206
+
+
+class ReadBytesStream(Protocol):
+ """Closeable synchronous download body."""
+
+ def __iter__(self) -> Iterator[bytes]: ...
+
+ def __next__(self) -> bytes: ...
+
+ def close(self) -> None: ...
+
+ def __enter__(self) -> "ReadBytesStream": ...
+
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: object | None,
+ ) -> None: ...
+
+
+class AsyncReadBytesStream(Protocol):
+ """Closeable asynchronous download body."""
+
+ def __aiter__(self) -> AsyncIterator[bytes]: ...
+
+ async def __anext__(self) -> bytes: ...
+
+ async def aclose(self) -> None: ...
+
+ async def __aenter__(self) -> "AsyncReadBytesStream": ...
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: object | None,
+ ) -> None: ...
+
class EntryInfo(BaseModel):
"""
diff --git a/sdks/sandbox/python/src/opensandbox/services/filesystem.py b/sdks/sandbox/python/src/opensandbox/services/filesystem.py
index 27990ac0a..82fedb4fe 100644
--- a/sdks/sandbox/python/src/opensandbox/services/filesystem.py
+++ b/sdks/sandbox/python/src/opensandbox/services/filesystem.py
@@ -23,11 +23,13 @@ from io import IOBase
from typing import Protocol
from opensandbox.models.filesystem import (
+ AsyncReadBytesStream,
ContentReplaceEntry,
ContentReplaceResult,
DirectoryListEntry,
EntryInfo,
MoveEntry,
+ ReadBytesResponse,
SearchEntry,
SetPermissionEntry,
WriteEntry,
@@ -101,6 +103,15 @@ class Filesystem(Protocol):
"""
...
+ async def read_bytes_detailed(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[bytes]: ...
+
async def read_bytes_stream(
self,
path: str,
@@ -115,6 +126,16 @@ class Filesystem(Protocol):
"""
...
+ async def read_bytes_stream_detailed(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[AsyncReadBytesStream]: ...
+
async def write_files(self, entries: list[WriteEntry]) -> None:
"""
Write content to files based on the provided write entries.
diff --git a/sdks/sandbox/python/src/opensandbox/sync/adapters/filesystem_adapter.py b/sdks/sandbox/python/src/opensandbox/sync/adapters/filesystem_adapter.py
index 8cee47756..3c4f93195 100644
--- a/sdks/sandbox/python/src/opensandbox/sync/adapters/filesystem_adapter.py
+++ b/sdks/sandbox/python/src/opensandbox/sync/adapters/filesystem_adapter.py
@@ -38,6 +38,10 @@ from opensandbox.adapters.converter.response_handler import (
extract_request_id,
handle_api_error,
)
+from opensandbox.adapters.download_response import (
+ create_read_bytes_response,
+ iter_response_bytes,
+)
from opensandbox.adapters.filesystem_identity import filesystem_identity_path
from opensandbox.config.connection_sync import ConnectionConfigSync
from opensandbox.exceptions import InvalidArgumentException, SandboxApiException
@@ -47,6 +51,8 @@ from opensandbox.models.filesystem import (
DirectoryListEntry,
EntryInfo,
MoveEntry,
+ ReadBytesResponse,
+ ReadBytesStream,
SearchEntry,
SetPermissionEntry,
WriteEntry,
@@ -170,6 +176,18 @@ class FilesystemAdapterSync(FilesystemSync):
offset: int | None = None,
limit: int | None = None,
) -> bytes:
+ return self.read_bytes_detailed(
+ path, range_header=range_header, offset=offset, limit=limit
+ ).body
+
+ def read_bytes_detailed(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[bytes]:
logger.debug(f"Reading file as bytes: {path}")
try:
request_data = self._build_download_request(
@@ -181,7 +199,7 @@ class FilesystemAdapterSync(FilesystemSync):
params=request_data["params"],
)
response.raise_for_status()
- return response.content
+ return create_read_bytes_response(response, response.content)
except Exception as e:
logger.error(f"Failed to read file {path}", exc_info=e)
raise ExceptionConverter.to_sandbox_exception(e) from e
@@ -195,6 +213,23 @@ class FilesystemAdapterSync(FilesystemSync):
offset: int | None = None,
limit: int | None = None,
) -> Iterator[bytes]:
+ return self.read_bytes_stream_detailed(
+ path,
+ chunk_size=chunk_size,
+ range_header=range_header,
+ offset=offset,
+ limit=limit,
+ ).body
+
+ def read_bytes_stream_detailed(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[ReadBytesStream]:
logger.debug(f"Streaming file as bytes: {path} (chunk_size={chunk_size})")
request_data = self._build_download_request(
path, range_header, offset=offset, limit=limit
@@ -222,13 +257,9 @@ class FilesystemAdapterSync(FilesystemSync):
request_id=extract_request_id(response.headers),
)
- def _iter() -> Iterator[bytes]:
- try:
- yield from response.iter_bytes(chunk_size=chunk_size)
- finally:
- response.close()
-
- return _iter()
+ return create_read_bytes_response(
+ response, iter_response_bytes(response, chunk_size)
+ )
def write_files(self, entries: list[WriteEntry]) -> None:
"""Write multiple files in a single operation using multipart upload.
diff --git a/sdks/sandbox/python/src/opensandbox/sync/adapters/isolated_filesystem_adapter.py b/sdks/sandbox/python/src/opensandbox/sync/adapters/isolated_filesystem_adapter.py
index be5a979f4..6c1f24824 100644
--- a/sdks/sandbox/python/src/opensandbox/sync/adapters/isolated_filesystem_adapter.py
+++ b/sdks/sandbox/python/src/opensandbox/sync/adapters/isolated_filesystem_adapter.py
@@ -36,6 +36,10 @@ from opensandbox.adapters.converter.response_handler import (
extract_request_id,
handle_api_error,
)
+from opensandbox.adapters.download_response import (
+ create_read_bytes_response,
+ iter_response_bytes,
+)
from opensandbox.config.connection_sync import ConnectionConfigSync
from opensandbox.exceptions import InvalidArgumentException, SandboxApiException
from opensandbox.models.filesystem import (
@@ -44,6 +48,8 @@ from opensandbox.models.filesystem import (
DirectoryListEntry,
EntryInfo,
MoveEntry,
+ ReadBytesResponse,
+ ReadBytesStream,
SearchEntry,
SetPermissionEntry,
WriteEntry,
@@ -126,6 +132,18 @@ class IsolatedFilesystemAdapterSync(FilesystemSync):
offset: int | None = None,
limit: int | None = None,
) -> bytes:
+ return self.read_bytes_detailed(
+ path, range_header=range_header, offset=offset, limit=limit
+ ).body
+
+ def read_bytes_detailed(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[bytes]:
try:
url = self._get_url(self.DOWNLOAD_PATH)
params: dict[str, str] = {"path": path}
@@ -139,7 +157,7 @@ class IsolatedFilesystemAdapterSync(FilesystemSync):
response = self._httpx_client.get(url, headers=headers, params=params)
response.raise_for_status()
- return response.content
+ return create_read_bytes_response(response, response.content)
except Exception as e:
raise ExceptionConverter.to_sandbox_exception(e) from e
@@ -152,6 +170,23 @@ class IsolatedFilesystemAdapterSync(FilesystemSync):
offset: int | None = None,
limit: int | None = None,
) -> Iterator[bytes]:
+ return self.read_bytes_stream_detailed(
+ path,
+ chunk_size=chunk_size,
+ range_header=range_header,
+ offset=offset,
+ limit=limit,
+ ).body
+
+ def read_bytes_stream_detailed(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[ReadBytesStream]:
url = self._get_url(self.DOWNLOAD_PATH)
params: dict[str, str] = {"path": path}
headers: dict[str, str] = {}
@@ -178,13 +213,9 @@ class IsolatedFilesystemAdapterSync(FilesystemSync):
request_id=extract_request_id(response.headers),
)
- def _iter() -> Iterator[bytes]:
- try:
- yield from response.iter_bytes(chunk_size=chunk_size)
- finally:
- response.close()
-
- return _iter()
+ return create_read_bytes_response(
+ response, iter_response_bytes(response, chunk_size)
+ )
def write_files(self, entries: list[WriteEntry]) -> None:
if not entries:
diff --git a/sdks/sandbox/python/src/opensandbox/sync/services/filesystem.py b/sdks/sandbox/python/src/opensandbox/sync/services/filesystem.py
index 881e37236..7a919e9ed 100644
--- a/sdks/sandbox/python/src/opensandbox/sync/services/filesystem.py
+++ b/sdks/sandbox/python/src/opensandbox/sync/services/filesystem.py
@@ -30,6 +30,8 @@ from opensandbox.models.filesystem import (
DirectoryListEntry,
EntryInfo,
MoveEntry,
+ ReadBytesResponse,
+ ReadBytesStream,
SearchEntry,
SetPermissionEntry,
WriteEntry,
@@ -106,6 +108,15 @@ class FilesystemSync(Protocol):
"""
...
+ def read_bytes_detailed(
+ self,
+ path: str,
+ *,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[bytes]: ...
+
def read_bytes_stream(
self,
path: str,
@@ -131,6 +142,16 @@ class FilesystemSync(Protocol):
"""
...
+ def read_bytes_stream_detailed(
+ self,
+ path: str,
+ *,
+ chunk_size: int = 64 * 1024,
+ range_header: str | None = None,
+ offset: int | None = None,
+ limit: int | None = None,
+ ) -> ReadBytesResponse[ReadBytesStream]: ...
+
def write_files(self, entries: list[WriteEntry]) -> None:
"""
Write content to files based on the provided write entries.
diff --git a/sdks/sandbox/python/tests/test_filesystem_download_response.py b/sdks/sandbox/python/tests/test_filesystem_download_response.py
new file mode 100644
index 000000000..77bcdc2c4
--- /dev/null
+++ b/sdks/sandbox/python/tests/test_filesystem_download_response.py
@@ -0,0 +1,211 @@
+#
+# Copyright 2026 Alibaba Group Holding Ltd.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import httpx
+import pytest
+
+from opensandbox.adapters.filesystem_adapter import FilesystemAdapter
+from opensandbox.config import ConnectionConfig
+from opensandbox.config.connection_sync import ConnectionConfigSync
+from opensandbox.models import ByteRange, ReadBytesResponse
+from opensandbox.models.sandboxes import SandboxEndpoint
+from opensandbox.sync.adapters.filesystem_adapter import FilesystemAdapterSync
+
+
+def _endpoint() -> SandboxEndpoint:
+ return SandboxEndpoint(endpoint="localhost:44772")
+
+
+async def test_async_read_bytes_detailed_exposes_partial_metadata() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ assert request.headers["Range"] == "bytes=0-4"
+ return httpx.Response(
+ 206,
+ request=request,
+ content=b"hello",
+ headers={
+ "Content-Type": "application/octet-stream",
+ "Content-Disposition": 'attachment; filename="data.bin"',
+ "Content-Length": "5",
+ "Content-Range": "bytes 0-4/10",
+ },
+ )
+
+ adapter = FilesystemAdapter(
+ ConnectionConfig(protocol="http", transport=httpx.MockTransport(handler)),
+ _endpoint(),
+ )
+ response = await adapter.read_bytes_detailed("/data.bin", range_header="bytes=0-4")
+
+ assert isinstance(response, ReadBytesResponse)
+ assert response.body == b"hello"
+ assert response.status_code == 206
+ assert response.is_partial is True
+ assert response.content_type == "application/octet-stream"
+ assert response.content_disposition == 'attachment; filename="data.bin"'
+ assert response.content_length == 5
+ assert response.total_size == 10
+ assert response.content_range == ByteRange(
+ start=0, end=4, total=10, raw="bytes 0-4/10"
+ )
+ await adapter._httpx_client.aclose()
+
+
+async def test_async_read_bytes_detailed_identifies_ignored_and_invalid_ranges() -> (
+ None
+):
+ ranges = iter([None, "garbage", "bytes 5-9/*"])
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ content_range = next(ranges)
+ status = 200 if content_range is None else 206
+ headers = {"Content-Length": "10"}
+ if content_range is not None:
+ headers["Content-Range"] = content_range
+ return httpx.Response(
+ status, request=request, content=b"0123456789", headers=headers
+ )
+
+ adapter = FilesystemAdapter(
+ ConnectionConfig(protocol="http", transport=httpx.MockTransport(handler)),
+ _endpoint(),
+ )
+
+ ignored = await adapter.read_bytes_detailed("/data.bin", range_header="bytes=5-")
+ assert ignored.is_partial is False
+ assert ignored.content_range is None
+ assert ignored.total_size == 10
+
+ malformed = await adapter.read_bytes_detailed("/data.bin")
+ assert malformed.content_range == ByteRange(-1, -1, -1, "garbage")
+ assert malformed.total_size == -1
+
+ unknown = await adapter.read_bytes_detailed("/data.bin")
+ assert unknown.content_range == ByteRange(5, 9, -1, "bytes 5-9/*")
+ assert unknown.total_size == -1
+ await adapter._httpx_client.aclose()
+
+
+class _TrackingAsyncStream(httpx.AsyncByteStream):
+ def __init__(self) -> None:
+ self.closed = False
+
+ async def __aiter__(self):
+ yield b"hello"
+
+ async def aclose(self) -> None:
+ self.closed = True
+
+
+async def test_async_detailed_and_legacy_streams_close_responses() -> None:
+ streams: list[_TrackingAsyncStream] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ stream = _TrackingAsyncStream()
+ streams.append(stream)
+ return httpx.Response(
+ 206,
+ request=request,
+ stream=stream,
+ headers={"Content-Length": "5", "Content-Range": "bytes 0-4/10"},
+ )
+
+ adapter = FilesystemAdapter(
+ ConnectionConfig(protocol="http", transport=httpx.MockTransport(handler)),
+ _endpoint(),
+ )
+
+ detailed = await adapter.read_bytes_stream_detailed("/data.bin")
+ assert detailed.is_partial is True
+ assert streams[0].closed is False
+ assert b"".join([chunk async for chunk in detailed.body]) == b"hello"
+ assert streams[0].closed is True
+
+ legacy = await adapter.read_bytes_stream("/data.bin")
+ assert b"".join([chunk async for chunk in legacy]) == b"hello"
+ assert streams[1].closed is True
+
+ unconsumed = await adapter.read_bytes_stream_detailed("/data.bin")
+ await unconsumed.body.aclose()
+ assert streams[2].closed is True
+
+ partial = await adapter.read_bytes_stream_detailed("/data.bin")
+ async with partial.body:
+ async for _chunk in partial.body:
+ break
+ assert streams[3].closed is True
+ await adapter._httpx_client.aclose()
+
+
+def test_sync_detailed_and_legacy_reads_preserve_behavior() -> None:
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 206,
+ request=request,
+ content=b"hello",
+ headers={"Content-Length": "5", "Content-Range": "bytes 0-4/10"},
+ )
+
+ adapter = FilesystemAdapterSync(
+ ConnectionConfigSync(protocol="http", transport=httpx.MockTransport(handler)),
+ _endpoint(),
+ )
+
+ detailed = adapter.read_bytes_detailed("/data.bin")
+ assert detailed.body == b"hello"
+ assert detailed.content_range == ByteRange(0, 4, 10, "bytes 0-4/10")
+ assert adapter.read_bytes("/data.bin") == b"hello"
+ assert b"".join(adapter.read_bytes_stream("/data.bin")) == b"hello"
+ adapter._httpx_client.close()
+
+
+class _TrackingSyncStream(httpx.SyncByteStream):
+ def __init__(self) -> None:
+ self.closed = False
+
+ def __iter__(self):
+ yield b"hello"
+
+ def close(self) -> None:
+ self.closed = True
+
+
+def test_sync_detailed_streams_close_unconsumed_and_partial_responses() -> None:
+ streams: list[_TrackingSyncStream] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ stream = _TrackingSyncStream()
+ streams.append(stream)
+ return httpx.Response(206, request=request, stream=stream)
+
+ adapter = FilesystemAdapterSync(
+ ConnectionConfigSync(protocol="http", transport=httpx.MockTransport(handler)),
+ _endpoint(),
+ )
+
+ unconsumed = adapter.read_bytes_stream_detailed("/data.bin")
+ unconsumed.body.close()
+ assert streams[0].closed is True
+
+ partial = adapter.read_bytes_stream_detailed("/data.bin")
+ with partial.body:
+ for _chunk in partial.body:
+ break
+ assert streams[1].closed is True
+ adapter._httpx_client.close()