Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(sdk): preserve raw response body on Kotlin SDK deserialize failures
高然3fef14bf1f77
diff --git a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/converter/Serializer.kt b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/converter/Serializer.ktindex 9ee0312db..9772d0533 100644--- a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/converter/Serializer.kt+++ b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/converter/Serializer.kt@@ -16,6 +16,7 @@package com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter+import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxInternalExceptionimport kotlinx.serialization.KSerializerimport kotlinx.serialization.descriptors.elementNamesimport kotlinx.serialization.encoding.Decoder@@ -36,6 +37,43 @@ internal val jsonParser =coerceInputValues = true}+/** Upper bound for response payloads embedded in decode-failure messages. */+internal const val DECODE_FAILURE_PAYLOAD_LIMIT = 2048++/**+ * Decodes a raw HTTP response body, converting deserialization failures into a+ * [SandboxInternalException] whose message keeps the raw payload (truncated to+ * [DECODE_FAILURE_PAYLOAD_LIMIT] characters) so the server's actual response is+ * never lost to the failure itself.+ *+ * Covers both [Exception]s (e.g. SerializationException) and [LinkageError]s+ * (e.g. AbstractMethodError from a serializer/runtime version mismatch): the+ * latter is an `Error`, so adapter-level `catch (Exception)` blocks would+ * otherwise let it escape without any response context.+ */+internal fun <T> Json.decodeResponseBody(+ serializer: KSerializer<T>,+ payload: String,+ operation: String,+): T =+ try {+ decodeFromString(serializer, payload)+ } catch (e: Exception) {+ throw responseDecodeFailure(operation, payload, e)+ } catch (e: LinkageError) {+ throw responseDecodeFailure(operation, payload, e)+ }++internal fun responseDecodeFailure(+ operation: String,+ payload: String,+ cause: Throwable,+): SandboxInternalException =+ SandboxInternalException(+ message = "$operation: failed to decode response body. Body: ${payload.take(DECODE_FAILURE_PAYLOAD_LIMIT)}",+ cause = cause,+ )+abstract class AbstractUnknownPropertiesSerializer<T>(private val delegate: KSerializer<T>,) : KSerializer<T> {diff --git a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/ExecdEventSupport.kt b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/ExecdEventSupport.ktindex 4932f2a11..1e35a74e6 100644--- a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/ExecdEventSupport.kt+++ b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/ExecdEventSupport.kt@@ -26,12 +26,18 @@ public object ExecdEventSupport {* Decode one SSE/NDJSON line into an [EventNode], skipping framing lines* and unwrapping the `data:` prefix. Returns null for non-payload lines.*- * [onError] is invoked for lines carrying a payload that fails to parse;+ * [onError] is invoked with the raw line for payloads that fail to parse;* callers must pass it so malformed SSE lines are never dropped silently.+ *+ * A [LinkageError] (e.g. `AbstractMethodError` from a serializer/runtime+ * version mismatch) is systemic: the raw line is reported through [onError]+ * and then the error is rethrown, because skipping every event would turn+ * the failure into a silent stream death.*/public fun decodeEventLine(line: String,- onError: (String, Exception) -> Unit,+ decodePayload: (String) -> EventNode = { jsonParser.decodeFromString(EventNode.serializer(), it) },+ onError: (String, Throwable) -> Unit,): EventNode? {if (line.isBlank()) {return null@@ -52,10 +58,13 @@ public object ExecdEventSupport {}return try {- jsonParser.decodeFromString(EventNode.serializer(), payload)+ decodePayload(payload)} catch (e: Exception) {onError(line, e)null+ } catch (e: LinkageError) {+ onError(line, e)+ throw e}}diff --git a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/IsolatedSessionsAdapter.kt b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/IsolatedSessionsAdapter.ktindex 2e3a10403..3c78438c4 100644--- a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/IsolatedSessionsAdapter.kt+++ b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/IsolatedSessionsAdapter.kt@@ -40,6 +40,7 @@ import com.alibaba.opensandbox.sandbox.domain.services.Filesystemimport com.alibaba.opensandbox.sandbox.domain.services.IsolationServiceimport com.alibaba.opensandbox.sandbox.domain.services.IsolationSessionimport com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.ExecutionEventDispatcher+import com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.decodeResponseBodyimport com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.toSandboxApiExceptionimport com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.toSandboxExceptionimport kotlinx.serialization.Serializable@@ -272,9 +273,10 @@ internal class IsolatedSessionsAdapter(httpClientProvider.httpClient.newCall(httpRequest).execute().use { response ->ensureSuccess(response, "create isolated session")val resp =- json.decodeFromString(+ json.decodeResponseBody(IsolatedSessionInfoResponse.serializer(),response.body!!.string(),+ "create isolated session",)val info =IsolatedSessionInfo(@@ -301,9 +303,10 @@ internal class IsolatedSessionsAdapter(httpClientProvider.httpClient.newCall(httpRequest).execute().use { response ->ensureSuccess(response, "attach isolated session")val resp =- json.decodeFromString(+ json.decodeResponseBody(IsolatedSessionStateResponse.serializer(),response.body!!.string(),+ "attach isolated session",)val info =IsolatedSessionInfo(@@ -351,9 +354,10 @@ internal class IsolatedSessionsAdapter(httpClientProvider.httpClient.newCall(httpRequest).execute().use { response ->ensureSuccess(response, "get isolated session")val resp =- json.decodeFromString(+ json.decodeResponseBody(IsolatedSessionStateResponse.serializer(),response.body!!.string(),+ "get isolated session",)return IsolatedSessionState(status = resp.status,@@ -471,9 +475,10 @@ internal class IsolatedSessionsAdapter(}}val resp =- json.decodeFromString(+ json.decodeResponseBody(IsolatedBackgroundRunResponse.serializer(),response.body!!.string(),+ "run background in isolated session",)return IsolatedBackgroundRun(sessionId = resp.session_id,@@ -503,9 +508,10 @@ internal class IsolatedSessionsAdapter(httpClientProvider.httpClient.newCall(httpRequest).execute().use { response ->ensureSuccess(response, "get isolated run status")val resp =- json.decodeFromString(+ json.decodeResponseBody(IsolatedRunStatusResponse.serializer(),response.body!!.string(),+ "get isolated run status",)return IsolatedRunStatus(sessionId = resp.session_id,@@ -587,9 +593,10 @@ internal class IsolatedSessionsAdapter(httpClientProvider.httpClient.newCall(httpRequest).execute().use { response ->ensureSuccess(response, "get isolated capabilities")val resp =- json.decodeFromString(+ json.decodeResponseBody(IsolatedCapabilitiesResponse.serializer(),response.body!!.string(),+ "get isolated capabilities",)return IsolatedCapabilities(available = resp.available,@@ -630,9 +637,10 @@ internal class IsolatedSessionsAdapter(httpClientProvider.httpClient.newCall(httpRequest).execute().use { response ->ensureSuccess(response, "list isolated sessions")val resp =- json.decodeFromString(+ json.decodeResponseBody(ListIsolatedSessionsResponse.serializer(),response.body!!.string(),+ "list isolated sessions",)return resp.sessions.map { summary ->IsolatedSessionSummary(diff --git a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/SandboxesAdapter.kt b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/SandboxesAdapter.ktindex 81d309f56..319dcdbc3 100644--- a/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/SandboxesAdapter.kt+++ b/sdks/sandbox/kotlin/sandbox/src/main/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/SandboxesAdapter.kt@@ -64,10 +64,10 @@ import com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.Templatimport com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.TemplateModelConverter.toApiCreateTemplateSandboxRequestimport com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.TemplateModelConverter.toPagedTemplateInfosimport com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.TemplateModelConverter.toTemplateInfo+import com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.decodeResponseBodyimport com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.toSandboxApiExceptionimport com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter.toSandboxExceptionimport com.alibaba.opensandbox.sandbox.transport.RequestDeadline-import kotlinx.serialization.decodeFromStringimport kotlinx.serialization.encodeToStringimport okhttp3.HttpUrl.Companion.toHttpUrlimport okhttp3.MediaType.Companion.toMediaType@@ -276,7 +276,11 @@ internal class SandboxesAdapter(provider.authenticatedClient.newCall(request).execute().use { response ->val responseBody = response.body?.string().orEmpty()if (response.isSuccessful) {- return Serializer.kotlinxSerializationJson.decodeFromString<ApiSandbox>(responseBody)+ return Serializer.kotlinxSerializationJson.decodeResponseBody(+ ApiSandbox.serializer(),+ responseBody,+ "patch sandbox metadata",+ )}throw response.toSandboxApiException(responseBody) { statusCode, body ->"Failed to patch sandbox metadata. Status code: $statusCode, Body: $body"diff --git a/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/converter/ResponseBodyDecodingTest.kt b/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/converter/ResponseBodyDecodingTest.ktnew file mode 100644index 000000000..9804f7e3e--- /dev/null+++ b/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/converter/ResponseBodyDecodingTest.kt@@ -0,0 +1,100 @@+/*+ * Copyright 2026 The OpenSandbox Authors+ *+ * 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.+ */++package com.alibaba.opensandbox.sandbox.infrastructure.adapters.converter++import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxInternalException+import kotlinx.serialization.KSerializer+import kotlinx.serialization.Serializable+import kotlinx.serialization.builtins.serializer+import kotlinx.serialization.descriptors.PrimitiveKind+import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor+import kotlinx.serialization.descriptors.SerialDescriptor+import kotlinx.serialization.encoding.Decoder+import kotlinx.serialization.encoding.Encoder+import org.junit.jupiter.api.Assertions.assertEquals+import org.junit.jupiter.api.Assertions.assertSame+import org.junit.jupiter.api.Assertions.assertTrue+import org.junit.jupiter.api.Test+import org.junit.jupiter.api.assertThrows++class ResponseBodyDecodingTest {+ @Serializable+ private data class Sample(val id: String)++ /** Serializer whose deserialize throws the given throwable, emulating e.g. a broken generated serializer. */+ private class FailingSerializer(+ private val error: Throwable,+ ) : KSerializer<Sample> {+ override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Sample", PrimitiveKind.STRING)++ override fun deserialize(decoder: Decoder): Sample = throw error++ override fun serialize(+ encoder: Encoder,+ value: Sample,+ ) = throw error+ }++ private val payload = """{"error":{"code":"INTERNAL","message":"execd exploded"}}"""++ @Test+ fun `decodes well-formed bodies unchanged`() {+ val decoded = jsonParser.decodeResponseBody(String.serializer(), "\"ok\"", "op")+ assertEquals("ok", decoded)+ }++ @Test+ fun `wraps serialization failures with the raw body`() {+ val boom = IllegalStateException("Unexpected JSON token")+ val thrown =+ assertThrows<SandboxInternalException> {+ jsonParser.decodeResponseBody(FailingSerializer(boom), payload, "create isolated session")+ }++ assertTrue(thrown.message!!.contains("create isolated session"))+ assertTrue(thrown.message!!.contains(payload))+ assertSame(boom, thrown.cause)+ }++ @Test+ fun `wraps linkage errors such as AbstractMethodError with the raw body`() {+ // LinkageError is an Error, not an Exception: without an explicit catch+ // branch it would escape every adapter-level catch (Exception) block and+ // the raw response body would be lost entirely.+ val boom = AbstractMethodError("missing typeParametersSerializers()")+ val thrown =+ assertThrows<SandboxInternalException> {+ jsonParser.decodeResponseBody(FailingSerializer(boom), payload, "get isolated session")+ }++ assertTrue(thrown.message!!.contains("get isolated session"))+ assertTrue(thrown.message!!.contains(payload))+ assertSame(boom, thrown.cause)+ }++ @Test+ fun `truncates oversized payloads to the configured limit`() {+ val oversized = "x".repeat(DECODE_FAILURE_PAYLOAD_LIMIT + 1000) + "TAIL-MARKER"+ val thrown =+ assertThrows<SandboxInternalException> {+ jsonParser.decodeResponseBody(FailingSerializer(IllegalStateException("no")), oversized, "op")+ }++ assertTrue(thrown.message!!.contains("x".repeat(DECODE_FAILURE_PAYLOAD_LIMIT)))+ assertTrue(!thrown.message!!.contains("TAIL-MARKER"))+ }+}diff --git a/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/ExecdEventSupportTest.kt b/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/ExecdEventSupportTest.ktindex 138838091..45542fbb5 100644--- a/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/ExecdEventSupportTest.kt+++ b/sdks/sandbox/kotlin/sandbox/src/test/kotlin/com/alibaba/opensandbox/sandbox/infrastructure/adapters/service/ExecdEventSupportTest.kt@@ -24,9 +24,10 @@ import org.junit.jupiter.api.Assertions.assertNotNullimport org.junit.jupiter.api.Assertions.assertNullimport org.junit.jupiter.api.Assertions.assertTrueimport org.junit.jupiter.api.Test+import org.junit.jupiter.api.assertThrowsclass ExecdEventSupportTest {- private val reported = mutableListOf<Pair<String, Exception>>()+ private val reported = mutableListOf<Pair<String, Throwable>>()private fun decode(line: String): com.alibaba.opensandbox.sandbox.api.models.execd.EventNode? =ExecdEventSupport.decodeEventLine(line) { line, error -> reported.add(line to error) }@@ -86,6 +87,28 @@ class ExecdEventSupportTest {assertTrue(reported[0].second is Exception)}+ @Test+ fun `reports linkage errors through onError and rethrows them`() {+ // Serializer/runtime version mismatches surface as AbstractMethodError,+ // an Error subtype that plain catch (Exception) blocks never see.+ val boom = AbstractMethodError("missing typeParametersSerializers()")+ val linkageReported = mutableListOf<Pair<String, Throwable>>()+ val rawLine = """data: {"type":"error","timestamp":1}"""++ val thrown =+ assertThrows<AbstractMethodError> {+ ExecdEventSupport.decodeEventLine(+ rawLine,+ decodePayload = { throw boom },+ ) { line, error -> linkageReported.add(line to error) }+ }++ assertEquals(boom, thrown)+ assertEquals(1, linkageReported.size)+ assertEquals(rawLine, linkageReported[0].first)+ assertEquals(boom, linkageReported[0].second)+ }+@Testfun `decodes payload lines the same way regardless of line endings`() {// Adapters feed reader.lineSequence() output: CRLF is already stripped.