Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
fix(sdk): retry 502 only for replayable operations, stop replaying secret updates (#1924)
devin-ai-integration[bot]3ba1d05e6f95
diff --git a/.changeset/python-retry-bad-gateway-replayable.md b/.changeset/python-retry-bad-gateway-replayable.mdnew file mode 100644index 000000000..a0a25ac42--- /dev/null+++ b/.changeset/python-retry-bad-gateway-replayable.md@@ -0,0 +1,5 @@+---+"@e2b/python-sdk": patch+---++Retry a `502` response only for operations that are safe to replay: a gateway may answer `502` after the API already processed the request, so a `502` from sandbox creation, fork, snapshot or another resource-creating `POST` is returned instead of being retried (which could create a duplicate). `503` is still retried for every operation. Secret updates (`POST /secrets/{id}`) are no longer replayed after a `502` or a dropped connection, as each update appends a new version.diff --git a/.changeset/retry-bad-gateway-replayable.md b/.changeset/retry-bad-gateway-replayable.mdnew file mode 100644index 000000000..d7e81935d--- /dev/null+++ b/.changeset/retry-bad-gateway-replayable.md@@ -0,0 +1,5 @@+---+"e2b": patch+---++Retry a `502` response only for operations that are safe to replay: a gateway may answer `502` after the API already processed the request, so a `502` from sandbox creation, fork, snapshot or another resource-creating `POST` is returned instead of being retried (which could create a duplicate). `503` is still retried for every operation. Secret updates (`POST /secrets/{id}`) are no longer replayed after a `502` or a dropped connection, as each update appends a new version.diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.tsindex 0810a973e..366cd886d 100644--- a/packages/js-sdk/src/connectionConfig.ts+++ b/packages/js-sdk/src/connectionConfig.ts@@ -88,8 +88,10 @@ export interface ConnectionOpts {* Number of control-plane API retries after a 429, 502 or 503 response or* a failure to establish the connection (refused, DNS, unreachable host).* Any other network error (dropped connection, opaque browser/Workers- * `TypeError`) is retried too, except for operations that create a resource- * (e.g. sandbox creation), as the server may already have processed them.+ * `TypeError`) is retried too. A 502 and those network errors are not+ * retried for operations that create a resource (e.g. sandbox creation) or+ * append to one (secret update), as the server may already have processed+ * them.* A 429 is retried only with a valid, non-negative integer delta-seconds* `Retry-After` header (HTTP-date and malformed values are not retried).* 502 and 503 honor such a `Retry-After` when present; otherwise they anddiff --git a/packages/js-sdk/src/retry.ts b/packages/js-sdk/src/retry.tsindex ea9f428dd..c0eff5f85 100644--- a/packages/js-sdk/src/retry.ts+++ b/packages/js-sdk/src/retry.ts@@ -26,12 +26,13 @@ const CONNECTION_ERROR_SYSCALLS = new Set(['connect', 'getaddrinfo'])// Deno reports hyper's connect-phase failures as `client error (Connect)`.const DENO_CONNECTION_ERROR = /client error \(Connect\)/// GET/PUT/PATCH/DELETE are idempotent by HTTP semantics. A POST is retried-// after a network error that may have occurred once the request was written-// only if it is listed here: a replay is a no-op or fails with a 404/409 the-// SDK already tolerates. POSTs that mint a resource without a client-supplied-// idempotency key (sandbox/fork/snapshot/API-key/volume/secret/webhook-// creation) must stay off the list — a replay could create a duplicate — and-// so does any new POST until it is reviewed. Connection-establishment failures+// after a 502 or a network error that may have occurred once the request was+// written only if it is listed here: a replay is a no-op or fails with a+// 404/409 the SDK already tolerates. POSTs that mint a resource without a+// client-supplied idempotency key (sandbox/fork/snapshot/API-key/volume/secret/+// webhook creation) or append to one (secret update) must stay off the list —+// a replay could create a duplicate — and so does any new POST until it is+// reviewed. Connection-establishment failures// are retried for every operation regardless: the request never left.const REPLAYABLE_METHODS = new Set(['GET', 'PUT', 'PATCH', 'DELETE'])const REPLAYABLE_OPERATIONS: [method: string, path: RegExp][] = [@@ -42,7 +43,6 @@ const REPLAYABLE_OPERATIONS: [method: string, path: RegExp][] = [['POST', /^\/templates\/tags$/],['POST', /^\/nodes\/[^/]+$/],['POST', /^\/admin\/teams\/[^/]+\/(sandboxes\/kill|builds\/cancel)$/],- ['POST', /^\/secrets\/[^/]+$/],]export function resolveRetries(retries: number): number {@@ -90,8 +90,8 @@ export function isConnectionError(error: unknown, depth = 0): boolean {}/**- * Whether `request` may be sent again after a network error that may have- * occurred once the request was written (see `REPLAYABLE_OPERATIONS`).+ * Whether `request` may be sent again after a 502 or a network error that may+ * have occurred once the request was written (see `REPLAYABLE_OPERATIONS`).*/export function isReplayable(request: Request): boolean {if (REPLAYABLE_METHODS.has(request.method)) return true@@ -150,14 +150,17 @@ function backoffMs(attempt: number, random: () => number): number {* Delay before the next attempt, or `undefined` when the response is not* retried: `Retry-After` when the server sends a usable one, otherwise* exponential backoff with jitter for 502/503. A 429 without `Retry-After`- * is not retried.+ * is not retried, nor is a 502 for a non-replayable request: a gateway may+ * answer 502 after the backend already processed it.*/function retryDelayMs(response: Response,attempt: number,+ replayable: boolean,random: () => number): number | undefined {if (!RETRYABLE_STATUSES.has(response.status)) return undefined+ if (response.status === 502 && !replayable) return undefinedconst retryAfter = parseRetryAfter(response.headers.get('Retry-After'))if (retryAfter !== undefined) return retryAfter * 1000@@ -167,9 +170,10 @@ function retryDelayMs(}/**- * Retry replayable requests after a 429 carrying `Retry-After`, a 502/503- * (using `Retry-After` when present, exponential backoff otherwise) or a- * network failure (exponential backoff; see {@link isRetryableFetchError}).+ * Retry requests after a 429 carrying `Retry-After`, a 503 or — for replayable+ * requests ({@link isReplayable}) — a 502 (using `Retry-After` when present,+ * exponential backoff otherwise), or a network failure (exponential backoff;+ * see {@link isRetryableFetchError}).*/export function withRetry(fetchImpl: typeof fetch,@@ -223,7 +227,7 @@ export function withRetry(}if (attempt === retries) return response- const delayMs = retryDelayMs(response, attempt, random)+ const delayMs = retryDelayMs(response, attempt, replayable, random)if (delayMs === undefined || monotonic() + delayMs >= deadline) {return response}diff --git a/packages/js-sdk/tests/retry.test.ts b/packages/js-sdk/tests/retry.test.tsindex 13065ef2c..7bd4f547e 100644--- a/packages/js-sdk/tests/retry.test.ts+++ b/packages/js-sdk/tests/retry.test.ts@@ -213,6 +213,47 @@ test.each([502, 503])(})+test.each([+ ['POST', '/sandboxes', 1],+ ['POST', '/secrets/secret-1', 1],+ ['POST', '/sandboxes/sbx-1/pause', 2],+ ['GET', '/sandboxes', 2],+])('a 502 for %s %s is attempted %i time(s)', async (method, path, calls) => {+ const statuses = [502, 200]+ const fetchImpl = vi.fn(+ async () => new Response(null, { status: statuses.shift() })+ ) as typeof fetch+ const fetchWithRetry = withRetry(fetchImpl, 3, 60_000, {+ monotonic: () => 0,+ sleep: async () => {},+ })++ const response = await fetchWithRetry(`https://api.e2b.test${path}`, {+ method,+ })++ expect(response.status).toBe(calls === 1 ? 502 : 200)+ expect(fetchImpl).toHaveBeenCalledTimes(calls)+})++test('retries a 503 for a non-replayable POST', async () => {+ const statuses = [503, 200]+ const fetchImpl = vi.fn(+ async () => new Response(null, { status: statuses.shift() })+ ) as typeof fetch+ const fetchWithRetry = withRetry(fetchImpl, 3, 60_000, {+ monotonic: () => 0,+ sleep: async () => {},+ })++ const response = await fetchWithRetry('https://api.e2b.test/sandboxes', {+ method: 'POST',+ })++ expect(response.status).toBe(200)+ expect(fetchImpl).toHaveBeenCalledTimes(2)+})+test('caps the backoff for long retry sequences', async () => {const fetchImpl = vi.fn(async () => new Response(null, { status: 503 })@@ -496,6 +537,7 @@ const nonReplayable = [['POST', '/admin/teams/team-1/api-keys'],['POST', '/volumes'],['POST', '/secrets'],+ ['POST', '/secrets/secret-1'],['POST', '/events/webhooks'],// POSTs not on the allowlist: unknown and near-miss paths['POST', '/sandboxes/sbx-1/pause/extra'],@@ -523,7 +565,6 @@ const replayable = [['POST', '/nodes/node-1'],['POST', '/admin/teams/team-1/sandboxes/kill'],['POST', '/admin/teams/team-1/builds/cancel'],- ['POST', '/secrets/secret-1'],['DELETE', '/volumes/vol-1'],['PATCH', '/events/webhooks/hook-1'],]diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.pyindex 4a712f140..1d6bf148c 100644--- a/packages/python-sdk/e2b/connection_config.py+++ b/packages/python-sdk/e2b/connection_config.py@@ -71,9 +71,10 @@ class ApiParams(TypedDict, total=False):retries: Optional[int]"""Number of control-plane HTTP retries after a 429, 502 or 503 response or- a network error once the request was written (dropped connection). The- latter is not retried for operations that create a resource (e.g. sandbox- creation), as the server may already have processed them; failures to+ a network error once the request was written (dropped connection). A 502+ and such network errors are not retried for operations that create a+ resource (e.g. sandbox creation) or append to one (secret update), as the+ server may already have processed them; failures toestablish the connection are retried separately for every operation, see``E2B_CONNECTION_RETRIES``.A 429 is retried only with a valid, non-negative integer delta-secondsdiff --git a/packages/python-sdk/e2b/retry.py b/packages/python-sdk/e2b/retry.pyindex dd5e8d410..50510fccf 100644--- a/packages/python-sdk/e2b/retry.py+++ b/packages/python-sdk/e2b/retry.py@@ -16,12 +16,13 @@ BACKOFF_JITTER_MIN = 0.5RETRYABLE_STATUSES = frozenset({429, 502, 503})# GET/PUT/PATCH/DELETE are idempotent by HTTP semantics. A POST is retried-# after a network error that may have occurred once the request was written-# only if it is listed here: a replay is a no-op or fails with a 404/409 the-# SDK already tolerates. POSTs that mint a resource without a client-supplied-# idempotency key (sandbox/fork/snapshot/API-key/volume/secret/webhook-# creation) must stay off the list — a replay could create a duplicate — and-# so does any new POST until it is reviewed. (Connection-establishment+# after a 502 or a network error that may have occurred once the request was+# written only if it is listed here: a replay is a no-op or fails with a+# 404/409 the SDK already tolerates. POSTs that mint a resource without a+# client-supplied idempotency key (sandbox/fork/snapshot/API-key/volume/secret/+# webhook creation) or append to one (secret update) must stay off the list —+# a replay could create a duplicate — and so does any new POST until it is+# reviewed. (Connection-establishment# failures are retried for every operation by ``ConnectionRetryTransport``# underneath: the request never left.)REPLAYABLE_METHODS = frozenset({"GET", "PUT", "PATCH", "DELETE"})@@ -33,7 +34,6 @@ REPLAYABLE_OPERATIONS: List[Tuple[str, re.Pattern[str]]] = [("POST", re.compile(r"^/templates/tags$")),("POST", re.compile(r"^/nodes/[^/]+$")),("POST", re.compile(r"^/admin/teams/[^/]+/(sandboxes/kill|builds/cancel)$")),- ("POST", re.compile(r"^/secrets/[^/]+$")),]# Raised by the pyqwest httpx adapter once the request was (at least partially)@@ -63,8 +63,8 @@ def parse_retry_after(value: Optional[str]) -> Optional[int]:def is_replayable(request: httpx.Request) -> bool:- """Whether ``request`` may be sent again after a network error that may- have occurred once it was written (see ``REPLAYABLE_OPERATIONS``)."""+ """Whether ``request`` may be sent again after a 502 or a network error+ that may have occurred once it was written (see ``REPLAYABLE_OPERATIONS``)."""if request.method in REPLAYABLE_METHODS:return Truepath = request.url.path@@ -80,14 +80,20 @@ def _backoff_delay(attempt: int, random_: Callable[[], float]) -> float:def _retry_delay(- response: httpx.Response, attempt: int, random_: Callable[[], float]+ response: httpx.Response,+ attempt: int,+ replayable: bool,+ random_: Callable[[], float],) -> Optional[float]:"""Delay before the next attempt, or ``None`` when the response is notretried: ``Retry-After`` when the server sends a usable one, otherwiseexponential backoff with jitter for 502/503. A 429 without ``Retry-After``- is not retried."""+ is not retried, nor is a 502 for a non-replayable request: a gateway may+ answer 502 after the backend already processed it."""if response.status_code not in RETRYABLE_STATUSES:return None+ if response.status_code == 502 and not replayable:+ return Noneretry_after = parse_retry_after(response.headers.get("Retry-After"))if retry_after is not None:@@ -133,9 +139,10 @@ def _request_deadline(request: httpx.Request, monotonic: Callable[[], float]) ->class RetryableTransport(httpx.BaseTransport):- """Retry replayable requests after a 429 carrying ``Retry-After`` or a- 502/503 (using ``Retry-After`` when present, exponential backoff- otherwise), and — for replayable operations (``is_replayable``) — after a network error once the request was written."""+ """Retry requests after a 429 carrying ``Retry-After`` or a 503, and — for+ replayable operations (``is_replayable``) — after a 502 (using+ ``Retry-After`` when present, exponential backoff otherwise) or a network+ error once the request was written."""def __init__(self,@@ -186,7 +193,7 @@ class RetryableTransport(httpx.BaseTransport):if attempt == self.retries:return response- delay = _retry_delay(response, attempt, self._random)+ delay = _retry_delay(response, attempt, replayable, self._random)if delay is None or self._monotonic() + delay >= deadline:return response@@ -252,7 +259,7 @@ class AsyncRetryableTransport(httpx.AsyncBaseTransport):if attempt == self.retries:return response- delay = _retry_delay(response, attempt, self._random)+ delay = _retry_delay(response, attempt, replayable, self._random)if delay is None or self._monotonic() + delay >= deadline:return responsediff --git a/packages/python-sdk/tests/test_rate_limit_retry_transport.py b/packages/python-sdk/tests/test_rate_limit_retry_transport.pyindex 481c1f8a4..c4699a8b7 100644--- a/packages/python-sdk/tests/test_rate_limit_retry_transport.py+++ b/packages/python-sdk/tests/test_rate_limit_retry_transport.py@@ -180,7 +180,9 @@ def test_retries_unavailable_status_with_exponential_backoff_and_jitter(status):inner = FakeTransport([status, status, status, 200], retry_after=None)sleeps = []randoms = iter([0.0, 1.0, 0.5])- request = httpx.Request("POST", "https://api.test", content=b"payload")+ request = httpx.Request(+ "POST", "https://api.test/sandboxes/sbx-1/pause", content=b"payload"+ )response = RetryableTransport(inner,@@ -196,6 +198,37 @@ def test_retries_unavailable_status_with_exponential_backoff_and_jitter(status):assert all(item.is_closed for item in inner.responses[:-1])+ ("method", "path", "attempts"),+ [+ ("POST", "/sandboxes", 1),+ ("POST", "/secrets/secret-1", 1),+ ("POST", "/sandboxes/sbx-1/pause", 2),+ ("GET", "/sandboxes", 2),+ ],+)+def test_bad_gateway_is_retried_only_for_replayable_operations(method, path, attempts):+ inner = FakeTransport([502, 200], retry_after=None)++ response = RetryableTransport(+ inner, retries=3, sleep=lambda _: None, monotonic=lambda: 0.0+ ).handle_request(httpx.Request(method, f"https://api.test{path}", content=b"p"))++ assert response.status_code == (502 if attempts == 1 else 200)+ assert len(inner.requests) == attempts+++def test_service_unavailable_is_retried_for_non_replayable_operation():+ inner = FakeTransport([503, 200], retry_after=None)++ response = RetryableTransport(+ inner, retries=3, sleep=lambda _: None, monotonic=lambda: 0.0+ ).handle_request(httpx.Request("POST", "https://api.test/sandboxes", content=b"p"))++ assert response.status_code == 200+ assert len(inner.requests) == 2++def test_backoff_is_capped_for_long_retry_sequences():inner = FakeTransport([503] * 9, retry_after=None)sleeps = []@@ -410,6 +443,7 @@ NON_REPLAYABLE = [("POST", "/admin/teams/team-1/api-keys"),("POST", "/volumes"),("POST", "/secrets"),+ ("POST", "/secrets/secret-1"),("POST", "/events/webhooks"),# POSTs not on the allowlist: unknown and near-miss paths("POST", "/sandboxes/sbx-1/pause/extra"),@@ -437,7 +471,6 @@ REPLAYABLE = [("POST", "/nodes/node-1"),("POST", "/admin/teams/team-1/sandboxes/kill"),("POST", "/admin/teams/team-1/builds/cancel"),- ("POST", "/secrets/secret-1"),("DELETE", "/volumes/vol-1"),("PATCH", "/events/webhooks/hook-1"),]@@ -627,7 +660,9 @@ async def test_async_retries_unavailable_status_with_backoff():monotonic=lambda: 0.0,random_=lambda: next(randoms),).handle_async_request(- httpx.Request("POST", "https://api.test", content=b"payload")+ httpx.Request(+ "POST", "https://api.test/sandboxes/sbx-1/pause", content=b"payload"+ ))assert response.status_code == 200@@ -636,6 +671,34 @@ async def test_async_retries_unavailable_status_with_backoff():assert all(item.is_closed for item in inner.responses[:-1])+ ("method", "path", "attempts"),+ [+ ("POST", "/sandboxes", 1),+ ("POST", "/secrets/secret-1", 1),+ ("POST", "/sandboxes/sbx-1/pause", 2),+ ("GET", "/sandboxes", 2),+ ],+)+async def test_async_bad_gateway_is_retried_only_for_replayable_operations(+ method, path, attempts+):+ inner = FakeAsyncTransport([502, 200], retry_after=None)++ async def sleep(_):+ pass++ response = await AsyncRetryableTransport(+ inner, retries=3, sleep=sleep, monotonic=lambda: 0.0+ ).handle_async_request(+ httpx.Request(method, f"https://api.test{path}", content=b"p")+ )++ assert response.status_code == (502 if attempts == 1 else 200)+ assert len(inner.requests) == attempts++@pytest.mark.asyncio@pytest.mark.parametrize("status", [400, 404, 500, 504])async def test_async_does_not_retry_other_status_codes(status):