Skip to content

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

perf(sdk-python): reuse SSL contexts across owned transports

贾岛1cd6928e027b
diff --git a/docs/sdks/python.md b/docs/sdks/python.md
index 942f6138e..238af19da 100644
--- a/docs/sdks/python.md
+++ b/docs/sdks/python.md
@@ -516,6 +516,8 @@ await sandbox.patch_metadata({"project": "demo", "obsolete-key": None})
The `ConnectionConfig` class manages API server connection settings.
+Reuse a `ConnectionConfig` (or `ConnectionConfigSync`) when creating multiple sandboxes. SDK-owned transports share that configuration's lazily loaded SSL context, avoiding repeated CA certificate loading, while each Sandbox/Manager keeps its own connection pool and closes it independently. TLS verification remains enabled. Create a new configuration to reload the system or environment-configured trust store. For connection pooling across sandboxes, supply a shared `transport` and close it after all users finish.
+
| Parameter | Description | Default | Environment Variable |
| ----------------- | ------------------------------------------ | ---------------------------- | ---------------------- |
| `api_key` | API Key for authentication | Optional; needed when server auth is enabled | `OPEN_SANDBOX_API_KEY` |
diff --git a/sdks/sandbox/python/src/opensandbox/config/connection.py b/sdks/sandbox/python/src/opensandbox/config/connection.py
index 7600c6367..91c7634a3 100644
--- a/sdks/sandbox/python/src/opensandbox/config/connection.py
+++ b/sdks/sandbox/python/src/opensandbox/config/connection.py
@@ -18,6 +18,7 @@ Connection configuration for OpenSandbox operations.
"""
import os
+import ssl
from datetime import timedelta
import httpx # type: ignore[reportMissingImports]
@@ -52,6 +53,7 @@ class ConnectionConfig(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
_owns_transport: bool = PrivateAttr(default=True)
+ _ssl_context: ssl.SSLContext | None = PrivateAttr(default=None)
api_key: str | None = Field(
default=None, description="API key for authentication with sandbox service"
@@ -171,7 +173,10 @@ class ConnectionConfig(BaseModel):
shared `transport` on this config is never touched. Callers that
close what they build (e.g. adapter clients) can do so safely.
"""
+ if self._ssl_context is None:
+ self._ssl_context = httpx.create_ssl_context()
inner = httpx.AsyncHTTPTransport(
+ verify=self._ssl_context,
limits=httpx.Limits(
max_connections=max_connections,
max_keepalive_connections=max_keepalive_connections,
diff --git a/sdks/sandbox/python/src/opensandbox/config/connection_sync.py b/sdks/sandbox/python/src/opensandbox/config/connection_sync.py
index fcd1d785a..97add5a14 100644
--- a/sdks/sandbox/python/src/opensandbox/config/connection_sync.py
+++ b/sdks/sandbox/python/src/opensandbox/config/connection_sync.py
@@ -20,6 +20,7 @@ This mirrors ConnectionConfig (async) but uses httpx sync transports.
"""
import os
+import ssl
from datetime import timedelta
import httpx
@@ -43,6 +44,7 @@ class ConnectionConfigSync(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
_owns_transport: bool = PrivateAttr(default=True)
+ _ssl_context: ssl.SSLContext | None = PrivateAttr(default=None)
api_key: str | None = Field(
default=None, description="API key for authentication with sandbox service"
@@ -158,7 +160,9 @@ class ConnectionConfigSync(BaseModel):
shared `transport` on this config is never touched. Callers that
close what they build (e.g. adapter clients) can do so safely.
"""
- ssl_context = httpx.create_ssl_context()
+ if self._ssl_context is None:
+ self._ssl_context = httpx.create_ssl_context()
+ ssl_context = self._ssl_context
inner = httpx.HTTPTransport(
verify=ssl_context,
limits=httpx.Limits(
diff --git a/sdks/sandbox/python/tests/test_connection_config.py b/sdks/sandbox/python/tests/test_connection_config.py
index b00c69801..2a1e1c3d8 100644
--- a/sdks/sandbox/python/tests/test_connection_config.py
+++ b/sdks/sandbox/python/tests/test_connection_config.py
@@ -13,6 +13,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+import ssl
+from unittest.mock import Mock
+
import httpx
import pytest
@@ -97,3 +100,58 @@ async def test_close_transport_if_owned_does_not_close_user_transport() -> None:
cfg = ConnectionConfig(transport=t)
await cfg.close_transport_if_owned()
assert t.closed is False
+
+
[email protected]("config_cls", [ConnectionConfig, ConnectionConfigSync])
+async def test_reuses_ssl_context_without_sharing_owned_transports(
+ config_cls: type[ConnectionConfig] | type[ConnectionConfigSync],
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ create_context = Mock(wraps=httpx.create_ssl_context)
+ transport_name = (
+ "AsyncHTTPTransport" if config_cls is ConnectionConfig else "HTTPTransport"
+ )
+ create_transport = Mock(wraps=getattr(httpx, transport_name))
+ monkeypatch.setattr(httpx, "create_ssl_context", create_context)
+ monkeypatch.setattr(httpx, transport_name, create_transport)
+ config = config_cls()
+ assert create_context.call_count == 0
+
+ first = config.with_transport_if_missing()
+ second = config.with_transport_if_missing()
+ try:
+ create_context.assert_called_once_with()
+ contexts = [call.kwargs["verify"] for call in create_transport.call_args_list]
+ assert contexts[0] is contexts[1]
+ assert contexts[0].verify_mode == ssl.CERT_REQUIRED
+ assert contexts[0].check_hostname
+ assert config.transport is None
+ assert first.transport is not second.transport
+ assert first.owns_transport and second.owns_transport
+ finally:
+ for resource in (first, second):
+ if isinstance(resource, ConnectionConfig):
+ await resource.close_transport_if_owned()
+ else:
+ resource.close_transport_if_owned()
+
+
[email protected]("config_cls", [ConnectionConfig, ConnectionConfigSync])
+async def test_new_config_reloads_environment_trust_store(
+ config_cls: type[ConnectionConfig] | type[ConnectionConfigSync],
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path,
+) -> None:
+ config = config_cls()
+ first = config.with_transport_if_missing()
+ monkeypatch.setenv("SSL_CERT_FILE", str(tmp_path / "missing-ca.pem"))
+ second = config.with_transport_if_missing()
+ try:
+ with pytest.raises(FileNotFoundError):
+ config_cls().with_transport_if_missing()
+ finally:
+ for resource in (first, second):
+ if isinstance(resource, ConnectionConfig):
+ await resource.close_transport_if_owned()
+ else:
+ resource.close_transport_if_owned()