Skip to content

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

fix(sdk-python): close wake timeout responses on cancellation

redyyang2233db64fddf
diff --git a/sdks/sandbox/python/src/opensandbox/transport/_async_retry.py b/sdks/sandbox/python/src/opensandbox/transport/_async_retry.py
index 9ddfb890e..9d8c8619b 100644
--- a/sdks/sandbox/python/src/opensandbox/transport/_async_retry.py
+++ b/sdks/sandbox/python/src/opensandbox/transport/_async_retry.py
@@ -241,17 +241,18 @@ class RetryAsyncTransport(httpx.AsyncBaseTransport):
try:
body = await response.aread()
except Exception:
- logger.debug(
- "failed to read wake-timeout body", exc_info=True
- )
+ logger.debug("failed to read wake-timeout body", exc_info=True)
+ finally:
+ # The response never reaches AsyncClient on this path,
+ # so close it even when the diagnostic read is cancelled.
+ try:
+ await response.aclose()
+ except Exception:
+ logger.debug(
+ "failed to close wake-timeout response",
+ exc_info=True,
+ )
request_id = response.headers.get("X-Request-ID")
- try:
- await response.aclose()
- except Exception:
- logger.debug(
- "failed to close wake-timeout response",
- exc_info=True,
- )
raise SandboxWakeTimeoutException(
"sandbox wake timeout: restore did not complete "
f"within the wake retry budget "
diff --git a/sdks/sandbox/python/tests/test_wake_retry_transport.py b/sdks/sandbox/python/tests/test_wake_retry_transport.py
index 27a56fb0c..e8b1d1759 100644
--- a/sdks/sandbox/python/tests/test_wake_retry_transport.py
+++ b/sdks/sandbox/python/tests/test_wake_retry_transport.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import asyncio
import random
from collections.abc import Callable
from dataclasses import replace
@@ -247,6 +248,40 @@ class TestSyncWakeRetry:
class TestAsyncWakeRetry:
+ @pytest.mark.asyncio
+ async def test_cancelled_exhaustion_body_read_closes_response(self) -> None:
+ started = asyncio.Event()
+
+ class PendingBody(httpx.AsyncByteStream):
+ closed = False
+
+ async def __aiter__(self):
+ started.set()
+ await asyncio.Event().wait()
+ yield b""
+
+ async def aclose(self) -> None:
+ self.closed = True
+
+ stream = PendingBody()
+ response = httpx.Response(
+ 503, headers={"OpenSandbox-Wake": "expired"}, stream=stream
+ )
+ inner = _ScriptAsync([response])
+ transport = RetryAsyncTransport(inner, _wake_policy(wake_max_attempts=1))
+ async with httpx.AsyncClient(
+ transport=transport, base_url="http://x"
+ ) as client:
+ task = asyncio.create_task(client.post("/", json={}))
+ await asyncio.wait_for(started.wait(), timeout=1)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert stream.closed
+ assert response.is_closed
+ assert inner.calls == 1
+
@pytest.mark.asyncio
async def test_post_retried_on_marked_503_then_success(self) -> None:
inner = _ScriptAsync([_wake_503(), httpx.Response(200, text="ok")])