Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(sdk): align download metadata and error handling
wenmou97f04351381e
diff --git a/sdks/sandbox/csharp/src/OpenSandbox/Adapters/FilesystemAdapter.cs b/sdks/sandbox/csharp/src/OpenSandbox/Adapters/FilesystemAdapter.csindex 775c2f871..58f0a34ae 100644--- a/sdks/sandbox/csharp/src/OpenSandbox/Adapters/FilesystemAdapter.cs+++ b/sdks/sandbox/csharp/src/OpenSandbox/Adapters/FilesystemAdapter.cs@@ -244,25 +244,14 @@ internal sealed class FilesystemAdapter : IIdentitySandboxFilesusing var request = BuildDownloadRequest(path, options);var response = await _client.SendTransferAsync(request, cancellationToken).ConfigureAwait(false);- if (!response.IsSuccessStatusCode)+ try{- try- {- var content = await HttpClientWrapper.ReadContentStringAsync(response.Content, cancellationToken).ConfigureAwait(false);- var requestId = response.Headers.TryGetValues(Constants.RequestIdHeader, out var values)- ? values.FirstOrDefault()- : null;-- throw new SandboxApiException(- message: "Download stream failed",- statusCode: (int)response.StatusCode,- requestId: requestId,- rawBody: content);- }- finally- {- response.Dispose();- }+ await _client.EnsureSuccessAsync(response, cancellationToken).ConfigureAwait(false);+ }+ catch+ {+ response.Dispose();+ throw;}IAsyncReadBytesStream body = new ResponseByteStream(response, cancellationToken);@@ -298,8 +287,8 @@ internal sealed class FilesystemAdapter : IIdentitySandboxFilesreturn new ReadBytesResponse<T>(Body: body,StatusCode: (int)response.StatusCode,- ContentType: response.Content.Headers.ContentType?.ToString(),- ContentDisposition: response.Content.Headers.ContentDisposition?.ToString(),+ ContentType: GetContentHeader(response, "Content-Type"),+ ContentDisposition: GetContentHeader(response, "Content-Disposition"),ContentLength: contentLength,TotalSize: isPartial ? contentRange?.Total ?? -1 : contentLength,ContentRange: contentRange);diff --git a/sdks/sandbox/csharp/tests/OpenSandbox.Tests/FilesystemAdapterTests.cs b/sdks/sandbox/csharp/tests/OpenSandbox.Tests/FilesystemAdapterTests.csindex ac74222a5..894da4c79 100644--- a/sdks/sandbox/csharp/tests/OpenSandbox.Tests/FilesystemAdapterTests.cs+++ b/sdks/sandbox/csharp/tests/OpenSandbox.Tests/FilesystemAdapterTests.cs@@ -16,6 +16,7 @@ using System.Net;using System.Text;using FluentAssertions;using OpenSandbox.Adapters;+using OpenSandbox.Core;using OpenSandbox.Internal;using OpenSandbox.Models;using Xunit;@@ -204,6 +205,21 @@ public class FilesystemAdapterTestsresponse.TotalSize.Should().Be(10);}+ [Fact]+ public async Task ReadBytesDetailedAsync_ShouldIdentifyPartialResponseWithoutContentRange()+ {+ var handler = new DownloadHandler();+ handler.Enqueue(DownloadResponse(HttpStatusCode.PartialContent, "hello"));+ using var client = new HttpClient(handler);+ var adapter = CreateAdapter(client);++ var response = await adapter.ReadBytesDetailedAsync("/data.bin");++ response.IsPartial.Should().BeTrue();+ response.ContentRange.Should().BeNull();+ response.TotalSize.Should().Be(-1);+ }+[Fact]public async Task ReadBytesDetailedAsync_ShouldPreserveInvalidAndUnknownRanges(){@@ -262,6 +278,31 @@ public class FilesystemAdapterTestspartialContent.Disposed.Should().BeTrue();}+ [Fact]+ public async Task ReadBytesStreamDetailedAsync_ShouldUseStandardApiErrorMapping()+ {+ var errorContent = new TrackingContent(+ """{"error":{"code":"FILE_NOT_FOUND","message":"missing file"}}""");+ var errorResponse = new HttpResponseMessage(HttpStatusCode.NotFound)+ {+ Content = errorContent,+ };+ errorResponse.Headers.TryAddWithoutValidation(Constants.RequestIdHeader, "request-123");+ var handler = new DownloadHandler();+ handler.Enqueue(errorResponse);+ using var client = new HttpClient(handler);+ var adapter = CreateAdapter(client);++ var action = () => adapter.ReadBytesStreamDetailedAsync("/missing.bin");++ var exception = await action.Should().ThrowAsync<SandboxApiException>();+ exception.Which.StatusCode.Should().Be(404);+ exception.Which.RequestId.Should().Be("request-123");+ exception.Which.Error.Code.Should().Be("FILE_NOT_FOUND");+ exception.Which.Error.Message.Should().Be("missing file");+ errorContent.Disposed.Should().BeTrue();+ }+private static FilesystemAdapter CreateAdapter(HttpClient client){var wrapper = new HttpClientWrapper(client, "http://localhost:8080");diff --git a/sdks/sandbox/go/opensandbox_test.go b/sdks/sandbox/go/opensandbox_test.goindex ed935243c..8609b4274 100644--- a/sdks/sandbox/go/opensandbox_test.go+++ b/sdks/sandbox/go/opensandbox_test.go@@ -1897,6 +1897,23 @@ func TestDownloadFileResponse_Range(t *testing.T) {require.Equal(t, ByteRange{Start: 0, End: 4, Total: 10, Raw: "bytes 0-4/10"}, *resp.ContentRange)}+func TestDownloadFileResponse_PartialWithoutContentRange(t *testing.T) {+ _, client := newExecdServer(t, func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusPartialContent)+ _, _ = w.Write([]byte("hello"))+ })++ resp, err := client.DownloadFileResponse(context.Background(), "/sandbox/big.bin", "bytes=0-4")+ require.NoErrorf(t, err, "DownloadFileResponse partial without Content-Range")+ defer resp.Body.Close()++ require.Equal(t, true, resp.IsPartial())+ if resp.ContentRange != nil {+ assert.Fail(t, fmt.Sprintf("ContentRange = %+v, want nil", resp.ContentRange))+ }+ require.Equal(t, int64(-1), resp.TotalSize)+}+func TestDownloadFileResponse_InvalidContentRange(t *testing.T) {_, client := newExecdServer(t, func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Range", "garbage")diff --git a/sdks/sandbox/javascript/tests/filesystem.download-response.test.mjs b/sdks/sandbox/javascript/tests/filesystem.download-response.test.mjsindex ea90148d8..a260df903 100644--- a/sdks/sandbox/javascript/tests/filesystem.download-response.test.mjs+++ b/sdks/sandbox/javascript/tests/filesystem.download-response.test.mjs@@ -83,6 +83,20 @@ test("readBytesDetailed identifies an ignored Range request", async () => {assert.equal(response.totalSize, 10);});+test("readBytesDetailed identifies a partial response without Content-Range", async () => {+ const adapter = createAdapter(async () =>+ new Response("hello", {+ status: 206,+ }),+ );++ const response = await adapter.readBytesDetailed("/data.bin");++ assert.equal(response.isPartial, true);+ assert.equal(response.contentRange, undefined);+ assert.equal(response.totalSize, -1);+});+test("readBytesDetailed preserves malformed and unknown Content-Range values", async () => {const ranges = ["garbage", "bytes 5-9/*"];const adapter = createAdapter(async () =>diff --git a/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/FilesystemAdapterTest.kt b/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/FilesystemAdapterTest.ktindex d43db1be3..6949ae762 100644--- a/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/FilesystemAdapterTest.kt+++ b/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/FilesystemAdapterTest.kt@@ -213,6 +213,21 @@ class FilesystemAdapterTest {assertEquals(10, response.totalSize)}+ @Test+ fun `readByteArrayDetailed identifies a partial response without Content-Range`() {+ mockWebServer.enqueue(+ MockResponse()+ .setResponseCode(206)+ .setBody("hello"),+ )++ val response = filesystemAdapter.readByteArrayDetailed("/data.bin")++ assertTrue(response.isPartial)+ assertNull(response.contentRange)+ assertEquals(-1, response.totalSize)+ }+@Testfun `readByteArrayDetailed preserves invalid and unknown Content-Range values`() {mockWebServer.enqueue(diff --git a/sdks/sandbox/python/src/opensandbox/adapters/isolated_filesystem_adapter.py b/sdks/sandbox/python/src/opensandbox/adapters/isolated_filesystem_adapter.pyindex 7abf244ed..d8954b549 100644--- a/sdks/sandbox/python/src/opensandbox/adapters/isolated_filesystem_adapter.py+++ b/sdks/sandbox/python/src/opensandbox/adapters/isolated_filesystem_adapter.py@@ -21,7 +21,7 @@ Uses auto-generated isolated_execution API modules with explicit session_id.import jsonimport logging-from collections.abc import AsyncGenerator+from collections.abc import AsyncIteratorfrom io import IOBase, TextIOBasefrom uuid import UUIDdiff --git a/sdks/sandbox/python/tests/test_filesystem_download_response.py b/sdks/sandbox/python/tests/test_filesystem_download_response.pyindex 77bcdc2c4..ca7618120 100644--- a/sdks/sandbox/python/tests/test_filesystem_download_response.py+++ b/sdks/sandbox/python/tests/test_filesystem_download_response.py@@ -101,6 +101,24 @@ async def test_async_read_bytes_detailed_identifies_ignored_and_invalid_ranges()await adapter._httpx_client.aclose()+async def test_async_read_bytes_detailed_identifies_partial_without_range() -> None:+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(206, request=request, content=b"hello")++ adapter = FilesystemAdapter(+ ConnectionConfig(protocol="http", transport=httpx.MockTransport(handler)),+ _endpoint(),+ )++ response = await adapter.read_bytes_detailed("/data.bin")++ assert response.is_partial is True+ assert response.content_range is None+ assert response.total_size == -1+ await adapter._httpx_client.aclose()++class _TrackingAsyncStream(httpx.AsyncByteStream):def __init__(self) -> None:self.closed = False