Open-source, secure environment with real-world tools for enterprise-grade agents.
Python agentaiai-agentai-agentscode-interpretercopilotdevelopmentdevtoolsgptgpt-4javascriptllmnextjsopenaipythonreactsoftwaretypescript
feat(sdk): retry control-plane requests on 502/503 and connection failures (#1888)
devin-ai-integration[bot]97522f8fc242
diff --git a/.changeset/python-retry-unavailable-responses.md b/.changeset/python-retry-unavailable-responses.mdnew file mode 100644index 000000000..4fcacf384--- /dev/null+++ b/.changeset/python-retry-unavailable-responses.md@@ -0,0 +1,5 @@+---+"@e2b/python-sdk": patch+---++Retry control-plane HTTP requests after `502` and `503` responses, in addition to `429`, and after a network error once the request was written (dropped connection) — except for `POST` operations not known to be safe to replay (sandbox creation, fork, snapshot, volume/secret/API-key/webhook creation), which the server may already have processed. Failures to establish the connection keep being retried for every operation (`E2B_CONNECTION_RETRIES`). `Retry-After` is honored when the server sends one; otherwise retries back off exponentially with jitter, starting at 0.1 seconds and capped at 10 seconds. The existing `retries` option (default 3, `0` to disable) and request-timeout budget apply to all of them.diff --git a/.changeset/retry-unavailable-responses.md b/.changeset/retry-unavailable-responses.mdnew file mode 100644index 000000000..d8188bcd5--- /dev/null+++ b/.changeset/retry-unavailable-responses.md@@ -0,0 +1,5 @@+---+"e2b": patch+---++Retry control-plane HTTP requests after `502` and `503` responses and failures to establish the connection (connection refused, DNS, unreachable host), in addition to `429`. Any other network error (dropped connection, or the opaque `TypeError` browsers and Cloudflare Workers raise) is retried too, except for `POST` operations not known to be safe to replay (sandbox creation, fork, snapshot, volume/secret/API-key/webhook creation), which the server may already have processed. `Retry-After` is honored when the server sends one; otherwise retries back off exponentially with jitter, starting at 100 ms and capped at 10 s. The existing `retries` option (default 3, `0` to disable) and request-timeout budget apply to all of them.diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.tsindex de6289f58..274491195 100644--- a/packages/js-sdk/src/api/index.ts+++ b/packages/js-sdk/src/api/index.ts@@ -11,7 +11,7 @@ import {SandboxError,} from '../errors'import { createApiLogger } from '../logs'-import { withRateLimitRetry } from '../retry'+import { withRetry } from '../retry'/*** Map an API error code and message to the matching error class — the same@@ -106,7 +106,7 @@ class ApiClient {this.api = createClient<paths>({baseUrl: config.apiUrl,- fetch: withRateLimitRetry(+ fetch: withRetry(createApiFetch(config.proxy),config.retries,config.requestTimeoutMsdiff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.tsindex 366c30d07..909bc72e6 100644--- a/packages/js-sdk/src/connectionConfig.ts+++ b/packages/js-sdk/src/connectionConfig.ts@@ -60,9 +60,16 @@ export interface ConnectionOpts {*/requestTimeoutMs?: number/**- * Number of control-plane API retries after a 429 response with a valid,- * non-negative integer delta-seconds `Retry-After` header. HTTP-date and- * malformed values are not retried.+ * 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.+ * 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 and+ * connection failures use exponential backoff with jitter starting at+ * 100 ms (capped at 10 s).* Retry waits use a 60-second total limit when request timeouts are disabled.** @default 3diff --git a/packages/js-sdk/src/retry.ts b/packages/js-sdk/src/retry.tsindex 7ad186ba9..ea9f428dd 100644--- a/packages/js-sdk/src/retry.ts+++ b/packages/js-sdk/src/retry.ts@@ -3,6 +3,47 @@ import { isReadableStreamLike } from './is'const MAX_RETRY_AFTER_SECONDS = 2_147_483const MAX_RETRY_WAIT_WITHOUT_TIMEOUT_MS = 60_000+const BACKOFF_BASE_MS = 100+const BACKOFF_MAX_MS = 10_000+const BACKOFF_JITTER_MIN = 0.5+const RETRYABLE_STATUSES = new Set([429, 502, 503])+// Error codes raised while establishing the connection, before any request+// bytes are written: Node/undici (`ECONNREFUSED`, `ENOTFOUND`, ...), Bun+// (`ConnectionRefused`). Post-write failures such as `ECONNRESET` are+// excluded: the server may have received the request.+const CONNECTION_ERROR_CODES = new Set([+ 'ECONNREFUSED',+ 'ENOTFOUND',+ 'EAI_AGAIN',+ 'EHOSTUNREACH',+ 'ENETUNREACH',+ 'ENETDOWN',+ 'EHOSTDOWN',+ 'UND_ERR_CONNECT_TIMEOUT',+ 'ConnectionRefused',+])+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+// 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][] = [+ ['POST', /^\/sandboxes\/[^/]+\/(pause|resume|timeout|refreshes)$/],+ ['POST', /^\/(v2\/)?sandboxes\/[^/]+\/connect$/],+ ['POST', /^\/v3\/templates$/],+ ['POST', /^\/v2\/templates\/[^/]+\/builds\/[^/]+$/],+ ['POST', /^\/templates\/tags$/],+ ['POST', /^\/nodes\/[^/]+$/],+ ['POST', /^\/admin\/teams\/[^/]+\/(sandboxes\/kill|builds\/cancel)$/],+ ['POST', /^\/secrets\/[^/]+$/],+]export function resolveRetries(retries: number): number {if (!Number.isInteger(retries) || retries < 0) {@@ -27,9 +68,59 @@ export function parseRetryAfter(: undefined}+/**+ * Whether `error` (thrown by `fetch`) is a failure to establish the connection.+ * Walks `cause` chains and `AggregateError` members, as Node wraps the socket+ * error in a `TypeError('fetch failed')`.+ */+export function isConnectionError(error: unknown, depth = 0): boolean {+ if (!(error instanceof Error) || depth > 4) return false++ const { code, syscall } = error as { code?: unknown; syscall?: unknown }+ if (typeof code === 'string' && CONNECTION_ERROR_CODES.has(code)) return true+ if (typeof syscall === 'string' && CONNECTION_ERROR_SYSCALLS.has(syscall)) {+ return true+ }+ if (DENO_CONNECTION_ERROR.test(error.message)) return true++ if (error instanceof AggregateError) {+ return error.errors.some((member) => isConnectionError(member, depth + 1))+ }+ return isConnectionError(error.cause, depth + 1)+}++/**+ * Whether `request` may be sent again after 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+ const { pathname } = new URL(request.url)+ return REPLAYABLE_OPERATIONS.some(+ ([method, path]) => request.method === method && path.test(pathname)+ )+}++/**+ * Whether a `fetch` rejection may be retried. Connection-establishment+ * failures are always retried: the request never left. For a replayable+ * request any other network error is retried as well — a connection dropped+ * mid-request, or the opaque `TypeError` browsers and Cloudflare Workers raise+ * for every network failure. Aborts are never retried.+ */+export function isRetryableFetchError(+ error: unknown,+ replayable: boolean+): boolean {+ if (error instanceof DOMException) return false+ if (isConnectionError(error)) return true+ return replayable && error instanceof Error+}+type RetryDependencies = {monotonic?: () => numbersleep?: (delayMs: number, signal: AbortSignal) => Promise<void>+ random?: () => number}function wait(delayMs: number, signal: AbortSignal): Promise<void> {@@ -48,8 +139,39 @@ function wait(delayMs: number, signal: AbortSignal): Promise<void> {})}-/** Retry replayable requests after a 429 carrying `Retry-After`. */-export function withRateLimitRetry(+function backoffMs(attempt: number, random: () => number): number {+ const backoff = Math.min(BACKOFF_BASE_MS * 2 ** attempt, BACKOFF_MAX_MS)+ return Math.floor(+ backoff * (BACKOFF_JITTER_MIN + random() * (1 - BACKOFF_JITTER_MIN))+ )+}++/**+ * 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.+ */+function retryDelayMs(+ response: Response,+ attempt: number,+ random: () => number+): number | undefined {+ if (!RETRYABLE_STATUSES.has(response.status)) return undefined++ const retryAfter = parseRetryAfter(response.headers.get('Retry-After'))+ if (retryAfter !== undefined) return retryAfter * 1000+ if (response.status === 429) return undefined++ return backoffMs(attempt, random)+}++/**+ * 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}).+ */+export function withRetry(fetchImpl: typeof fetch,retries: number,requestTimeoutMs: number,@@ -57,6 +179,7 @@ export function withRateLimitRetry(): typeof fetch {const monotonic = dependencies.monotonic ?? (() => performance.now())const sleep = dependencies.sleep ?? wait+ const random = dependencies.random ?? Math.randomreturn (async (input, init) => {// Streaming bodies would be consumed by the first attempt and cannot be@@ -75,24 +198,39 @@ export function withRateLimitRetry(: new Request(input, init)const deadline =monotonic() + (requestTimeoutMs || MAX_RETRY_WAIT_WITHOUT_TIMEOUT_MS)+ const replayable = isReplayable(request)for (let attempt = 0; ; attempt++) {- const response = await fetchImpl(- attempt === retries ? request : request.clone()- )- const retryAfter = parseRetryAfter(response.headers.get('Retry-After'))- const delayMs = retryAfter === undefined ? undefined : retryAfter * 1000-- if (- response.status !== 429 ||- delayMs === undefined ||- attempt === retries ||- monotonic() + delayMs >= deadline- ) {+ let response: Response+ try {+ response = await fetchImpl(+ attempt === retries ? request : request.clone()+ )+ } catch (error) {+ if (+ attempt === retries ||+ request.signal.aborted ||+ !isRetryableFetchError(error, replayable)+ ) {+ throw error+ }++ const delayMs = backoffMs(attempt, random)+ if (monotonic() + delayMs >= deadline) throw error++ await sleep(delayMs, request.signal)+ continue+ }+ if (attempt === retries) return response++ const delayMs = retryDelayMs(response, attempt, random)+ if (delayMs === undefined || monotonic() + delayMs >= deadline) {return response}- await response.body?.cancel().catch(() => {})+ // Not awaited: some fetch interceptors never settle `cancel()`, and the+ // retry does not depend on the discarded body having been released.+ void response.body?.cancel().catch(() => {})await sleep(delayMs, request.signal)}}) as typeof fetchdiff --git a/packages/js-sdk/tests/client.test.ts b/packages/js-sdk/tests/client.test.tsindex 5e4e18287..3364bd191 100644--- a/packages/js-sdk/tests/client.test.ts+++ b/packages/js-sdk/tests/client.test.ts@@ -215,6 +215,27 @@ test('client replays serialized control-plane JSON after a rate limit', async ()expect(bodies[1]).toEqual(bodies[0])})+test('client retries sandbox creation after a 503', async () => {+ let attempts = 0+ server.use(+ http.post(/\/sandboxes$/, () => {+ attempts+++ if (attempts === 1) {+ return HttpResponse.json(+ { code: 503, message: 'not enough capacity' },+ { status: 503, headers: { 'Retry-After': '0' } }+ )+ }+ return HttpResponse.json(sandboxResponse)+ })+ )+ const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })++ await client.Sandbox.create()++ assert.equal(attempts, 2)+})+test('client.Sandbox can be rebound to a variable', async () => {const client = new E2B({ apiKey: API_KEY_A, domain: DOMAIN_A })const S = client.Sandboxdiff --git a/packages/js-sdk/tests/retry.test.ts b/packages/js-sdk/tests/retry.test.tsindex dfb934782..13065ef2c 100644--- a/packages/js-sdk/tests/retry.test.ts+++ b/packages/js-sdk/tests/retry.test.ts@@ -1,9 +1,12 @@import { describe, expect, test, vi } from 'vitest'import {+ isConnectionError,+ isReplayable,+ isRetryableFetchError,parseRetryAfter,resolveRetries,- withRateLimitRetry,+ withRetry,} from '../src/retry'import { EnvdApiClient } from '../src/envd/api'import { InvalidArgumentError } from '../src/errors'@@ -49,7 +52,7 @@ test('retries a buffered request and cancels the intermediate response', async (return bodies.length === 1 ? rateLimited : new Response('ok')}) as typeof fetchconst sleep = vi.fn(async () => {})- const fetchWithRetry = withRateLimitRetry(fetchImpl, 1, 10_000, {+ const fetchWithRetry = withRetry(fetchImpl, 1, 10_000, {monotonic: () => 0,sleep,})@@ -89,7 +92,7 @@ test.each(['', '{"templateID":"base"}'])(})}) as typeof fetch- const response = await withRateLimitRetry(fetchImpl, 2, 10_000)(request)+ const response = await withRetry(fetchImpl, 2, 10_000)(request)expect(response.status).toBe(200)expect(bodies).toEqual([body, body, body])@@ -114,7 +117,7 @@ test('returns the final 429 after exhausting retries', async () => {headers: { 'Retry-After': '0' },})}) as typeof fetch- const fetchWithRetry = withRateLimitRetry(fetchImpl, 2, 10_000, {+ const fetchWithRetry = withRetry(fetchImpl, 2, 10_000, {monotonic: () => 0,sleep: async () => {},})@@ -133,7 +136,7 @@ test('propagates 429 when Retry-After exceeds the request timeout', async () =>})}) as typeof fetchconst sleep = vi.fn(async () => {})- const fetchWithRetry = withRateLimitRetry(fetchImpl, 1, 1_000, {+ const fetchWithRetry = withRetry(fetchImpl, 1, 1_000, {monotonic: () => 0,sleep,})@@ -154,7 +157,7 @@ test('bounds retry waits when the request timeout is disabled', async () => {})) as typeof fetchconst sleep = vi.fn(async () => {})- const fetchWithRetry = withRateLimitRetry(fetchImpl, 3, 0, {+ const fetchWithRetry = withRetry(fetchImpl, 3, 0, {monotonic: () => 0,sleep,})@@ -170,7 +173,7 @@ test('propagates 429 without Retry-After as is', async () => {const rateLimited = new Response('rate limited', { status: 429 })const fetchImpl = vi.fn(async () => rateLimited) as typeof fetchconst sleep = vi.fn(async () => {})- const fetchWithRetry = withRateLimitRetry(fetchImpl, 2, 10_000, {+ const fetchWithRetry = withRetry(fetchImpl, 2, 10_000, {monotonic: () => 0,sleep,})@@ -183,13 +186,133 @@ test('propagates 429 without Retry-After as is', async () => {expect(sleep).not.toHaveBeenCalled()})+test.each([502, 503])(+ 'retries a %s with exponential backoff and jitter',+ async (status) => {+ const statuses = [status, status, status, 200]+ const fetchImpl = vi.fn(+ async () => new Response(null, { status: statuses.shift() })+ ) as typeof fetch+ const sleep = vi.fn(async () => {})+ const random = vi+ .fn<() => number>()+ .mockReturnValueOnce(0)+ .mockReturnValueOnce(1)+ .mockReturnValueOnce(0.5)+ const fetchWithRetry = withRetry(fetchImpl, 3, 60_000, {+ monotonic: () => 0,+ sleep,+ random,+ })++ const response = await fetchWithRetry('https://api.e2b.test/resource')++ expect(response.status).toBe(200)+ expect(fetchImpl).toHaveBeenCalledTimes(4)+ expect(sleep.mock.calls.map(([delayMs]) => delayMs)).toEqual([50, 200, 300])+ }+)++test('caps the backoff for long retry sequences', async () => {+ const fetchImpl = vi.fn(+ async () => new Response(null, { status: 503 })+ ) as typeof fetch+ const sleep = vi.fn(async () => {})+ const fetchWithRetry = withRetry(fetchImpl, 8, 0, {+ monotonic: () => 0,+ sleep,+ random: () => 1,+ })++ await fetchWithRetry('https://api.e2b.test/resource')++ expect(sleep.mock.calls.map(([delayMs]) => delayMs)).toEqual([+ 100, 200, 400, 800, 1_600, 3_200, 6_400, 10_000,+ ])+})++test('prefers Retry-After over backoff for a 503', async () => {+ const statuses = [503, 200]+ const fetchImpl = vi.fn(+ async () =>+ new Response(null, {+ status: statuses.shift(),+ headers: { 'Retry-After': '3' },+ })+ ) as typeof fetch+ const sleep = vi.fn(async () => {})+ const random = vi.fn(() => 0)+ const fetchWithRetry = withRetry(fetchImpl, 3, 10_000, {+ monotonic: () => 0,+ sleep,+ random,+ })++ const response = await fetchWithRetry('https://api.e2b.test/resource')++ expect(response.status).toBe(200)+ expect(sleep).toHaveBeenCalledWith(3_000, expect.any(AbortSignal))+ expect(random).not.toHaveBeenCalled()+})++test('returns the final 503 after exhausting retries', async () => {+ const fetchImpl = vi.fn(+ async () => new Response('busy', { status: 503 })+ ) as typeof fetch+ const fetchWithRetry = withRetry(fetchImpl, 2, 10_000, {+ monotonic: () => 0,+ sleep: async () => {},+ })++ const response = await fetchWithRetry('https://api.e2b.test/resource')++ expect(response.status).toBe(503)+ expect(await response.text()).toBe('busy')+ expect(fetchImpl).toHaveBeenCalledTimes(3)+})++test('propagates 502 when the backoff would exceed the request timeout', async () => {+ const fetchImpl = vi.fn(+ async () => new Response(null, { status: 502 })+ ) as typeof fetch+ const sleep = vi.fn(async () => {})+ const fetchWithRetry = withRetry(fetchImpl, 3, 80, {+ monotonic: () => 0,+ sleep,+ random: () => 1,+ })++ const response = await fetchWithRetry('https://api.e2b.test/resource')++ expect(response.status).toBe(502)+ expect(fetchImpl).toHaveBeenCalledOnce()+ expect(sleep).not.toHaveBeenCalled()+})++test.each([400, 404, 500, 504])('does not retry a %s', async (status) => {+ const failed = new Response('error', { status })+ const fetchImpl = vi.fn(async () => failed) as typeof fetch+ const sleep = vi.fn(async () => {})+ const fetchWithRetry = withRetry(fetchImpl, 3, 10_000, {+ monotonic: () => 0,+ sleep,+ })++ const response = await fetchWithRetry('https://api.e2b.test/resource')++ expect(response).toBe(failed)+ expect(response.bodyUsed).toBe(false)+ expect(fetchImpl).toHaveBeenCalledOnce()+ expect(sleep).not.toHaveBeenCalled()+})+test('aborting during Retry-After sleep rejects promptly', async () => {const rateLimited = new Response('rate limited', {status: 429,headers: { 'Retry-After': '1' },})const fetchImpl = vi.fn(async () => rateLimited) as typeof fetch- const fetchWithRetry = withRateLimitRetry(fetchImpl, 1, 10_000)+ const fetchWithRetry = withRetry(fetchImpl, 1, 10_000)const controller = new AbortController()const reason = new Error('cancelled')@@ -208,7 +331,7 @@ test.each([0, 3])('retries=%s passes a streaming request through unchanged',async (retries) => {const fetchImpl = vi.fn(async () => new Response('ok')) as typeof fetch- const fetchWithRetry = withRateLimitRetry(fetchImpl, retries, 10_000)+ const fetchWithRetry = withRetry(fetchImpl, retries, 10_000)const body = new ReadableStream()const init = {method: 'POST',@@ -248,3 +371,319 @@ test('envd clients do not retry rate-limited requests', async () => {expect(response.response.status).toBe(429)expect(fetchImpl).toHaveBeenCalledOnce()})++function connectError(code: string, syscall = 'connect'): TypeError {+ return new TypeError('fetch failed', {+ cause: Object.assign(new Error(`${syscall} ${code}`), { code, syscall }),+ })+}++// Shapes observed from `fetch()` against a refused port / unresolvable host.+const connectFailures = {+ 'Node refused': connectError('ECONNREFUSED'),+ 'Node dns': connectError('ENOTFOUND', 'getaddrinfo'),+ 'Node connect timeout': connectError('ETIMEDOUT'),+ 'Node happy-eyeballs': Object.assign(new Error('fetch failed'), {+ cause: new AggregateError([connectError('ECONNREFUSED').cause]),+ }),+ 'Bun refused': Object.assign(+ new TypeError('Unable to connect. Is the computer able to access the url?'),+ { code: 'ConnectionRefused' }+ ),+ 'Bun dns': Object.assign(+ new TypeError('getaddrinfo ENOTFOUND nonexistent.invalid'),+ { code: 'ENOTFOUND', syscall: 'getaddrinfo' }+ ),+ 'Deno refused': new TypeError(+ 'error sending request for url (http://x): client error (Connect): tcp connect error'+ ),+ 'Deno dns': new TypeError(+ 'error sending request for url (http://x): client error (Connect): dns error'+ ),+}++// Connection dropped after the request was (at least partially) written:+// the server may have processed it, so these are replayed only for+// operations that are safe to replay.+const terminated = {+ Node: new TypeError('terminated'),+ 'Node reset': new TypeError('fetch failed', {+ cause: Object.assign(new Error('read ECONNRESET'), {+ code: 'ECONNRESET',+ syscall: 'read',+ }),+ }),+ 'Node socket': new TypeError('fetch failed', {+ cause: Object.assign(new Error('socket'), { code: 'UND_ERR_SOCKET' }),+ }),+ Bun: new Error('The socket connection was closed unexpectedly'),+ Deno: new TypeError('error reading a body from connection'),+ 'Deno send': new TypeError(+ 'error sending request for url (http://x): client error (SendRequest)'+ ),+ 'Cloudflare Workers': new Error('Network connection lost.'),+ Browser: new TypeError('network error'),+}++// Opaque failures that look identical whether the connection was never+// established or was lost mid-request.+const opaque = {+ 'Cloudflare Workers': Object.assign(new Error('Network connection lost.'), {+ remote: true,+ retryable: true,+ }),+ 'Cloudflare Workers dns': Object.assign(+ new Error('internal error; reference = abc'),+ { remote: true }+ ),+ Chrome: new TypeError('Failed to fetch'),+ Firefox: new TypeError('NetworkError when attempting to fetch resource.'),+ Safari: new TypeError('Load failed'),+}++const aborts = {+ abort: new DOMException('aborted', 'AbortError'),+ timeout: new DOMException('timed out', 'TimeoutError'),+}++describe('isConnectionError', () => {+ test.each(Object.entries(connectFailures))('recognizes %s', (_, error) => {+ expect(isConnectionError(error)).toBe(true)+ })++ test.each([+ ...Object.entries(terminated),+ ...Object.entries(opaque),+ ...Object.entries(aborts),+ ['non-error', 'ECONNREFUSED'],+ ])('rejects %s', (_, error) => {+ expect(isConnectionError(error)).toBe(false)+ })+})++describe('isRetryableFetchError', () => {+ test.each(Object.entries(connectFailures))(+ 'retries %s for any operation',+ (_, error) => {+ expect(isRetryableFetchError(error, true)).toBe(true)+ expect(isRetryableFetchError(error, false)).toBe(true)+ }+ )++ test.each([...Object.entries(terminated), ...Object.entries(opaque)])(+ 'retries %s only for a replayable operation',+ (_, error) => {+ expect(isRetryableFetchError(error, true)).toBe(true)+ expect(isRetryableFetchError(error, false)).toBe(false)+ }+ )++ test.each([...Object.entries(aborts), ['non-error', 'ECONNREFUSED']])(+ 'never retries %s',+ (_, error) => {+ expect(isRetryableFetchError(error, true)).toBe(false)+ expect(isRetryableFetchError(error, false)).toBe(false)+ }+ )+})++const nonReplayable = [+ ['POST', '/sandboxes'],+ ['POST', '/v2/sandboxes'],+ ['POST', '/sandboxes/sbx-1/fork'],+ ['POST', '/sandboxes/sbx-1/snapshots'],+ ['POST', '/api-keys'],+ ['POST', '/admin/teams/team-1/api-keys'],+ ['POST', '/volumes'],+ ['POST', '/secrets'],+ ['POST', '/events/webhooks'],+ // POSTs not on the allowlist: unknown and near-miss paths+ ['POST', '/sandboxes/sbx-1/pause/extra'],+ ['POST', '/sandboxes/a/b/pause'],+ ['POST', '/templates/tags/extra'],+ ['POST', '/new-resources'],+]++const replayable = [+ ['GET', '/sandboxes'],+ ['GET', '/sandboxes/sbx-1'],+ ['DELETE', '/sandboxes/sbx-1'],+ ['POST', '/sandboxes/sbx-1/pause'],+ ['POST', '/sandboxes/sbx-1/resume'],+ ['POST', '/sandboxes/sbx-1/connect'],+ ['POST', '/v2/sandboxes/sbx-1/connect'],+ ['POST', '/sandboxes/sbx-1/timeout'],+ ['POST', '/sandboxes/sbx-1/refreshes'],+ ['PUT', '/sandboxes/sbx-1/network'],+ ['PATCH', '/templates/tpl-1'],+ ['POST', '/v3/templates'],+ ['POST', '/v2/templates/tpl-1/builds/build-1'],+ ['POST', '/templates/tags'],+ ['DELETE', '/templates/tags'],+ ['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'],+]++describe('isReplayable', () => {+ test.each(nonReplayable)('%s %s is not replayable', (method, path) => {+ const request = new Request(`https://api.e2b.test${path}?x=1`, { method })+ expect(isReplayable(request)).toBe(false)+ })++ test.each(replayable)('%s %s is replayable', (method, path) => {+ const request = new Request(`https://api.e2b.test${path}?x=1`, { method })+ expect(isReplayable(request)).toBe(true)+ })+})++test('retries a connection failure with exponential backoff', async () => {+ const outcomes = [+ () => Promise.reject(connectError('ECONNREFUSED')),+ () => Promise.reject(connectError('ENOTFOUND', 'getaddrinfo')),+ () => Promise.resolve(new Response('ok')),+ ]+ const fetchImpl = vi.fn(() => outcomes.shift()!()) as typeof fetch+ const sleep = vi.fn(async () => {})+ const fetchWithRetry = withRetry(fetchImpl, 3, 60_000, {+ monotonic: () => 0,+ sleep,+ random: () => 1,+ })++ const response = await fetchWithRetry('https://api.e2b.test/sandboxes', {+ method: 'POST',+ body: 'payload',+ })++ expect(response.status).toBe(200)+ expect(fetchImpl).toHaveBeenCalledTimes(3)+ expect(sleep.mock.calls.map(([delayMs]) => delayMs)).toEqual([100, 200])+ const bodies = await Promise.all(+ fetchImpl.mock.calls.map(([request]) => (request as Request).text())+ )+ expect(bodies).toEqual(['payload', 'payload', 'payload'])+})++test('rethrows the connection failure after exhausting retries', async () => {+ const error = connectError('ECONNREFUSED')+ const fetchImpl = vi.fn(async () => {+ throw error+ }) as typeof fetch+ const fetchWithRetry = withRetry(fetchImpl, 2, 10_000, {+ monotonic: () => 0,+ sleep: async () => {},+ })++ await expect(fetchWithRetry('https://api.e2b.test/resource')).rejects.toBe(+ error+ )+ expect(fetchImpl).toHaveBeenCalledTimes(3)+})++test('rethrows a connection failure when the backoff would exceed the request timeout', async () => {+ const error = connectError('ECONNREFUSED')+ const fetchImpl = vi.fn(async () => {+ throw error+ }) as typeof fetch+ const sleep = vi.fn(async () => {})+ const fetchWithRetry = withRetry(fetchImpl, 3, 80, {+ monotonic: () => 0,+ sleep,+ random: () => 1,+ })++ await expect(fetchWithRetry('https://api.e2b.test/resource')).rejects.toBe(+ error+ )+ expect(fetchImpl).toHaveBeenCalledOnce()+ expect(sleep).not.toHaveBeenCalled()+})++test.each([+ ['GET', '/sandboxes'],+ ['POST', '/sandboxes/sbx-1/pause'],+ ['DELETE', '/sandboxes/sbx-1'],+])('retries an opaque network error for %s %s', async (method, path) => {+ const outcomes = [+ () => Promise.reject(opaque.Chrome),+ () => Promise.reject(terminated['Node reset']),+ () => Promise.resolve(new Response('ok')),+ ]+ const fetchImpl = vi.fn(() => outcomes.shift()!()) as typeof fetch+ const sleep = vi.fn(async () => {})+ const fetchWithRetry = withRetry(fetchImpl, 3, 60_000, {+ monotonic: () => 0,+ sleep,+ random: () => 1,+ })++ const response = await fetchWithRetry(`https://api.e2b.test${path}`, {+ method,+ })++ expect(response.status).toBe(200)+ expect(fetchImpl).toHaveBeenCalledTimes(3)+ expect(sleep.mock.calls.map(([delayMs]) => delayMs)).toEqual([100, 200])+})++test.each([+ ['opaque network error', opaque.Chrome, 'POST', '/sandboxes'],+ ['dropped connection', terminated['Node reset'], 'POST', '/v2/sandboxes'],+ [+ 'dropped connection',+ terminated['Cloudflare Workers'],+ 'POST',+ '/sandboxes/sbx-1/fork',+ ],+ ['abort', aborts.abort, 'GET', '/sandboxes'],+])('does not retry %s for %s %s', async (_, error, method, path) => {+ const fetchImpl = vi.fn(async () => {+ throw error+ }) as typeof fetch+ const fetchWithRetry = withRetry(fetchImpl, 3, 10_000, {+ monotonic: () => 0,+ sleep: async () => {},+ })++ await expect(+ fetchWithRetry(`https://api.e2b.test${path}`, { method })+ ).rejects.toBe(error)+ expect(fetchImpl).toHaveBeenCalledOnce()+})++test('does not retry a GET whose signal was aborted', async () => {+ const controller = new AbortController()+ const reason = new Error('cancelled by caller')+ const fetchImpl = vi.fn(async () => {+ controller.abort(reason)+ throw reason+ }) as typeof fetch+ const fetchWithRetry = withRetry(fetchImpl, 3, 10_000, {+ monotonic: () => 0,+ sleep: async () => {},+ })++ await expect(+ fetchWithRetry('https://api.e2b.test/resource', {+ signal: controller.signal,+ })+ ).rejects.toBe(reason)+ expect(fetchImpl).toHaveBeenCalledOnce()+})++test('retries=0 propagates a connection failure unchanged', async () => {+ const error = connectError('ECONNREFUSED')+ const fetchImpl = vi.fn(async () => {+ throw error+ }) as typeof fetch+ const fetchWithRetry = withRetry(fetchImpl, 0, 10_000)++ await expect(fetchWithRetry('https://api.e2b.test/resource')).rejects.toBe(+ error+ )+ expect(fetchImpl).toHaveBeenCalledOnce()+})diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.pyindex 7745080b2..a48983d05 100644--- a/packages/python-sdk/e2b/connection_config.py+++ b/packages/python-sdk/e2b/connection_config.py@@ -51,9 +51,17 @@ class ApiParams(TypedDict, total=False):"""Timeout for the request in **seconds**, defaults to 60 seconds."""retries: Optional[int]- """Number of control-plane HTTP retries after a 429 with a valid,- non-negative integer delta-seconds ``Retry-After`` header. HTTP-date and- malformed values are not retried.+ """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+ establish the connection are retried separately for every operation, see+ ``E2B_CONNECTION_RETRIES``.+ 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 and+ network errors use exponential backoff with jitter starting at 0.1 seconds+ (capped at 10 seconds).A retry is skipped when its wait would exhaust the request timeout.Retry waits use a 60-second total limit when request timeouts are disabled.Set to ``0`` to disable retries. Defaults to 3 retries.diff --git a/packages/python-sdk/e2b/retry.py b/packages/python-sdk/e2b/retry.pyindex 6761aa2c2..dd5e8d410 100644--- a/packages/python-sdk/e2b/retry.py+++ b/packages/python-sdk/e2b/retry.py@@ -1,6 +1,8 @@import asyncio+import random+import reimport time-from typing import Awaitable, Callable, Optional+from typing import Awaitable, Callable, List, Optional, Tupleimport httpx@@ -8,6 +10,37 @@ from e2b.exceptions import InvalidArgumentExceptionMAX_RETRY_AFTER_SECONDS = 2_147_483_647MAX_RETRY_WAIT_WITHOUT_TIMEOUT_SECONDS = 60.0+BACKOFF_BASE_SECONDS = 0.1+BACKOFF_MAX_SECONDS = 10.0+BACKOFF_JITTER_MIN = 0.5+RETRYABLE_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+# failures are retried for every operation by ``ConnectionRetryTransport``+# underneath: the request never left.)+REPLAYABLE_METHODS = frozenset({"GET", "PUT", "PATCH", "DELETE"})+REPLAYABLE_OPERATIONS: List[Tuple[str, re.Pattern[str]]] = [+ ("POST", re.compile(r"^/sandboxes/[^/]+/(pause|resume|timeout|refreshes)$")),+ ("POST", re.compile(r"^/(v2/)?sandboxes/[^/]+/connect$")),+ ("POST", re.compile(r"^/v3/templates$")),+ ("POST", re.compile(r"^/v2/templates/[^/]+/builds/[^/]+$")),+ ("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)+# written: the connection dropped while sending it or awaiting the response.+# ``httpx.ConnectError``/``ConnectTimeout`` are excluded — the connection layer+# already retries those — as are timeouts, which exhaust the request's budget.+NETWORK_ERRORS = (httpx.ReadError, httpx.WriteError, httpx.RemoteProtocolError)def resolve_max_retries(retries: int) -> int:@@ -29,6 +62,42 @@ def parse_retry_after(value: Optional[str]) -> Optional[int]:return delay if delay <= MAX_RETRY_AFTER_SECONDS else None+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``)."""+ if request.method in REPLAYABLE_METHODS:+ return True+ path = request.url.path+ return any(+ request.method == method and pattern.match(path)+ for method, pattern in REPLAYABLE_OPERATIONS+ )+++def _backoff_delay(attempt: int, random_: Callable[[], float]) -> float:+ backoff = min(BACKOFF_BASE_SECONDS * 2**attempt, BACKOFF_MAX_SECONDS)+ return backoff * (BACKOFF_JITTER_MIN + random_() * (1 - BACKOFF_JITTER_MIN))+++def _retry_delay(+ response: httpx.Response, attempt: int, random_: Callable[[], float]+) -> Optional[float]:+ """Delay before the next attempt, or ``None`` 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."""+ if response.status_code not in RETRYABLE_STATUSES:+ return None++ retry_after = parse_retry_after(response.headers.get("Retry-After"))+ if retry_after is not None:+ return float(retry_after)+ if response.status_code == 429:+ return None++ return _backoff_delay(attempt, random_)++def _copy_request(request: httpx.Request, remaining_timeout: Optional[float] = None) -> httpx.Request:@@ -64,19 +133,24 @@ def _request_deadline(request: httpx.Request, monotonic: Callable[[], float]) ->class RetryableTransport(httpx.BaseTransport):- """Retry replayable requests after a 429 carrying ``Retry-After``."""+ """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."""def __init__(self,transport: httpx.BaseTransport,retries: int,+ *,sleep: Callable[[float], None] = time.sleep,monotonic: Callable[[], float] = time.monotonic,+ random_: Callable[[], float] = random.random,):self.transport = transportself.retries = retriesself._sleep = sleepself._monotonic = monotonic+ self._random = random_def handle_request(self, request: httpx.Request) -> httpx.Response:# Iterators, files, and other streaming bodies may be consumed by the@@ -86,30 +160,38 @@ class RetryableTransport(httpx.BaseTransport):request.read()deadline = _request_deadline(request, self._monotonic)+ replayable = is_replayable(request)for attempt in range(self.retries + 1):remaining_timeout = Noneif attempt > 0:remaining_timeout = deadline - self._monotonic()if remaining_timeout <= 0:raise httpx.TimeoutException(- "Request timed out while waiting to retry a rate-limited "- "request. Increase `request_timeout` or lower `retries`.",+ "Request timed out while waiting to retry. "+ "Increase `request_timeout` or lower `retries`.",request=request,)- response = self.transport.handle_request(- _copy_request(request, remaining_timeout)- )- retry_after = parse_retry_after(response.headers.get("Retry-After"))- if (- response.status_code != 429- or retry_after is None- or attempt == self.retries- or (self._monotonic() + retry_after >= deadline)- ):+ try:+ response = self.transport.handle_request(+ _copy_request(request, remaining_timeout)+ )+ except NETWORK_ERRORS:+ if attempt == self.retries or not replayable:+ raise+ delay = _backoff_delay(attempt, self._random)+ if self._monotonic() + delay >= deadline:+ raise+ self._sleep(delay)+ continue+ if attempt == self.retries:+ return response++ delay = _retry_delay(response, attempt, self._random)+ if delay is None or self._monotonic() + delay >= deadline:return responseresponse.close()- self._sleep(retry_after)+ self._sleep(delay)raise AssertionError("unreachable")@@ -125,13 +207,16 @@ class AsyncRetryableTransport(httpx.AsyncBaseTransport):self,transport: httpx.AsyncBaseTransport,retries: int,+ *,sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,monotonic: Callable[[], float] = time.monotonic,+ random_: Callable[[], float] = random.random,):self.transport = transportself.retries = retriesself._sleep = sleepself._monotonic = monotonic+ self._random = random_async def handle_async_request(self, request: httpx.Request) -> httpx.Response:# Iterators, files, and other streaming bodies may be consumed by the@@ -141,30 +226,38 @@ class AsyncRetryableTransport(httpx.AsyncBaseTransport):await request.aread()deadline = _request_deadline(request, self._monotonic)+ replayable = is_replayable(request)for attempt in range(self.retries + 1):remaining_timeout = Noneif attempt > 0:remaining_timeout = deadline - self._monotonic()if remaining_timeout <= 0:raise httpx.TimeoutException(- "Request timed out while waiting to retry a rate-limited "- "request. Increase `request_timeout` or lower `retries`.",+ "Request timed out while waiting to retry. "+ "Increase `request_timeout` or lower `retries`.",request=request,)- response = await self.transport.handle_async_request(- _copy_request(request, remaining_timeout)- )- retry_after = parse_retry_after(response.headers.get("Retry-After"))- if (- response.status_code != 429- or retry_after is None- or attempt == self.retries- or (self._monotonic() + retry_after >= deadline)- ):+ try:+ response = await self.transport.handle_async_request(+ _copy_request(request, remaining_timeout)+ )+ except NETWORK_ERRORS:+ if attempt == self.retries or not replayable:+ raise+ delay = _backoff_delay(attempt, self._random)+ if self._monotonic() + delay >= deadline:+ raise+ await self._sleep(delay)+ continue+ if attempt == self.retries:+ return response++ delay = _retry_delay(response, attempt, self._random)+ if delay is None or self._monotonic() + delay >= deadline:return responseawait response.aclose()- await self._sleep(retry_after)+ await self._sleep(delay)raise AssertionError("unreachable")diff --git a/packages/python-sdk/tests/test_rate_limit_retry_transport.py b/packages/python-sdk/tests/test_rate_limit_retry_transport.pyindex fffdba7c4..481c1f8a4 100644--- a/packages/python-sdk/tests/test_rate_limit_retry_transport.py+++ b/packages/python-sdk/tests/test_rate_limit_retry_transport.py@@ -1,12 +1,17 @@import httpximport pytest-from e2b.retry import AsyncRetryableTransport, RetryableTransport, parse_retry_after+from e2b.retry import (+ AsyncRetryableTransport,+ RetryableTransport,+ is_replayable,+ parse_retry_after,+)class FakeTransport(httpx.BaseTransport):- def __init__(self, statuses, retry_after="0"):- self.statuses = iter(statuses)+ def __init__(self, outcomes, retry_after="0"):+ self.outcomes = iter(outcomes)self.retry_after = retry_afterself.requests = []self.responses = []@@ -14,8 +19,11 @@ class FakeTransport(httpx.BaseTransport):def handle_request(self, request):self.requests.append(request)+ outcome = next(self.outcomes)+ if isinstance(outcome, Exception):+ raise outcomeresponse = httpx.Response(- next(self.statuses),+ outcome,headers={"Retry-After": self.retry_after} if self.retry_after else {},content=b"response",request=request,@@ -28,8 +36,8 @@ class FakeTransport(httpx.BaseTransport):class FakeAsyncTransport(httpx.AsyncBaseTransport):- def __init__(self, statuses, retry_after="0"):- self.statuses = iter(statuses)+ def __init__(self, outcomes, retry_after="0"):+ self.outcomes = iter(outcomes)self.retry_after = retry_afterself.requests = []self.responses = []@@ -37,8 +45,11 @@ class FakeAsyncTransport(httpx.AsyncBaseTransport):async def handle_async_request(self, request):self.requests.append(request)+ outcome = next(self.outcomes)+ if isinstance(outcome, Exception):+ raise outcomeresponse = httpx.Response(- next(self.statuses),+ outcome,headers={"Retry-After": self.retry_after} if self.retry_after else {},content=b"response",request=request,@@ -152,17 +163,107 @@ def test_retry_wait_is_bounded_when_request_timeout_is_disabled():assert sleeps == []-def test_does_not_retry_other_status_codes():- inner = FakeTransport([503], retry_after="0")[email protected]("status", [400, 404, 500, 504])+def test_does_not_retry_other_status_codes(status):+ inner = FakeTransport([status], retry_after="0")response = RetryableTransport(inner, retries=3).handle_request(httpx.Request("GET", "https://api.test"))- assert response.status_code == 503+ assert response is inner.responses[0]assert len(inner.requests) == 1[email protected]("status", [502, 503])+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")++ response = RetryableTransport(+ inner,+ retries=3,+ sleep=sleeps.append,+ monotonic=lambda: 0.0,+ random_=lambda: next(randoms),+ ).handle_request(request)++ assert response.status_code == 200+ assert sleeps == pytest.approx([0.05, 0.2, 0.3])+ assert [item.content for item in inner.requests] == [b"payload"] * 4+ assert all(item.is_closed for item in inner.responses[:-1])+++def test_backoff_is_capped_for_long_retry_sequences():+ inner = FakeTransport([503] * 9, retry_after=None)+ sleeps = []+ request = httpx.Request(+ "GET",+ "https://api.test",+ extensions={"timeout": {"connect": None, "read": None}},+ )++ RetryableTransport(+ inner,+ retries=8,+ sleep=sleeps.append,+ monotonic=lambda: 0.0,+ random_=lambda: 1.0,+ ).handle_request(request)++ assert sleeps == pytest.approx([0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 6.4, 10.0])+++def test_unavailable_status_prefers_retry_after_over_backoff():+ inner = FakeTransport([503, 200], retry_after="3")+ sleeps = []++ def random_():+ raise AssertionError("backoff should not be used")++ response = RetryableTransport(+ inner, retries=3, sleep=sleeps.append, random_=random_+ ).handle_request(httpx.Request("GET", "https://api.test"))++ assert response.status_code == 200+ assert sleeps == [3]+++def test_unavailable_status_exhaustion_returns_final_response():+ inner = FakeTransport([503, 503, 503], retry_after=None)++ response = RetryableTransport(+ inner, retries=2, sleep=lambda _: None, random_=lambda: 0.0+ ).handle_request(httpx.Request("GET", "https://api.test"))++ assert response is inner.responses[-1]+ assert len(inner.requests) == 3+ assert response.content == b"response"+++def test_backoff_exceeding_timeout_is_propagated_as_is():+ inner = FakeTransport([502], retry_after=None)+ sleeps = []+ request = httpx.Request(+ "GET",+ "https://api.test",+ extensions={"timeout": {"connect": 0.08, "read": 0.08}},+ )++ response = RetryableTransport(+ inner,+ retries=3,+ sleep=sleeps.append,+ monotonic=lambda: 0.0,+ random_=lambda: 1.0,+ ).handle_request(request)++ assert response is inner.responses[0]+ assert sleeps == []++def test_does_not_retry_when_cumulative_wait_reaches_request_timeout():inner = FakeTransport([429, 429], retry_after="2")clock = FakeClock()@@ -300,6 +401,149 @@ def test_close_leaves_cached_transport_open():assert not inner.closed+NON_REPLAYABLE = [+ ("POST", "/sandboxes"),+ ("POST", "/v2/sandboxes"),+ ("POST", "/sandboxes/sbx-1/fork"),+ ("POST", "/sandboxes/sbx-1/snapshots"),+ ("POST", "/api-keys"),+ ("POST", "/admin/teams/team-1/api-keys"),+ ("POST", "/volumes"),+ ("POST", "/secrets"),+ ("POST", "/events/webhooks"),+ # POSTs not on the allowlist: unknown and near-miss paths+ ("POST", "/sandboxes/sbx-1/pause/extra"),+ ("POST", "/sandboxes/a/b/pause"),+ ("POST", "/templates/tags/extra"),+ ("POST", "/new-resources"),+]++REPLAYABLE = [+ ("GET", "/sandboxes"),+ ("GET", "/sandboxes/sbx-1"),+ ("DELETE", "/sandboxes/sbx-1"),+ ("POST", "/sandboxes/sbx-1/pause"),+ ("POST", "/sandboxes/sbx-1/resume"),+ ("POST", "/sandboxes/sbx-1/connect"),+ ("POST", "/v2/sandboxes/sbx-1/connect"),+ ("POST", "/sandboxes/sbx-1/timeout"),+ ("POST", "/sandboxes/sbx-1/refreshes"),+ ("PUT", "/sandboxes/sbx-1/network"),+ ("PATCH", "/templates/tpl-1"),+ ("POST", "/v3/templates"),+ ("POST", "/v2/templates/tpl-1/builds/build-1"),+ ("POST", "/templates/tags"),+ ("DELETE", "/templates/tags"),+ ("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"),+]++NETWORK_ERRORS = [+ httpx.ReadError("connection reset"),+ httpx.WriteError("broken pipe"),+ httpx.RemoteProtocolError("stream reset"),+]++[email protected](("method", "path"), NON_REPLAYABLE)+def test_unlisted_posts_are_not_replayable(method, path):+ assert not is_replayable(httpx.Request(method, f"https://api.test{path}?x=1"))++[email protected](("method", "path"), REPLAYABLE)+def test_other_operations_are_replayable(method, path):+ assert is_replayable(httpx.Request(method, f"https://api.test{path}?x=1"))++[email protected](("method", "path"), REPLAYABLE[:5])+def test_retries_network_error_for_replayable_operation(method, path):+ inner = FakeTransport([NETWORK_ERRORS[0], NETWORK_ERRORS[2], 200])+ sleeps = []++ response = RetryableTransport(+ inner,+ retries=3,+ sleep=sleeps.append,+ monotonic=lambda: 0.0,+ random_=lambda: 1.0,+ ).handle_request(httpx.Request(method, f"https://api.test{path}", content=b"p"))++ assert response.status_code == 200+ assert sleeps == pytest.approx([0.1, 0.2])+ assert [item.content for item in inner.requests] == [b"p"] * 3++[email protected]("error", NETWORK_ERRORS)[email protected](("method", "path"), NON_REPLAYABLE[:3])+def test_does_not_retry_network_error_for_non_replayable_operation(error, method, path):+ inner = FakeTransport([error, 200])++ with pytest.raises(type(error)):+ RetryableTransport(inner, retries=3, sleep=lambda _: None).handle_request(+ httpx.Request(method, f"https://api.test{path}", content=b"p")+ )++ assert len(inner.requests) == 1+++ "error",+ [+ httpx.ConnectError("refused"),+ httpx.ConnectTimeout("timed out"),+ httpx.ReadTimeout("timed out"),+ httpx.LocalProtocolError("bad request"),+ ],+)+def test_leaves_connect_errors_and_timeouts_to_the_layers_around(error):+ inner = FakeTransport([error, 200])++ with pytest.raises(type(error)):+ RetryableTransport(inner, retries=3, sleep=lambda _: None).handle_request(+ httpx.Request("GET", "https://api.test/sandboxes")+ )++ assert len(inner.requests) == 1+++def test_rethrows_network_error_after_exhausting_retries():+ inner = FakeTransport([httpx.ReadError("reset")] * 3)++ with pytest.raises(httpx.ReadError):+ RetryableTransport(+ inner, retries=2, sleep=lambda _: None, monotonic=lambda: 0.0+ ).handle_request(httpx.Request("GET", "https://api.test/sandboxes"))++ assert len(inner.requests) == 3+++def test_rethrows_network_error_when_backoff_would_exceed_request_timeout():+ inner = FakeTransport([httpx.ReadError("reset"), 200])+ sleeps = []++ with pytest.raises(httpx.ReadError):+ RetryableTransport(+ inner,+ retries=3,+ sleep=sleeps.append,+ monotonic=lambda: 0.0,+ random_=lambda: 1.0,+ ).handle_request(+ httpx.Request(+ "GET",+ "https://api.test/sandboxes",+ extensions={"timeout": {"connect": 0.08, "read": 0.08}},+ )+ )++ assert len(inner.requests) == 1+ assert sleeps == []++@pytest.mark.asyncioasync def test_async_retries_rate_limit_and_replays_body():inner = FakeAsyncTransport([429, 200], retry_after="2")@@ -367,6 +611,44 @@ async def test_async_timeout_after_retry_wait_names_configuration_options():).handle_async_request(request)+async def test_async_retries_unavailable_status_with_backoff():+ inner = FakeAsyncTransport([503, 502, 200], retry_after=None)+ sleeps = []+ randoms = iter([0.0, 1.0])++ async def sleep(delay):+ sleeps.append(delay)++ response = await AsyncRetryableTransport(+ inner,+ retries=3,+ sleep=sleep,+ monotonic=lambda: 0.0,+ random_=lambda: next(randoms),+ ).handle_async_request(+ httpx.Request("POST", "https://api.test", content=b"payload")+ )++ assert response.status_code == 200+ assert sleeps == pytest.approx([0.05, 0.2])+ assert [item.content for item in inner.requests] == [b"payload"] * 3+ assert all(item.is_closed for item in inner.responses[:-1])++[email protected]("status", [400, 404, 500, 504])+async def test_async_does_not_retry_other_status_codes(status):+ inner = FakeAsyncTransport([status], retry_after="0")++ response = await AsyncRetryableTransport(inner, retries=3).handle_async_request(+ httpx.Request("GET", "https://api.test")+ )++ assert response is inner.responses[0]+ assert len(inner.requests) == 1++@pytest.mark.asyncioasync def test_async_429_without_retry_after_is_propagated_as_is():inner = FakeAsyncTransport([429], retry_after=None)@@ -532,6 +814,66 @@ async def test_async_close_leaves_cached_transport_open():assert not inner.closed[email protected](("method", "path"), REPLAYABLE[:5])+async def test_async_retries_network_error_for_replayable_operation(method, path):+ inner = FakeAsyncTransport([NETWORK_ERRORS[0], NETWORK_ERRORS[2], 200])+ sleeps = []++ async def sleep(delay):+ sleeps.append(delay)++ response = await AsyncRetryableTransport(+ inner,+ retries=3,+ sleep=sleep,+ monotonic=lambda: 0.0,+ random_=lambda: 1.0,+ ).handle_async_request(+ httpx.Request(method, f"https://api.test{path}", content=b"p")+ )++ assert response.status_code == 200+ assert sleeps == pytest.approx([0.1, 0.2])+ assert [item.content for item in inner.requests] == [b"p"] * 3++[email protected]("error", NETWORK_ERRORS)[email protected](("method", "path"), NON_REPLAYABLE[:3])+async def test_async_does_not_retry_network_error_for_non_replayable_operation(+ error, method, path+):+ inner = FakeAsyncTransport([error, 200])++ async def sleep(_):+ pass++ with pytest.raises(type(error)):+ await AsyncRetryableTransport(+ inner, retries=3, sleep=sleep+ ).handle_async_request(+ httpx.Request(method, f"https://api.test{path}", content=b"p")+ )++ assert len(inner.requests) == 1+++async def test_async_rethrows_network_error_after_exhausting_retries():+ inner = FakeAsyncTransport([httpx.ReadError("reset")] * 3)++ async def sleep(_):+ pass++ with pytest.raises(httpx.ReadError):+ await AsyncRetryableTransport(+ inner, retries=2, sleep=sleep, monotonic=lambda: 0.0+ ).handle_async_request(httpx.Request("GET", "https://api.test/sandboxes"))++ assert len(inner.requests) == 3++@pytest.mark.parametrize(("value", "expected"),[