Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

refactor(python-sdk): balance envd traffic across growable connection pools (#1825)

devin-ai-integration[bot]f7139140d34a
diff --git a/.changeset/shard-by-sandbox-id.md b/.changeset/shard-by-sandbox-id.md
new file mode 100644
index 000000000..bb3526dde
--- /dev/null
+++ b/.changeset/shard-by-sandbox-id.md
@@ -0,0 +1,5 @@
+---
+"@e2b/python-sdk": patch
+---
+
+Sandbox `commands`/`files` traffic is now balanced across HTTP/2 connections the way the JS SDK's undici agent does it, instead of being sharded into a fixed number of pools by sandbox ID. Every request goes to the connection with the fewest streams in flight to its host; a new connection is dialed only when all existing ones already carry `E2B_STREAMS_PER_CONNECTION` streams to that host (default `100`), up to `E2B_MAX_CONNECTIONS` (default `200`). Envd RPC and HTTP calls share the same connections. `E2B_ENVD_POOL_SHARDS` and the `pool_shard` argument of the internal transport factories (`get_transport`, `get_httpx_transport`, `get_pyqwest_transport`, `get_envd_transport`) are removed.
diff --git a/packages/python-sdk/README.md b/packages/python-sdk/README.md
index 6997acd54..c8a42764b 100644
--- a/packages/python-sdk/README.md
+++ b/packages/python-sdk/README.md
@@ -68,12 +68,12 @@ Per-call params still take precedence over the client's params, and clients are
### High-concurrency sandbox streams
-The Python SDK spreads sandbox `commands` and `files` traffic across four HTTP/2 connection pools by default. This prevents long-running streams in one process from all contending for a single connection's concurrent-stream limit.
+Sandbox `commands` and `files` traffic from all sandboxes in a process shares one set of HTTP/2 connections. Each request goes to the connection with the fewest streams in flight to its host, and a new connection is dialed only when every existing one already carries `E2B_STREAMS_PER_CONNECTION` streams to that host (default `100`, the usual server limit), up to `E2B_MAX_CONNECTIONS` (default `200`). Long-running streams therefore never queue behind one connection's concurrent-stream limit, and idle processes keep a single connection.
-If one process needs more capacity, set `E2B_ENVD_POOL_SHARDS` before importing `e2b`. Each additional shard can open another connection to the sandbox host, so increase it only as needed:
+Both variables are read when `e2b` is imported:
```sh
-E2B_ENVD_POOL_SHARDS=8 python eval.py
+E2B_STREAMS_PER_CONNECTION=50 E2B_MAX_CONNECTIONS=400 python eval.py
```
### 5. Code execution with Code Interpreter
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index 845658ccf..321bd5318 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -1,11 +1,22 @@
import json
import logging
import os
-import zlib
+import threading
from dataclasses import dataclass
from types import TracebackType
-from typing import NamedTuple, Optional, Protocol, Tuple, Union
-from urllib.parse import quote
+from typing import (
+ Callable,
+ Dict,
+ Generic,
+ List,
+ NamedTuple,
+ Optional,
+ Protocol,
+ Tuple,
+ TypeVar,
+ Union,
+)
+from urllib.parse import quote, urlsplit
import httpx
from httpx import AsyncBaseTransport, BaseTransport, Timeout
@@ -98,31 +109,81 @@ connection_retries = int(os.getenv("E2B_CONNECTION_RETRIES") or "3")
# Pool tuning for the pyqwest transports, shared by the REST API, envd RPC,
# and envd HTTP API stacks. `pool_max_idle_per_host` is per host rather than
# the global idle cap the httpx transports took, which suits both: API traffic
-# goes to a single host and each sandbox is its own host. `E2B_MAX_CONNECTIONS`
-# has no counterpart left — reqwest does not cap concurrent connections — so it
-# is no longer read.
+# goes to a single host and each sandbox is its own host.
pool_idle_timeout = float(os.getenv("E2B_KEEPALIVE_EXPIRY") or "300")
pool_max_idle_per_host = int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS") or "20")
-envd_pool_shards = max(1, int(os.getenv("E2B_ENVD_POOL_SHARDS") or "4"))
-
-
-def envd_pool_shard(config: ConnectionConfig) -> int:
- """Return the stable connection-pool shard for a sandbox's envd traffic.
- Production envd requests share one origin, whose HTTP/2 connection has a
- finite concurrent-stream limit. Long-running commands hold those streams,
- so one process-wide connection becomes a bottleneck even though the edge
- and account can run more sandboxes. A small bounded set of pools provides
- additional connections without returning to one connection per sandbox.
-
- The sandbox ID is carried on every envd request and CRC32 is stable across
- processes, unlike Python's randomized ``hash``. Configs without a sandbox
- ID (including control-plane clients) stay on shard zero.
- """
- sandbox_id = config.sandbox_headers.get("E2b-Sandbox-Id")
- if not sandbox_id:
- return 0
- return zlib.crc32(sandbox_id.encode()) % envd_pool_shards
+# A reqwest pool multiplexes every request to an origin over one HTTP/2
+# connection and queues past the server's concurrent-stream limit (envd's
+# edge, which all sandboxes share, advertises 100) rather than dialing another
+# — long-running commands hold those streams. So each cached transport is a
+# set of reqwest pools that grows on demand, like undici's
+# `Agent({ connections })` in the JS SDK: a request goes to the pool with the
+# fewest in flight to its origin, another pool is dialed once every one
+# carries `streams_per_connection` to that origin, up to `max_connections`
+# pools.
+streams_per_connection = max(1, int(os.getenv("E2B_STREAMS_PER_CONNECTION") or "100"))
+max_connections = max(1, int(os.getenv("E2B_MAX_CONNECTIONS") or "200"))
+
+T = TypeVar("T")
+
+
+def request_origin(url: str) -> str:
+ """The origin a request URL is served from — what a reqwest pool keeps
+ one HTTP/2 connection, and so one concurrent-stream budget, for."""
+ parts = urlsplit(url)
+ return f"{parts.scheme}://{parts.netloc}".lower()
+
+
+class PooledConnection(Generic[T]):
+ """One reqwest pool in a :class:`ConnectionBalancer` and the number of
+ requests in flight on it, per origin: the pool keeps a connection per
+ origin, so the streams of one never crowd out another's."""
+
+ __slots__ = ("transport", "active")
+
+ def __init__(self, transport: T) -> None:
+ self.transport = transport
+ self.active: Dict[str, int] = {}
+
+ def in_flight(self, origin: str) -> int:
+ return self.active.get(origin, 0)
+
+
+class ConnectionBalancer(Generic[T]):
+ """Least-loaded selection over a growable, bounded set of reqwest pools.
+
+ The policy shared by the sync and async balancing transports, which do the
+ I/O: :meth:`acquire` picks (or dials) a pool and counts the request on it,
+ :meth:`release` uncounts it once the response is consumed or closed.
+ Per-request state is a lock away from every thread and loop that shares
+ the transport; the lock is reentrant because a release can run from a
+ ``__del__`` at any point, including inside :meth:`acquire`."""
+
+ def __init__(self, build: Callable[[], T]) -> None:
+ self._build = build
+ self._lock = threading.RLock()
+ self.connections: List[PooledConnection[T]] = [PooledConnection(build())]
+
+ def acquire(self, origin: str) -> PooledConnection[T]:
+ with self._lock:
+ connection = min(self.connections, key=lambda c: c.in_flight(origin))
+ if (
+ connection.in_flight(origin) >= streams_per_connection
+ and len(self.connections) < max_connections
+ ):
+ connection = PooledConnection(self._build())
+ self.connections.append(connection)
+ connection.active[origin] = connection.in_flight(origin) + 1
+ return connection
+
+ def release(self, connection: PooledConnection[T], origin: str) -> None:
+ with self._lock:
+ remaining = connection.in_flight(origin) - 1
+ if remaining:
+ connection.active[origin] = remaining
+ else:
+ del connection.active[origin]
class ProxyConfig(NamedTuple):
diff --git a/packages/python-sdk/e2b/api/client_async/__init__.py b/packages/python-sdk/e2b/api/client_async/__init__.py
index c549e36d6..711ef14ee 100644
--- a/packages/python-sdk/e2b/api/client_async/__init__.py
+++ b/packages/python-sdk/e2b/api/client_async/__init__.py
@@ -1,22 +1,24 @@
import threading
-from typing import Dict, Optional, Tuple, Union
+from functools import partial
+from typing import AsyncIterator, Callable, Dict, Optional, Tuple, Union
import httpx
-from pyqwest import HTTPTransport, HTTPVersion, Request, Response
+from pyqwest import HTTPTransport, HTTPVersion, Request, Response, Transport
from pyqwest.httpx import AsyncPyqwestTransport
from pyqwest.middleware.retry import RetryMode, RetryTransport
from e2b.retry import AsyncRetryableTransport
from e2b.api import (
AsyncApiClient,
+ ConnectionBalancer,
ProxyConfig,
connection_retries,
- envd_pool_shard,
make_async_logging_event_hooks,
pool_idle_timeout,
pool_max_idle_per_host,
proxy_to_config,
+ request_origin,
)
from e2b.connection_config import READ_TIMEOUT, ConnectionConfig
@@ -54,24 +56,99 @@ class ConnectionRetryTransport(RetryTransport):
return isinstance(response, ConnectionError)
-_TransportKey = Tuple[Optional[ProxyConfig], Optional[float], bool, int]
-"""Cache key: proxy, idle read bound, HTTP version, connection-pool shard.
+_Chunk = Union[bytes, bytearray, memoryview]
-The first three are fixed when a pyqwest transport is constructed. The shard
-allows bounded parallel HTTP/2 connections to the stable envd host. Each
-distinct combination is necessarily its own pool."""
+
+class _TrackedContent:
+ """The content iterator of a balanced response: hands back the original
+ response's chunks and releases its connection slot exactly once, after
+ the stream is over — when the content is exhausted, when the response is
+ closed (``Response`` forwards ``aclose`` to its content), when reading
+ fails, or, failing all of those, when it is garbage collected, which
+ drops the original response and so resets its stream."""
+
+ __slots__ = ("_response", "_content", "_release")
+
+ def __init__(self, response: Response, release: Callable[[], None]) -> None:
+ self._response = response
+ self._content = response.content.__aiter__()
+ self._release: Optional[Callable[[], None]] = release
+
+ def __aiter__(self) -> AsyncIterator[_Chunk]:
+ return self
+
+ async def __anext__(self) -> _Chunk:
+ try:
+ return await self._content.__anext__()
+ except BaseException:
+ await self.aclose()
+ raise
+
+ async def aclose(self) -> None:
+ release, self._release = self._release, None
+ if release is None:
+ return
+ try:
+ await self._response.aclose()
+ finally:
+ release()
+
+ def __del__(self) -> None:
+ release, self._release = self._release, None
+ if release is None:
+ return
+ del self._content, self._response
+ release()
+
+
+class BalancingTransport(Transport):
+ """A pyqwest transport over a growable, bounded set of reqwest pools
+ (see :class:`e2b.api.ConnectionBalancer`): each request runs on the pool
+ with the fewest in flight to its origin and counts against it until its
+ response is consumed or closed. Pools are built with ``build`` — the first
+ eagerly, the rest as load requires — so they share every construction
+ knob."""
+
+ def __init__(self, build: Callable[[], HTTPTransport]) -> None:
+ self.balancer: ConnectionBalancer[HTTPTransport] = ConnectionBalancer(build)
+
+ async def execute(self, request: Request) -> Response:
+ origin = request_origin(request.url)
+ connection = self.balancer.acquire(origin)
+ try:
+ response = await connection.transport.execute(request)
+ except BaseException:
+ self.balancer.release(connection, origin)
+ raise
+ return Response(
+ status=response.status,
+ http_version=response.http_version,
+ headers=response.headers,
+ content=_TrackedContent(
+ response, partial(self.balancer.release, connection, origin)
+ ),
+ # Populated in place once the original content is consumed.
+ trailers=response.trailers,
+ )
+
+
+_TransportKey = Tuple[Optional[ProxyConfig], Optional[float], bool]
+"""Cache key: proxy, idle read bound, HTTP version — fixed when a pyqwest
+transport is constructed, so each distinct combination is necessarily its own
+transport."""
_transport_lock = threading.Lock()
-# One pyqwest transport — one reqwest connection pool — per key; a `None` proxy
-# is the direct pool. Generic API and volume traffic use shard zero. Envd RPC
-# and non-streaming HTTP traffic for one sandbox use the same sandbox shard, so
-# they share one HTTP/2 connection instead of opening one per stack.
+# One balancing transport — a set of reqwest connection pools — per key; a
+# `None` proxy is the direct transport. The REST API, envd RPC, envd HTTP API
+# and volume stacks all draw from the same one for their proxy, so a sandbox's
+# RPC and HTTP traffic multiplex over the same connections instead of opening
+# one per stack.
#
# pyqwest's I/O runs on its own Rust runtime, so unlike the httpx transports
# they replaced, the transports are not bound to an event loop and the caches
# are process-global rather than per-loop.
_transports: Dict[_TransportKey, ConnectionRetryTransport] = {}
-# The httpx adapter over each pool, shared by every httpx client on it.
+# The httpx adapter over each transport, shared by every httpx client on it.
_httpx_transports: Dict[_TransportKey, AsyncPyqwestTransport] = {}
@@ -79,19 +156,21 @@ def get_pyqwest_transport(
proxy: Optional[ProxyConfig],
read_timeout: Optional[float] = None,
http2: bool = True,
- pool_shard: int = 0,
) -> ConnectionRetryTransport:
- """The shared pyqwest transport (= one connection pool) with the SDK's
- tuning — system CA certs (without which TLS through an intercepting proxy
- fails) and the httpx-equivalent pool limits — behind connect-only retries.
+ """The shared pyqwest transport with the SDK's tuning — system CA certs
+ (without which TLS through an intercepting proxy fails) and the
+ httpx-equivalent pool limits — behind connect-only retries. It balances
+ requests over as many reqwest connection pools as the load needs (see
+ :class:`BalancingTransport`), so long-running streams do not all queue
+ behind one HTTP/2 connection's concurrent-stream limit.
Consumers speaking pyqwest natively (the envd RPC clients) take this;
consumers speaking httpx take :func:`get_httpx_transport`, the adapter over
- the very same pool. Layer concerns above it rather than into it — the RPC
- stack's plain-HTTP-error normalization wraps it, headers and codecs are
- per-request — so that the pool stays shareable.
+ the very same transport. Layer concerns above it rather than into it — the
+ RPC stack's plain-HTTP-error normalization wraps it, headers and codecs are
+ per-request — so that the pools stay shareable.
- ``read_timeout`` bounds every read on the pool's connections and ``http2``
+ ``read_timeout`` bounds every read on the pools' connections and ``http2``
fixes the HTTP version; both are part of the cache key because they are
transport-construction knobs, so one pool cannot serve two values of
either. reqwest's read timer keeps running while a request body is sent and
@@ -103,27 +182,29 @@ def get_pyqwest_transport(
``pyqwest`` loggers at ``DEBUG`` (off unless enabled) — the transport-level
diagnostics httpcore used to provide. The SDK's own ``logger`` option is
separate and sits above this, on the httpx client."""
- key = (proxy, read_timeout, http2, pool_shard)
+ key = (proxy, read_timeout, http2)
+
+ def build() -> HTTPTransport:
+ return HTTPTransport(
+ tls_include_system_certs=True,
+ proxy=proxy.to_pyqwest() if proxy is not None else None,
+ pool_idle_timeout=pool_idle_timeout,
+ pool_max_idle_per_host=pool_max_idle_per_host,
+ read_timeout=read_timeout,
+ # `None` leaves the version to ALPN on TLS connections (HTTP/2
+ # against the E2B API and envd) and uses HTTP/1 for plaintext,
+ # like the http2-enabled httpx transport this replaced.
+ http_version=None if http2 else HTTPVersion.HTTP1,
+ # Redirects belong to the httpx client above (which the generated
+ # clients leave off), not to reqwest.
+ follow_redirects=False,
+ )
+
with _transport_lock:
transport = _transports.get(key)
if transport is None:
transport = ConnectionRetryTransport(
- HTTPTransport(
- tls_include_system_certs=True,
- proxy=proxy.to_pyqwest() if proxy is not None else None,
- pool_idle_timeout=pool_idle_timeout,
- pool_max_idle_per_host=pool_max_idle_per_host,
- read_timeout=read_timeout,
- # `None` leaves the version to ALPN on TLS connections
- # (HTTP/2 against the E2B API and envd) and uses HTTP/1 for
- # plaintext, like the http2-enabled httpx transport this
- # replaced.
- http_version=None if http2 else HTTPVersion.HTTP1,
- # Redirects belong to the httpx client above (which the
- # generated clients leave off), not to reqwest.
- follow_redirects=False,
- ),
- max_retries=connection_retries,
+ BalancingTransport(build), max_retries=connection_retries
)
_transports[key] = transport
return transport
@@ -133,16 +214,15 @@ def get_httpx_transport(
proxy: Optional[ProxyConfig],
read_timeout: Optional[float] = None,
http2: bool = True,
- pool_shard: int = 0,
) -> AsyncPyqwestTransport:
- """The httpx adapter over the shared pool of
+ """The httpx adapter over the shared transport of
:func:`get_pyqwest_transport`, for the generated httpx clients (control
plane, envd HTTP API, volume content). The adapter holds no state of its
- own and does not close the pool, so closing an httpx client leaves the
- pool intact for the other clients on it."""
- key = (proxy, read_timeout, http2, pool_shard)
+ own and does not close the pools, so closing an httpx client leaves them
+ intact for the other clients on it."""
+ key = (proxy, read_timeout, http2)
# Resolve the pool before taking the lock: it takes the same one.
- pool = get_pyqwest_transport(proxy, read_timeout, http2, pool_shard)
+ pool = get_pyqwest_transport(proxy, read_timeout, http2)
with _transport_lock:
transport = _httpx_transports.get(key)
if transport is None:
@@ -156,13 +236,11 @@ def get_transport(
http2: bool = True,
*,
for_streaming: bool = False,
- pool_shard: int = 0,
) -> AsyncPyqwestTransport:
"""The shared httpx transport factory for the control-plane REST API and
- envd HTTP API (file transfers, health checks). Generic callers use shard
- zero; :func:`get_envd_transport` supplies a sandbox-specific shard. For TLS
- connections ALPN negotiates the HTTP version (HTTP/2 against the E2B API),
- like the http2-enabled httpx transport this replaced.
+ envd HTTP API (file transfers, health checks). For TLS connections ALPN
+ negotiates the HTTP version (HTTP/2 against the E2B API), like the
+ http2-enabled httpx transport this replaced.
``http2=False`` returns a separate transport (its own pool) pinned to
HTTP/1.1. That matters for a server that reacts to a client going away:
@@ -183,29 +261,6 @@ def get_transport(
proxy_to_config(config.proxy),
READ_TIMEOUT if for_streaming else None,
http2,
- pool_shard,
- )
-
-
-def get_envd_transport(
- config: ConnectionConfig, http2: bool = True, *, for_streaming: bool = False
-) -> AsyncPyqwestTransport:
- """The envd HTTP API's transport, sharded by sandbox ID.
-
- Envd RPC and non-streaming HTTP traffic for one sandbox resolve the same
- shard, retaining their shared connection while spreading different
- sandboxes over a bounded number of connections to the stable sandbox host.
- Streaming HTTP traffic uses the same shard number with a separate
- read-timeout-keyed pool.
-
- Kept as a separate factory because generic API transports stay on shard
- zero while envd transports use the sandbox's shard.
- """
- return get_transport(
- config,
- http2,
- for_streaming=for_streaming,
- pool_shard=envd_pool_shard(config),
)
@@ -218,7 +273,7 @@ def get_envd_api(
is shared and loop-independent."""
return httpx.AsyncClient(
base_url=base_url,
- transport=get_envd_transport(config, for_streaming=for_streaming),
+ transport=get_transport(config, for_streaming=for_streaming),
headers=config.sandbox_headers,
event_hooks=make_async_logging_event_hooks(config.logger),
)
diff --git a/packages/python-sdk/e2b/api/client_sync/__init__.py b/packages/python-sdk/e2b/api/client_sync/__init__.py
index 289c8bdfc..3bcce8b43 100644
--- a/packages/python-sdk/e2b/api/client_sync/__init__.py
+++ b/packages/python-sdk/e2b/api/client_sync/__init__.py
@@ -1,22 +1,30 @@
-from typing import Dict, Optional, Tuple, Union
+from functools import partial
+from typing import Callable, Dict, Iterator, Optional, Tuple, Union
import httpx
import threading
-from pyqwest import HTTPVersion, SyncHTTPTransport, SyncRequest, SyncResponse
+from pyqwest import (
+ HTTPVersion,
+ SyncHTTPTransport,
+ SyncRequest,
+ SyncResponse,
+ SyncTransport,
+)
from pyqwest.httpx import PyqwestTransport
from pyqwest.middleware.retry import RetryMode, SyncRetryTransport
from e2b.retry import RetryableTransport
from e2b.api import (
ApiClient,
+ ConnectionBalancer,
ProxyConfig,
connection_retries,
- envd_pool_shard,
make_logging_event_hooks,
pool_idle_timeout,
pool_max_idle_per_host,
proxy_to_config,
+ request_origin,
)
from e2b.connection_config import READ_TIMEOUT, ConnectionConfig
@@ -54,23 +62,98 @@ class ConnectionRetryTransport(SyncRetryTransport):
return isinstance(response, ConnectionError)
-_TransportKey = Tuple[Optional[ProxyConfig], Optional[float], bool, int]
-"""Cache key: proxy, idle read bound, HTTP version, connection-pool shard.
+_Chunk = Union[bytes, bytearray, memoryview]
+
+
+class _TrackedContent:
+ """The content iterator of a balanced response: hands back the original
+ response's chunks and releases its connection slot exactly once, after
+ the stream is over — when the content is exhausted, when the response is
+ closed (``SyncResponse`` forwards ``close`` to its content), when reading
+ fails, or, failing all of those, when it is garbage collected, which
+ drops the original response and so resets its stream."""
+
+ __slots__ = ("_response", "_content", "_release")
+
+ def __init__(self, response: SyncResponse, release: Callable[[], None]) -> None:
+ self._response = response
+ self._content = iter(response.content)
+ self._release: Optional[Callable[[], None]] = release
+
+ def __iter__(self) -> Iterator[_Chunk]:
+ return self
+
+ def __next__(self) -> _Chunk:
+ try:
+ return next(self._content)
+ except BaseException:
+ self.close()
+ raise
+
+ def close(self) -> None:
+ release, self._release = self._release, None
+ if release is None:
+ return
+ try:
+ self._response.close()
+ finally:
+ release()
+
+ def __del__(self) -> None:
+ release, self._release = self._release, None
+ if release is None:
+ return
+ del self._content, self._response
+ release()
+
+
+class BalancingTransport(SyncTransport):
+ """A pyqwest transport over a growable, bounded set of reqwest pools
+ (see :class:`e2b.api.ConnectionBalancer`): each request runs on the pool
+ with the fewest in flight to its origin and counts against it until its
+ response is consumed or closed. Pools are built with ``build`` — the first
+ eagerly, the rest as load requires — so they share every construction
+ knob."""
+
+ def __init__(self, build: Callable[[], SyncHTTPTransport]) -> None:
+ self.balancer: ConnectionBalancer[SyncHTTPTransport] = ConnectionBalancer(build)
+
+ def execute_sync(self, request: SyncRequest) -> SyncResponse:
+ origin = request_origin(request.url)
+ connection = self.balancer.acquire(origin)
+ try:
+ response = connection.transport.execute_sync(request)
+ except BaseException:
+ self.balancer.release(connection, origin)
+ raise
+ return SyncResponse(
+ status=response.status,
+ http_version=response.http_version,
+ headers=response.headers,
+ content=_TrackedContent(
+ response, partial(self.balancer.release, connection, origin)
+ ),
+ # Populated in place once the original content is consumed.
+ trailers=response.trailers,
+ )
-The first three are fixed when a pyqwest transport is constructed. The shard
-allows bounded parallel HTTP/2 connections to the stable envd host. Each
-distinct combination is necessarily its own pool."""
+
+_TransportKey = Tuple[Optional[ProxyConfig], Optional[float], bool]
+"""Cache key: proxy, idle read bound, HTTP version — fixed when a pyqwest
+transport is constructed, so each distinct combination is necessarily its own
+transport."""
_transport_lock = threading.Lock()
-# One pyqwest transport — one reqwest connection pool — per key; a `None` proxy
-# is the direct pool. Generic API and volume traffic use shard zero. Envd RPC
-# and non-streaming HTTP traffic for one sandbox use the same sandbox shard, so
-# they share one HTTP/2 connection instead of opening one per stack.
+# One balancing transport — a set of reqwest connection pools — per key; a
+# `None` proxy is the direct transport. The REST API, envd RPC, envd HTTP API
+# and volume stacks all draw from the same one for their proxy, so a sandbox's
+# RPC and HTTP traffic multiplex over the same connections instead of opening
+# one per stack.
#
# pyqwest transports are thread-safe, so unlike the httpx transports they
# replaced, the caches are process-global rather than per-thread.
_transports: Dict[_TransportKey, ConnectionRetryTransport] = {}
-# The httpx adapter over each pool, shared by every httpx client on it.
+# The httpx adapter over each transport, shared by every httpx client on it.
_httpx_transports: Dict[_TransportKey, PyqwestTransport] = {}
@@ -78,19 +161,21 @@ def get_pyqwest_transport(
proxy: Optional[ProxyConfig],
read_timeout: Optional[float] = None,
http2: bool = True,
- pool_shard: int = 0,
) -> ConnectionRetryTransport:
- """The shared pyqwest transport (= one connection pool) with the SDK's
- tuning — system CA certs (without which TLS through an intercepting proxy
- fails) and the httpx-equivalent pool limits — behind connect-only retries.
+ """The shared pyqwest transport with the SDK's tuning — system CA certs
+ (without which TLS through an intercepting proxy fails) and the
+ httpx-equivalent pool limits — behind connect-only retries. It balances
+ requests over as many reqwest connection pools as the load needs (see
+ :class:`BalancingTransport`), so long-running streams do not all queue
+ behind one HTTP/2 connection's concurrent-stream limit.
Consumers speaking pyqwest natively (the envd RPC clients) take this;
consumers speaking httpx take :func:`get_httpx_transport`, the adapter over
- the very same pool. Layer concerns above it rather than into it — the RPC
- stack's plain-HTTP-error normalization wraps it, headers and codecs are
- per-request — so that the pool stays shareable.
+ the very same transport. Layer concerns above it rather than into it — the
+ RPC stack's plain-HTTP-error normalization wraps it, headers and codecs are
+ per-request — so that the pools stay shareable.
- ``read_timeout`` bounds every read on the pool's connections and ``http2``
+ ``read_timeout`` bounds every read on the pools' connections and ``http2``
fixes the HTTP version; both are part of the cache key because they are
transport-construction knobs, so one pool cannot serve two values of
either. reqwest's read timer keeps running while a request body is sent and
@@ -102,27 +187,29 @@ def get_pyqwest_transport(
``pyqwest`` loggers at ``DEBUG`` (off unless enabled) — the transport-level
diagnostics httpcore used to provide. The SDK's own ``logger`` option is
separate and sits above this, on the httpx client."""
- key = (proxy, read_timeout, http2, pool_shard)
+ key = (proxy, read_timeout, http2)
+
+ def build() -> SyncHTTPTransport:
+ return SyncHTTPTransport(
+ tls_include_system_certs=True,
+ proxy=proxy.to_pyqwest() if proxy is not None else None,
+ pool_idle_timeout=pool_idle_timeout,
+ pool_max_idle_per_host=pool_max_idle_per_host,
+ read_timeout=read_timeout,
+ # `None` leaves the version to ALPN on TLS connections (HTTP/2
+ # against the E2B API and envd) and uses HTTP/1 for plaintext,
+ # like the http2-enabled httpx transport this replaced.
+ http_version=None if http2 else HTTPVersion.HTTP1,
+ # Redirects belong to the httpx client above (which the generated
+ # clients leave off), not to reqwest.
+ follow_redirects=False,
+ )
+
with _transport_lock:
transport = _transports.get(key)
if transport is None:
transport = ConnectionRetryTransport(
- SyncHTTPTransport(
- tls_include_system_certs=True,
- proxy=proxy.to_pyqwest() if proxy is not None else None,
- pool_idle_timeout=pool_idle_timeout,
- pool_max_idle_per_host=pool_max_idle_per_host,
- read_timeout=read_timeout,
- # `None` leaves the version to ALPN on TLS connections
- # (HTTP/2 against the E2B API and envd) and uses HTTP/1 for
- # plaintext, like the http2-enabled httpx transport this
- # replaced.
- http_version=None if http2 else HTTPVersion.HTTP1,
- # Redirects belong to the httpx client above (which the
- # generated clients leave off), not to reqwest.
- follow_redirects=False,
- ),
- max_retries=connection_retries,
+ BalancingTransport(build), max_retries=connection_retries
)
_transports[key] = transport
return transport
@@ -132,16 +219,15 @@ def get_httpx_transport(
proxy: Optional[ProxyConfig],
read_timeout: Optional[float] = None,
http2: bool = True,
- pool_shard: int = 0,
) -> PyqwestTransport:
- """The httpx adapter over the shared pool of
+ """The httpx adapter over the shared transport of
:func:`get_pyqwest_transport`, for the generated httpx clients (control
plane, envd HTTP API, volume content). The adapter holds no state of its
- own and does not close the pool, so closing an httpx client leaves the
- pool intact for the other clients on it."""
- key = (proxy, read_timeout, http2, pool_shard)
+ own and does not close the pools, so closing an httpx client leaves them
+ intact for the other clients on it."""
+ key = (proxy, read_timeout, http2)
# Resolve the pool before taking the lock: it takes the same one.
- pool = get_pyqwest_transport(proxy, read_timeout, http2, pool_shard)
+ pool = get_pyqwest_transport(proxy, read_timeout, http2)
with _transport_lock:
transport = _httpx_transports.get(key)
if transport is None:
@@ -155,13 +241,11 @@ def get_transport(
http2: bool = True,
*,
for_streaming: bool = False,
- pool_shard: int = 0,
) -> PyqwestTransport:
"""The shared httpx transport factory for the control-plane REST API and
- envd HTTP API (file transfers, health checks). Generic callers use shard
- zero; :func:`get_envd_transport` supplies a sandbox-specific shard. For TLS
- connections ALPN negotiates the HTTP version (HTTP/2 against the E2B API),
- like the http2-enabled httpx transport this replaced.
+ envd HTTP API (file transfers, health checks). For TLS connections ALPN
+ negotiates the HTTP version (HTTP/2 against the E2B API), like the
+ http2-enabled httpx transport this replaced.
``http2=False`` returns a separate transport (its own pool) pinned to
HTTP/1.1. That matters for a server that reacts to a client going away:
@@ -182,29 +266,6 @@ def get_transport(
proxy_to_config(config.proxy),
READ_TIMEOUT if for_streaming else None,
http2,
- pool_shard,
- )
-
-
-def get_envd_transport(
- config: ConnectionConfig, http2: bool = True, *, for_streaming: bool = False
-) -> PyqwestTransport:
- """The envd HTTP API's transport, sharded by sandbox ID.
-
- Envd RPC and non-streaming HTTP traffic for one sandbox resolve the same
- shard, retaining their shared connection while spreading different
- sandboxes over a bounded number of connections to the stable sandbox host.
- Streaming HTTP traffic uses the same shard number with a separate
- read-timeout-keyed pool.
-
- Kept as a separate factory because generic API transports stay on shard
- zero while envd transports use the sandbox's shard.
- """
- return get_transport(
- config,
- http2,
- for_streaming=for_streaming,
- pool_shard=envd_pool_shard(config),
)
@@ -217,7 +278,7 @@ def get_envd_api(
is shared and thread-safe."""
return httpx.Client(
base_url=base_url,
- transport=get_envd_transport(config, for_streaming=for_streaming),
+ transport=get_transport(config, for_streaming=for_streaming),
headers=config.sandbox_headers,
event_hooks=make_logging_event_hooks(config.logger),
)
diff --git a/packages/python-sdk/e2b/envd/client_async/__init__.py b/packages/python-sdk/e2b/envd/client_async/__init__.py
index f3827cc76..dcc979d73 100644
--- a/packages/python-sdk/e2b/envd/client_async/__init__.py
+++ b/packages/python-sdk/e2b/envd/client_async/__init__.py
@@ -15,7 +15,7 @@ from connectrpc.code import Code
from connectrpc.errors import ConnectError
from pyqwest import Client, Request, Response, Transport
-from e2b.api import envd_pool_shard, proxy_to_config
+from e2b.api import proxy_to_config
from e2b.api.client_async import get_pyqwest_transport
from e2b.connection_config import ConnectionConfig
from e2b.envd.client_shared import (
@@ -80,12 +80,7 @@ def create_rpc_client(
outside the retries so it converts the settled response once.
"""
http_client = Client(
- PlainHTTPErrorTransport(
- get_pyqwest_transport(
- proxy_to_config(config.proxy),
- pool_shard=envd_pool_shard(config),
- )
- )
+ PlainHTTPErrorTransport(get_pyqwest_transport(proxy_to_config(config.proxy)))
)
return client_cls(
base_url,
diff --git a/packages/python-sdk/e2b/envd/client_sync/__init__.py b/packages/python-sdk/e2b/envd/client_sync/__init__.py
index dfbdde4ee..fadf66323 100644
--- a/packages/python-sdk/e2b/envd/client_sync/__init__.py
+++ b/packages/python-sdk/e2b/envd/client_sync/__init__.py
@@ -9,7 +9,7 @@ from pyqwest import (
SyncTransport,
)
-from e2b.api import envd_pool_shard, proxy_to_config
+from e2b.api import proxy_to_config
from e2b.api.client_sync import get_pyqwest_transport
from e2b.connection_config import ConnectionConfig
from e2b.envd.client_shared import (
@@ -75,12 +75,7 @@ def create_rpc_client(
outside the retries so it converts the settled response once.
"""
http_client = SyncClient(
- PlainHTTPErrorTransport(
- get_pyqwest_transport(
- proxy_to_config(config.proxy),
- pool_shard=envd_pool_shard(config),
- )
- )
+ PlainHTTPErrorTransport(get_pyqwest_transport(proxy_to_config(config.proxy)))
)
return client_cls(
base_url,
diff --git a/packages/python-sdk/tests/test_api_client_transport.py b/packages/python-sdk/tests/test_api_client_transport.py
index f7ac9d523..ab73da39d 100644
--- a/packages/python-sdk/tests/test_api_client_transport.py
+++ b/packages/python-sdk/tests/test_api_client_transport.py
@@ -1,5 +1,6 @@
import asyncio
import base64
+import gc
import json
import logging
import threading
@@ -9,7 +10,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import httpx
import pytest
-from pyqwest import HTTPVersion, Request, SyncRequest
+from pyqwest import Headers, HTTPVersion, Request, Response, SyncRequest, SyncResponse
from pyqwest.httpx import AsyncPyqwestTransport, PyqwestTransport
from transport_caches import reset_transport_caches
@@ -18,53 +19,110 @@ import e2b.api.client_async as api_client_async
import e2b.api.client_sync as api_client_sync
from e2b.retry import AsyncRetryableTransport, RetryableTransport
from e2b.api import (
- envd_pool_shard,
+ ConnectionBalancer,
pool_idle_timeout,
pool_max_idle_per_host,
proxy_to_config,
)
from e2b.api.client_async import get_api_client as get_async_api_client
from e2b.api.client_async import get_envd_api as get_async_envd_api
-from e2b.api.client_async import get_envd_transport as get_async_envd_transport
from e2b.api.client_async import (
get_pyqwest_transport as get_async_pyqwest_transport,
)
from e2b.api.client_async import get_transport as get_async_transport
from e2b.api.client_sync import get_api_client as get_sync_api_client
from e2b.api.client_sync import get_envd_api as get_sync_envd_api
-from e2b.api.client_sync import get_envd_transport as get_sync_envd_transport
from e2b.api.client_sync import get_pyqwest_transport as get_sync_pyqwest_transport
from e2b.api.client_sync import get_transport as get_sync_transport
from e2b.connection_config import READ_TIMEOUT, ConnectionConfig
+# Origins the balancer counts streams for: production envd traffic to every
+# sandbox shares one, the REST API is another.
+ENVD = "https://sandbox.e2b.app"
+API = "https://api.e2b.app"
+ENVD_HEALTH = "http://envd"
+
def run_in_worker_thread(fn):
with ThreadPoolExecutor(max_workers=1) as executor:
return executor.submit(fn).result()
-def sandbox_config(test_api_key: str, sandbox_id: str) -> ConnectionConfig:
- return ConnectionConfig(
- api_key=test_api_key,
- extra_sandbox_headers={
- "E2b-Sandbox-Id": sandbox_id,
- "E2b-Sandbox-Port": "49983",
- },
- )
-
-
[email protected]("pool_shards", [1, 4, 8])
-def test_envd_pool_shard_respects_configured_count(
- test_api_key, monkeypatch, pool_shards
+def test_balancer_builds_the_first_pool_eagerly_and_the_rest_on_demand(
+ monkeypatch,
):
- monkeypatch.setattr(api, "envd_pool_shards", pool_shards)
-
- assigned = {
- envd_pool_shard(sandbox_config(test_api_key, f"sbx-{index}"))
- for index in range(100)
- }
-
- assert assigned == set(range(pool_shards))
+ monkeypatch.setattr(api, "streams_per_connection", 2)
+ monkeypatch.setattr(api, "max_connections", 3)
+ built = []
+
+ def build():
+ built.append(object())
+ return built[-1]
+
+ balancer = ConnectionBalancer(build)
+ assert len(built) == 1
+
+ # The first pool takes requests up to its stream limit before a second
+ # one is dialed; each new pool is then the least loaded and fills up in
+ # turn, until the cap, after which the least-loaded pool absorbs the rest.
+ connections = [balancer.acquire(ENVD) for _ in range(7)]
+ assert [built.index(c.transport) for c in connections] == [0, 0, 1, 1, 2, 2, 0]
+ assert len(built) == 3
+ assert [c.in_flight(ENVD) for c in balancer.connections] == [3, 2, 2]
+
+ # Releasing frees the slot; new requests prefer the pool with the fewest
+ # in flight rather than the first one that has room.
+ for connection in connections[2:4]:
+ balancer.release(connection, ENVD)
+ assert [c.in_flight(ENVD) for c in balancer.connections] == [3, 0, 2]
+ assert balancer.acquire(ENVD).transport is built[1]
+
+
+def test_balancer_counts_streams_per_origin(monkeypatch):
+ """A pool holds one HTTP/2 connection per origin, so the stream limit is
+ per origin too: traffic to other hosts — the REST API, or each sandbox's
+ own host on a custom domain — neither fills a pool nor dials one."""
+ monkeypatch.setattr(api, "streams_per_connection", 2)
+ monkeypatch.setattr(api, "max_connections", 3)
+ balancer = ConnectionBalancer(object)
+
+ hosts = [f"https://49983-sbx-{index}.e2b-foo.dev" for index in range(5)]
+ for host in hosts:
+ balancer.acquire(host)
+ balancer.acquire(API)
+ balancer.acquire(API)
+ assert len(balancer.connections) == 1
+ assert balancer.connections[0].active == {**dict.fromkeys(hosts, 1), API: 2}
+
+ # The third request to one origin dials, and lands on the new pool.
+ first, second = balancer.acquire(ENVD), balancer.acquire(ENVD)
+ third = balancer.acquire(ENVD)
+ assert len(balancer.connections) == 2
+ assert third is balancer.connections[1]
+ assert third.in_flight(ENVD) == 1
+
+ # The new pool is least loaded for every origin, so it takes the next
+ # request to any of them without dialing again.
+ assert balancer.acquire(API) is third
+ assert len(balancer.connections) == 2
+
+ # Origins with nothing in flight are dropped, so the count does not grow
+ # with every sandbox a process has ever spoken to.
+ balancer.release(first, ENVD)
+ balancer.release(second, ENVD)
+ assert ENVD not in balancer.connections[0].active
+
+
+def test_balancer_never_exceeds_the_connection_cap(monkeypatch):
+ monkeypatch.setattr(api, "streams_per_connection", 1)
+ monkeypatch.setattr(api, "max_connections", 1)
+ balancer = ConnectionBalancer(object)
+
+ connections = [balancer.acquire(ENVD) for _ in range(5)]
+
+ assert len(balancer.connections) == 1
+ assert {c.transport for c in connections} == {balancer.connections[0].transport}
+ assert balancer.connections[0].in_flight(ENVD) == 5
def test_sync_api_client_proxy_uses_explicit_transport(test_api_key):
@@ -154,51 +212,22 @@ def test_sync_transports_keyed_by_http_version(test_api_key):
try:
negotiated = get_sync_transport(config)
http1 = get_sync_transport(config, http2=False)
- envd_negotiated = get_sync_envd_transport(config)
- envd_http1 = get_sync_envd_transport(config, http2=False)
assert http1 is not negotiated
- assert envd_http1 is not envd_negotiated
- # A config without sandbox headers resolves envd to shard zero, so it
- # shares the generic transport for each HTTP version.
- assert envd_negotiated is negotiated
- assert envd_http1 is http1
- # Each version still has one pool per proxy, and repeat calls with the
- # same arguments reuse it.
+ # Each version still has one transport per proxy, and repeat calls
+ # with the same arguments reuse it.
assert get_sync_transport(proxied_config, http2=False) not in (
http1,
negotiated,
)
assert get_sync_transport(config, http2=False) is http1
assert get_sync_transport(config) is negotiated
- assert get_sync_envd_transport(config, http2=False) is envd_http1
- assert (
- get_sync_envd_transport(config, http2=False, for_streaming=True)
- is not envd_http1
- )
- finally:
- reset_transport_caches()
-
-
-def test_sync_envd_transports_are_consistently_sharded_by_sandbox(
- test_api_key, monkeypatch
-):
- monkeypatch.setattr(api, "envd_pool_shards", 4)
- reset_transport_caches()
- first = sandbox_config(test_api_key, "sbx-0")
- same_shard = sandbox_config(test_api_key, "sbx-2")
- different_shard = sandbox_config(test_api_key, "sbx-1")
-
- try:
- assert envd_pool_shard(first) == envd_pool_shard(same_shard)
- assert envd_pool_shard(first) != envd_pool_shard(different_shard)
- assert get_sync_envd_transport(first) is get_sync_envd_transport(same_shard)
- assert get_sync_envd_transport(first) is not get_sync_envd_transport(
- different_shard
- )
- # Generic API traffic remains on shard zero rather than multiplying
- # control-plane connections for every envd shard.
- assert get_sync_envd_transport(first) is not get_sync_transport(first)
+ assert get_sync_transport(config, http2=False, for_streaming=True) is not http1
+ # The envd RPC clients' pyqwest transport is the one under the httpx
+ # adapter the envd HTTP API uses, so a sandbox's RPC and HTTP traffic
+ # share connections.
+ assert get_sync_pyqwest_transport(None) is negotiated._transport
+ assert get_sync_pyqwest_transport(None, http2=False) is http1._transport
finally:
reset_transport_caches()
@@ -223,9 +252,7 @@ def test_sync_transports_pass_http_version_to_pyqwest(test_api_key, monkeypatch)
get_sync_transport(config)
get_sync_transport(config, http2=False)
# A third pool: same version as the call above, different idle bound.
- # (`get_envd_transport(config, http2=False)` would be a cache hit and
- # build nothing, since it shares the control plane's pool.)
- get_sync_envd_transport(config, http2=False, for_streaming=True)
+ get_sync_transport(config, http2=False, for_streaming=True)
assert captured == [None, HTTPVersion.HTTP1, HTTPVersion.HTTP1]
finally:
@@ -398,42 +425,13 @@ async def test_async_transports_keyed_by_http_version(test_api_key):
try:
negotiated = get_async_transport(config)
http1 = get_async_transport(config, http2=False)
- envd_negotiated = get_async_envd_transport(config)
- envd_http1 = get_async_envd_transport(config, http2=False)
assert http1 is not negotiated
- assert envd_http1 is not envd_negotiated
- # A config without sandbox headers resolves envd to shard zero, so it
- # shares the generic transport for each HTTP version.
- assert envd_negotiated is negotiated
- assert envd_http1 is http1
assert get_async_transport(config, http2=False) is http1
assert get_async_transport(config) is negotiated
- assert get_async_envd_transport(config, http2=False) is envd_http1
- assert (
- get_async_envd_transport(config, http2=False, for_streaming=True)
- is not envd_http1
- )
- finally:
- reset_transport_caches()
-
-
-async def test_async_envd_transports_are_consistently_sharded_by_sandbox(
- test_api_key, monkeypatch
-):
- monkeypatch.setattr(api, "envd_pool_shards", 4)
- reset_transport_caches()
- first = sandbox_config(test_api_key, "sbx-0")
- same_shard = sandbox_config(test_api_key, "sbx-2")
- different_shard = sandbox_config(test_api_key, "sbx-1")
-
- try:
- assert get_async_envd_transport(first) is get_async_envd_transport(same_shard)
- assert get_async_envd_transport(first) is not get_async_envd_transport(
- different_shard
- )
- assert get_async_envd_transport(first) is not get_async_transport(first)
+ assert get_async_transport(config, http2=False, for_streaming=True) is not http1
+ assert get_async_pyqwest_transport(None) is negotiated._transport
+ assert get_async_pyqwest_transport(None, http2=False) is http1._transport
finally:
reset_transport_caches()
@@ -455,7 +453,7 @@ async def test_async_transports_pass_http_version_to_pyqwest(test_api_key, monke
get_async_transport(config)
get_async_transport(config, http2=False)
# A third pool: same version as the call above, different idle bound.
- get_async_envd_transport(config, http2=False, for_streaming=True)
+ get_async_transport(config, http2=False, for_streaming=True)
assert captured == [None, HTTPVersion.HTTP1, HTTPVersion.HTTP1]
finally:
@@ -1084,3 +1082,217 @@ async def test_async_closing_one_client_leaves_the_shared_pool_open(
finally:
await envd_api.aclose()
reset_transport_caches()
+
+
+class FakeSyncPool:
+ """A stand-in reqwest pool: serves a canned streamed response and records
+ whether pyqwest's response was closed, so the balancing transport's
+ accounting can be checked without a server."""
+
+ def __init__(self, chunks=(b"a", b"b"), error=None):
+ self.chunks = chunks
+ self.error = error
+ self.closed = 0
+ self.trailers = Headers()
+
+ def execute_sync(self, request):
+ if self.error is not None:
+ raise self.error
+ return SyncResponse(
+ status=200,
+ headers=Headers([("content-type", "text/plain")]),
+ content=self._content(),
+ trailers=self.trailers,
+ )
+
+ def _content(self):
+ try:
+ for chunk in self.chunks:
+ yield chunk
+ self.trailers.add("grpc-status", "0")
+ finally:
+ self.closed += 1
+
+
+def sync_balancing_transport(pool):
+ transport = api_client_sync.BalancingTransport(lambda: pool)
+ return transport, transport.balancer.connections[0]
+
+
+def record_closed_at_release(transport, pool):
+ """How many times the pool had closed its response when each release
+ came in: a slot must not read as free while its stream is still open."""
+ closed_at_release = []
+ release = transport.balancer.release
+
+ def recording_release(connection, origin):
+ closed_at_release.append(pool.closed)
+ release(connection, origin)
+
+ transport.balancer.release = recording_release
+ return closed_at_release
+
+
+def test_sync_balancing_transport_counts_a_request_until_its_content_is_consumed():
+ pool = FakeSyncPool()
+ transport, connection = sync_balancing_transport(pool)
+
+ response = transport.execute_sync(SyncRequest("GET", ENVD_HEALTH + "/health"))
+
+ assert response.status == 200
+ assert response.headers.get("content-type") == "text/plain"
+ assert connection.in_flight(ENVD_HEALTH) == 1
+ assert next(response.content) == b"a"
+ assert connection.in_flight(ENVD_HEALTH) == 1
+ assert list(response.content) == [b"b"]
+ # Trailers are read off the original response after its content, as the
+ # RPC clients do, and the slot is freed exactly once.
+ assert response.trailers.get("grpc-status") == "0"
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert pool.closed == 1
+ response.close()
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert pool.closed == 1
+
+
+def test_sync_balancing_transport_frees_the_slot_when_the_response_is_closed():
+ pool = FakeSyncPool()
+ transport, connection = sync_balancing_transport(pool)
+
+ closed_at_release = record_closed_at_release(transport, pool)
+
+ response = transport.execute_sync(SyncRequest("GET", ENVD_HEALTH + "/health"))
+ assert next(response.content) == b"a"
+ assert connection.in_flight(ENVD_HEALTH) == 1
+
+ response.close()
+
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert pool.closed == 1
+ assert closed_at_release == [1]
+ response.close()
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert closed_at_release == [1]
+
+
+def test_sync_balancing_transport_frees_the_slot_when_the_request_fails():
+ pool = FakeSyncPool(error=ConnectionError("refused"))
+ transport, connection = sync_balancing_transport(pool)
+
+ with pytest.raises(ConnectionError):
+ transport.execute_sync(SyncRequest("GET", ENVD_HEALTH + "/health"))
+
+ assert connection.in_flight(ENVD_HEALTH) == 0
+
+
+def test_sync_balancing_transport_frees_the_slot_when_the_response_is_dropped():
+ pool = FakeSyncPool()
+ transport, connection = sync_balancing_transport(pool)
+
+ closed_at_release = record_closed_at_release(transport, pool)
+
+ response = transport.execute_sync(SyncRequest("GET", ENVD_HEALTH + "/health"))
+ assert next(response.content) == b"a"
+ del response
+ gc.collect()
+
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert pool.closed == 1
+ assert closed_at_release == [1]
+
+
+class FakeAsyncPool:
+ def __init__(self, chunks=(b"a", b"b"), error=None):
+ self.chunks = chunks
+ self.error = error
+ self.closed = 0
+ self.trailers = Headers()
+
+ async def execute(self, request):
+ if self.error is not None:
+ raise self.error
+ return Response(
+ status=200,
+ headers=Headers([("content-type", "text/plain")]),
+ content=self._content(),
+ trailers=self.trailers,
+ )
+
+ async def _content(self):
+ try:
+ for chunk in self.chunks:
+ yield chunk
+ self.trailers.add("grpc-status", "0")
+ finally:
+ self.closed += 1
+
+
+def async_balancing_transport(pool):
+ transport = api_client_async.BalancingTransport(lambda: pool)
+ return transport, transport.balancer.connections[0]
+
+
+async def test_async_balancing_transport_counts_a_request_until_its_content_is_consumed():
+ pool = FakeAsyncPool()
+ transport, connection = async_balancing_transport(pool)
+
+ response = await transport.execute(Request("GET", ENVD_HEALTH + "/health"))
+
+ assert response.status == 200
+ assert response.headers.get("content-type") == "text/plain"
+ assert connection.in_flight(ENVD_HEALTH) == 1
+ assert await response.content.__anext__() == b"a"
+ assert connection.in_flight(ENVD_HEALTH) == 1
+ assert [chunk async for chunk in response.content] == [b"b"]
+ assert response.trailers.get("grpc-status") == "0"
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert pool.closed == 1
+ await response.aclose()
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert pool.closed == 1
+
+
+async def test_async_balancing_transport_frees_the_slot_when_the_response_is_closed():
+ pool = FakeAsyncPool()
+ transport, connection = async_balancing_transport(pool)
+
+ closed_at_release = record_closed_at_release(transport, pool)
+
+ response = await transport.execute(Request("GET", ENVD_HEALTH + "/health"))
+ assert await response.content.__anext__() == b"a"
+ assert connection.in_flight(ENVD_HEALTH) == 1
+
+ await response.aclose()
+
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert pool.closed == 1
+ assert closed_at_release == [1]
+ await response.aclose()
+ assert connection.in_flight(ENVD_HEALTH) == 0
+ assert closed_at_release == [1]
+
+
+async def test_async_balancing_transport_frees_the_slot_when_the_request_fails():
+ pool = FakeAsyncPool(error=ConnectionError("refused"))
+ transport, connection = async_balancing_transport(pool)
+
+ with pytest.raises(ConnectionError):
+ await transport.execute(Request("GET", ENVD_HEALTH + "/health"))
+
+ assert connection.in_flight(ENVD_HEALTH) == 0
+
+
+async def test_async_balancing_transport_frees_the_slot_when_the_response_is_dropped():
+ pool = FakeAsyncPool()
+ transport, connection = async_balancing_transport(pool)
+
+ response = await transport.execute(Request("GET", ENVD_HEALTH + "/health"))
+ assert await response.content.__anext__() == b"a"
+ del response
+ gc.collect()
+
+ assert connection.in_flight(ENVD_HEALTH) == 0
diff --git a/packages/python-sdk/tests/test_env_var_parsing.py b/packages/python-sdk/tests/test_env_var_parsing.py
index fc83438d0..c94567338 100644
--- a/packages/python-sdk/tests/test_env_var_parsing.py
+++ b/packages/python-sdk/tests/test_env_var_parsing.py
@@ -10,7 +10,8 @@ _ENV_VARS = (
"E2B_KEEPALIVE_EXPIRY",
"E2B_MAX_KEEPALIVE_CONNECTIONS",
"E2B_CONNECTION_RETRIES",
- "E2B_ENVD_POOL_SHARDS",
+ "E2B_STREAMS_PER_CONNECTION",
+ "E2B_MAX_CONNECTIONS",
)
@@ -26,7 +27,8 @@ def test_empty_env_vars_fall_back_to_defaults(monkeypatch):
assert api.pool_idle_timeout == 300
assert api.pool_max_idle_per_host == 20
assert api.connection_retries == 3
- assert api.envd_pool_shards == 4
+ assert api.streams_per_connection == 100
+ assert api.max_connections == 200
finally:
monkeypatch.undo()
_reload()
@@ -35,12 +37,14 @@ def test_empty_env_vars_fall_back_to_defaults(monkeypatch):
def test_set_env_vars_are_honored(monkeypatch):
monkeypatch.setenv("E2B_KEEPALIVE_EXPIRY", "42")
monkeypatch.setenv("E2B_CONNECTION_RETRIES", "5")
- monkeypatch.setenv("E2B_ENVD_POOL_SHARDS", "8")
+ monkeypatch.setenv("E2B_STREAMS_PER_CONNECTION", "50")
+ monkeypatch.setenv("E2B_MAX_CONNECTIONS", "8")
try:
api = _reload()
assert api.pool_idle_timeout == 42
assert api.connection_retries == 5
- assert api.envd_pool_shards == 8
+ assert api.streams_per_connection == 50
+ assert api.max_connections == 8
finally:
monkeypatch.undo()
_reload()
diff --git a/packages/python-sdk/tests/test_envd_client_transport.py b/packages/python-sdk/tests/test_envd_client_transport.py
index 1b8c6203e..f99d1f7fe 100644
--- a/packages/python-sdk/tests/test_envd_client_transport.py
+++ b/packages/python-sdk/tests/test_envd_client_transport.py
@@ -180,3 +180,7 @@ def test_shared_pool_retries_connects():
assert isinstance(apool, api_client_async.ConnectionRetryTransport)
assert pool._max_retries == connection_retries
assert apool._max_retries == connection_retries
+ # The retries sit above the balancer, so a failed connect is retried on
+ # whichever pool is least loaded then rather than pinned to one.
+ assert isinstance(pool._transport, api_client_sync.BalancingTransport)
+ assert isinstance(apool._transport, api_client_async.BalancingTransport)
diff --git a/packages/python-sdk/tests/test_envd_stream_capacity.py b/packages/python-sdk/tests/test_envd_stream_capacity.py
index 1f3dbefb3..1cac61591 100644
--- a/packages/python-sdk/tests/test_envd_stream_capacity.py
+++ b/packages/python-sdk/tests/test_envd_stream_capacity.py
@@ -25,6 +25,11 @@ from e2b.envd.process.process_connect import ProcessClient, ProcessClientSync
from e2b.envd.process.process_pb import ConnectRequest
from transport_caches import reset_transport_caches
+# Production `sandbox.e2b.app` advertises 100 concurrent streams per
+# connection; the SDK dials another once a pool carries that many.
+STREAMS_PER_CONNECTION = 100
+WAVE = 80
+
def sandbox_config(sandbox_id: str) -> ConnectionConfig:
return ConnectionConfig(
@@ -36,55 +41,124 @@ def sandbox_config(sandbox_id: str) -> ConnectionConfig:
)
-def test_sync_envd_spreads_repeated_waves_across_reused_connections(monkeypatch):
- """Fresh sync sandboxes keep filling the same four pools evenly."""
- monkeypatch.setattr(api, "envd_pool_shards", 4)
- reset_transport_caches()
- build_transport = api_client_sync.SyncHTTPTransport
+def force_http2(monkeypatch, module, name):
+ # Production negotiates HTTP/2 over TLS. The frame server is plaintext, so
+ # force prior knowledge while retaining the production factory/cache.
+ build_transport = getattr(module, name)
def build_http2_transport(**kwargs):
- # Production negotiates HTTP/2 over TLS. The frame server is plaintext,
- # so force prior knowledge while retaining the production factory/cache.
kwargs["http_version"] = HTTPVersion.HTTP2
return build_transport(**kwargs)
- monkeypatch.setattr(api_client_sync, "SyncHTTPTransport", build_http2_transport)
+ monkeypatch.setattr(module, name, build_http2_transport)
+
+
+def active_streams(pool) -> list:
+ # Every stream in these tests goes to the frame server's one origin.
+ return [
+ sum(connection.active.values())
+ for connection in pool._transport.balancer.connections
+ ]
+
+
+def wave_counts(server, since: int) -> Counter:
+ return Counter(connection_id for connection_id, _ in server.streams[since:])
+
+
+def connections_used(server) -> int:
+ # Connections that carried a stream: hyper may race an extra dial for a
+ # fresh pool under concurrent requests and drop it unused.
+ return len(wave_counts(server, 0))
+
+
+def test_sync_envd_dials_connections_as_streams_fill_them(monkeypatch):
+ """Three waves of 80 sync streams: the first fits one connection, the
+ second spills onto a second, the third onto a third — and closed streams
+ hand their slots back so a fourth wave dials nothing new."""
+ monkeypatch.setattr(api, "streams_per_connection", STREAMS_PER_CONNECTION)
+ monkeypatch.setattr(api, "max_connections", 200)
+ reset_transport_caches()
+ force_http2(monkeypatch, api_client_sync, "SyncHTTPTransport")
+
+ streams = []
+
+ def open_wave(server, wave):
+ wave_streams = []
+ for index in range(WAVE):
+ client = create_sync_rpc_client(
+ ProcessClientSync,
+ f"http://127.0.0.1:{server.port}",
+ sandbox_config(f"sbx-wave-{wave}-{index}"),
+ )
+ wave_streams.append(as_sync_stream(client.connect(ConnectRequest())))
+ streams.extend(wave_streams)
+ with ThreadPoolExecutor(max_workers=len(wave_streams)) as executor:
+ futures = [executor.submit(next, stream) for stream in wave_streams]
+ assert len([future.result(timeout=2) for future in futures]) == WAVE
+ return wave_streams
+
+ try:
+ with stream_capacity_server(
+ max_concurrent_streams=STREAMS_PER_CONNECTION
+ ) as server:
+ pool = api_client_sync.get_pyqwest_transport(None)
+
+ first = open_wave(server, 0)
+ assert connections_used(server) == 1
+ assert active_streams(pool) == [80]
+
+ open_wave(server, 1)
+ assert connections_used(server) == 2
+ assert active_streams(pool) == [100, 60]
+ assert sorted(wave_counts(server, 80).values()) == [20, 60]
+
+ open_wave(server, 2)
+ assert connections_used(server) == 3
+ assert active_streams(pool) == [100, 100, 40]
+ assert len(server.active_streams) == 240
+
+ # Closing a stream resets it and frees its slot on the connection
+ # that carried it, so the next wave reuses that headroom instead
+ # of dialing.
+ for stream in first:
+ stream.close()
+ assert active_streams(pool) == [20, 100, 40]
+
+ open_wave(server, 3)
+ assert connections_used(server) == 3
+ assert active_streams(pool) == [70, 100, 70]
+ assert len(server.streams) == 320
+ server.assert_no_errors()
+ finally:
+ for stream in streams:
+ stream.close()
+ reset_transport_caches()
+
+
+def test_sync_envd_stops_dialing_at_the_connection_cap(monkeypatch):
+ monkeypatch.setattr(api, "streams_per_connection", 10)
+ monkeypatch.setattr(api, "max_connections", 2)
+ reset_transport_caches()
+ force_http2(monkeypatch, api_client_sync, "SyncHTTPTransport")
streams = []
try:
with stream_capacity_server(max_concurrent_streams=100) as server:
- connection_ids = None
- for wave in range(3):
- wave_streams = []
- for index in range(80):
- client = create_sync_rpc_client(
- ProcessClientSync,
- f"http://127.0.0.1:{server.port}",
- sandbox_config(f"sbx-wave-{wave}-{index}"),
- )
- wave_streams.append(
- as_sync_stream(client.connect(ConnectRequest()))
- )
- streams.extend(wave_streams)
-
- stream_count = len(server.streams)
- with ThreadPoolExecutor(max_workers=len(wave_streams)) as executor:
- futures = [executor.submit(next, stream) for stream in wave_streams]
- events = [future.result(timeout=2) for future in futures]
-
- assert len(events) == 80
- wave_counts = Counter(
- connection_id for connection_id, _ in server.streams[stream_count:]
+ for index in range(30):
+ client = create_sync_rpc_client(
+ ProcessClientSync,
+ f"http://127.0.0.1:{server.port}",
+ sandbox_config(f"sbx-{index}"),
)
- assert len(wave_counts) == 4
- if connection_ids is None:
- connection_ids = set(wave_counts)
- assert set(wave_counts) == connection_ids
- assert max(wave_counts.values()) - min(wave_counts.values()) <= 2
- assert len(server.active_streams) == (wave + 1) * 80
-
- assert len(server.connections) == 4
- assert len(server.streams) == 240
+ streams.append(as_sync_stream(client.connect(ConnectRequest())))
+ with ThreadPoolExecutor(max_workers=len(streams)) as executor:
+ futures = [executor.submit(next, stream) for stream in streams]
+ assert len([future.result(timeout=2) for future in futures]) == 30
+
+ pool = api_client_sync.get_pyqwest_transport(None)
+ assert connections_used(server) == 2
+ assert active_streams(pool) == [15, 15]
+ assert sorted(wave_counts(server, 0).values()) == [15, 15]
server.assert_no_errors()
finally:
for stream in streams:
@@ -93,60 +167,93 @@ def test_sync_envd_spreads_repeated_waves_across_reused_connections(monkeypatch)
@pytest.mark.asyncio
-async def test_async_envd_spreads_repeated_waves_across_reused_connections(
- monkeypatch,
-):
- """Fresh async sandboxes keep filling the same four pools evenly."""
- monkeypatch.setattr(api, "envd_pool_shards", 4)
+async def test_async_envd_dials_connections_as_streams_fill_them(monkeypatch):
+ monkeypatch.setattr(api, "streams_per_connection", STREAMS_PER_CONNECTION)
+ monkeypatch.setattr(api, "max_connections", 200)
reset_transport_caches()
- build_transport = api_client_async.HTTPTransport
+ force_http2(monkeypatch, api_client_async, "HTTPTransport")
- def build_http2_transport(**kwargs):
- # Production negotiates HTTP/2 over TLS. The frame server is plaintext,
- # so force prior knowledge while retaining the production factory/cache.
- kwargs["http_version"] = HTTPVersion.HTTP2
- return build_transport(**kwargs)
+ streams = []
+
+ async def open_wave(server, wave):
+ wave_streams = []
+ for index in range(WAVE):
+ client = create_async_rpc_client(
+ ProcessClient,
+ f"http://127.0.0.1:{server.port}",
+ sandbox_config(f"sbx-wave-{wave}-{index}"),
+ )
+ wave_streams.append(as_async_stream(client.connect(ConnectRequest())))
+ streams.extend(wave_streams)
+ events = await asyncio.gather(
+ *(first_event(stream, 0.5) for stream in wave_streams),
+ return_exceptions=True,
+ )
+ assert not [event for event in events if isinstance(event, BaseException)]
+ return wave_streams
+
+ try:
+ with stream_capacity_server(
+ max_concurrent_streams=STREAMS_PER_CONNECTION
+ ) as server:
+ pool = api_client_async.get_pyqwest_transport(None)
+
+ first = await open_wave(server, 0)
+ assert connections_used(server) == 1
+ assert active_streams(pool) == [80]
+
+ await open_wave(server, 1)
+ assert connections_used(server) == 2
+ assert active_streams(pool) == [100, 60]
+ assert sorted(wave_counts(server, 80).values()) == [20, 60]
- monkeypatch.setattr(api_client_async, "HTTPTransport", build_http2_transport)
+ await open_wave(server, 2)
+ assert connections_used(server) == 3
+ assert active_streams(pool) == [100, 100, 40]
+ assert len(server.active_streams) == 240
+
+ await asyncio.gather(*(stream.aclose() for stream in first))
+ assert active_streams(pool) == [20, 100, 40]
+
+ await open_wave(server, 3)
+ assert connections_used(server) == 3
+ assert active_streams(pool) == [70, 100, 70]
+ assert len(server.streams) == 320
+ server.assert_no_errors()
+ finally:
+ await asyncio.gather(
+ *(stream.aclose() for stream in streams), return_exceptions=True
+ )
+ reset_transport_caches()
+
+
+async def test_async_envd_stops_dialing_at_the_connection_cap(monkeypatch):
+ monkeypatch.setattr(api, "streams_per_connection", 10)
+ monkeypatch.setattr(api, "max_connections", 2)
+ reset_transport_caches()
+ force_http2(monkeypatch, api_client_async, "HTTPTransport")
streams = []
try:
with stream_capacity_server(max_concurrent_streams=100) as server:
- connection_ids = None
- for wave in range(3):
- wave_streams = []
- for index in range(80):
- client = create_async_rpc_client(
- ProcessClient,
- f"http://127.0.0.1:{server.port}",
- sandbox_config(f"sbx-wave-{wave}-{index}"),
- )
- wave_streams.append(
- as_async_stream(client.connect(ConnectRequest()))
- )
- streams.extend(wave_streams)
-
- stream_count = len(server.streams)
- events = await asyncio.gather(
- *(first_event(stream, 0.5) for stream in wave_streams),
- return_exceptions=True,
+ for index in range(30):
+ client = create_async_rpc_client(
+ ProcessClient,
+ f"http://127.0.0.1:{server.port}",
+ sandbox_config(f"sbx-{index}"),
)
+ streams.append(as_async_stream(client.connect(ConnectRequest())))
+ events = await asyncio.gather(
+ *(first_event(stream, 0.5) for stream in streams),
+ return_exceptions=True,
+ )
+ assert not [event for event in events if isinstance(event, BaseException)]
- assert not [
- event for event in events if isinstance(event, BaseException)
- ]
- wave_counts = Counter(
- connection_id for connection_id, _ in server.streams[stream_count:]
- )
- assert len(wave_counts) == 4
- if connection_ids is None:
- connection_ids = set(wave_counts)
- assert set(wave_counts) == connection_ids
- assert max(wave_counts.values()) - min(wave_counts.values()) <= 2
- assert len(server.active_streams) == (wave + 1) * 80
-
- assert len(server.connections) == 4
- assert len(server.streams) == 240
+ pool = api_client_async.get_pyqwest_transport(None)
+ assert connections_used(server) == 2
+ assert active_streams(pool) == [15, 15]
+ assert sorted(wave_counts(server, 0).values()) == [15, 15]
server.assert_no_errors()
finally:
await asyncio.gather(