Skip to content

armgit / E2B

Public Imported from GitHub
0

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

fix(sdks): stabilize CI diagnostics and readiness checks (#1794)

Matt Brockmanba1587f865fe
diff --git a/.changeset/quiet-desktops-wait.md b/.changeset/quiet-desktops-wait.md
new file mode 100644
index 000000000..67e9511d5
--- /dev/null
+++ b/.changeset/quiet-desktops-wait.md
@@ -0,0 +1,6 @@
+---
+'@e2b/desktop': patch
+'@e2b/desktop-python': patch
+---
+
+Wait for the XFCE session to be fully ready before returning a new Desktop sandbox, and clean up the sandbox if desktop startup fails.
diff --git a/.github/workflows/cli_tests.yml b/.github/workflows/cli_tests.yml
index a5c8bb5fc..062ebde3e 100644
--- a/.github/workflows/cli_tests.yml
+++ b/.github/workflows/cli_tests.yml
@@ -14,6 +14,9 @@ on:
permissions:
contents: read
+env:
+ E2B_USER_AGENT_SOURCE: ci
+
jobs:
test:
defaults:
diff --git a/.github/workflows/code_interpreter_js_tests.yml b/.github/workflows/code_interpreter_js_tests.yml
index 9b3dcc21d..e7c45b8c6 100644
--- a/.github/workflows/code_interpreter_js_tests.yml
+++ b/.github/workflows/code_interpreter_js_tests.yml
@@ -23,6 +23,9 @@ on:
permissions:
contents: read
+env:
+ E2B_USER_AGENT_SOURCE: ci
+
jobs:
test:
defaults:
@@ -32,6 +35,9 @@ jobs:
name: Code Interpreter JS SDK - ${{ matrix.runtime }}
strategy:
fail-fast: false
+ # Each runtime keeps one live-test worker. This matrix has four legs, so
+ # it naturally stays below the shared six-job cap.
+ max-parallel: 6
# With node-only (set by staging callers) the matrix collapses to the
# Node leg: the other legs re-run the suite the Node leg already covers
# and add sandbox load without extra backend signal, so the other
@@ -83,6 +89,8 @@ jobs:
- name: Install Bun
if: matrix.runtime == 'bun'
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
+ with:
+ bun-version: '${{ env.TOOL_VERSION_BUN }}'
- name: Install Deno
if: matrix.runtime == 'deno'
@@ -107,3 +115,6 @@ jobs:
env:
E2B_API_KEY: ${{ secrets.E2B_API_KEY }}
E2B_DOMAIN: ${{ inputs.E2B_DOMAIN }}
+ # Keep one live-sandbox worker per runtime; matrix parallelism is
+ # bounded separately above.
+ E2B_TEST_MAX_WORKERS: 1
diff --git a/.github/workflows/code_interpreter_python_tests.yml b/.github/workflows/code_interpreter_python_tests.yml
index f04af990f..9d30b4115 100644
--- a/.github/workflows/code_interpreter_python_tests.yml
+++ b/.github/workflows/code_interpreter_python_tests.yml
@@ -18,6 +18,9 @@ on:
permissions:
contents: read
+env:
+ E2B_USER_AGENT_SOURCE: ci
+
jobs:
test:
defaults:
@@ -53,9 +56,9 @@ jobs:
- name: Run tests
run: |
if [[ "${{ inputs.run_recovery_tests }}" == "true" ]]; then
- uv run pytest --verbose --numprocesses=4
+ uv run pytest --verbose --numprocesses=1
else
- uv run pytest --verbose --numprocesses=4 \
+ uv run pytest --verbose --numprocesses=1 \
--ignore=tests/async/test_async_interrupt.py \
--ignore=tests/async/test_async_systemd.py \
--ignore=tests/sync/test_interrupt.py \
diff --git a/.github/workflows/desktop_js_tests.yml b/.github/workflows/desktop_js_tests.yml
index c02018655..79fb992a0 100644
--- a/.github/workflows/desktop_js_tests.yml
+++ b/.github/workflows/desktop_js_tests.yml
@@ -18,6 +18,9 @@ on:
permissions:
contents: read
+env:
+ E2B_USER_AGENT_SOURCE: ci
+
jobs:
test:
defaults:
@@ -27,6 +30,9 @@ jobs:
name: Desktop JS SDK - ${{ inputs.run_tests && matrix.runtime || 'build' }}
strategy:
fail-fast: false
+ # Each runtime keeps one live-test worker. This matrix has four legs, so
+ # it naturally stays below the shared six-job cap.
+ max-parallel: 6
# Callers that only build (staging) collapse the matrix to a single job;
# the runtime legs are exercised against production.
matrix:
@@ -76,6 +82,8 @@ jobs:
- name: Install Bun
if: inputs.run_tests && matrix.runtime == 'bun'
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
+ with:
+ bun-version: '${{ env.TOOL_VERSION_BUN }}'
- name: Install Deno
if: inputs.run_tests && matrix.runtime == 'deno'
@@ -97,3 +105,4 @@ jobs:
env:
E2B_API_KEY: ${{ secrets.E2B_API_KEY }}
E2B_DOMAIN: ${{ inputs.E2B_DOMAIN }}
+ E2B_TEST_MAX_WORKERS: 1
diff --git a/.github/workflows/desktop_python_tests.yml b/.github/workflows/desktop_python_tests.yml
index 8861c728d..dae63885a 100644
--- a/.github/workflows/desktop_python_tests.yml
+++ b/.github/workflows/desktop_python_tests.yml
@@ -18,6 +18,9 @@ on:
permissions:
contents: read
+env:
+ E2B_USER_AGENT_SOURCE: ci
+
jobs:
test:
defaults:
diff --git a/.github/workflows/js_sdk_tests.yml b/.github/workflows/js_sdk_tests.yml
index 3a08f0dcb..885ab9182 100644
--- a/.github/workflows/js_sdk_tests.yml
+++ b/.github/workflows/js_sdk_tests.yml
@@ -19,6 +19,9 @@ on:
permissions:
contents: read
+env:
+ E2B_USER_AGENT_SOURCE: ci
+
jobs:
test:
defaults:
@@ -28,6 +31,9 @@ jobs:
name: JS SDK - ${{ matrix.runtime }} (${{ matrix.os }})
strategy:
fail-fast: false
+ # Each runtime keeps one live-test worker, so all six runtime/OS jobs can
+ # run together without restoring Vitest's default worker multiplication.
+ max-parallel: 6
# With node-only (set by staging callers) the matrix collapses to the
# Node legs: the Bun/Deno/Cloudflare legs re-run suites the Node legs
# already cover and add sandbox/build load without extra backend
@@ -38,6 +44,8 @@ jobs:
&& fromJSON('[{"runtime": "node", "os": "ubuntu-22.04"}, {"runtime": "node", "os": "windows-latest"}]')
|| fromJSON('[{"runtime": "node", "os": "ubuntu-22.04"}, {"runtime": "node", "os": "windows-latest"}, {"runtime": "bun", "os": "ubuntu-22.04"}, {"runtime": "deno", "os": "ubuntu-22.04"}, {"runtime": "cloudflare", "os": "ubuntu-22.04"}, {"runtime": "cloudflare-deploy", "os": "ubuntu-22.04"}]') }}
runs-on: ${{ matrix.os }}
+ env:
+ E2B_TEST_MAX_WORKERS: 1
# The cloudflare-deploy leg is advisory: it deploys to a brand-new
# Cloudflare preview account on every run, so it inherits that account's
# propagation and read-after-write races (the fresh workers.dev subdomain
@@ -115,6 +123,8 @@ jobs:
- name: Install Bun
if: matrix.runtime == 'bun'
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
+ with:
+ bun-version: '${{ env.TOOL_VERSION_BUN }}'
- name: Run test suite under Bun
if: matrix.runtime == 'bun'
diff --git a/.github/workflows/python_sdk_tests.yml b/.github/workflows/python_sdk_tests.yml
index 741d24246..a22b93d0f 100644
--- a/.github/workflows/python_sdk_tests.yml
+++ b/.github/workflows/python_sdk_tests.yml
@@ -14,6 +14,9 @@ on:
permissions:
contents: read
+env:
+ E2B_USER_AGENT_SOURCE: ci
+
jobs:
test:
defaults:
diff --git a/.tool-versions b/.tool-versions
index 8cb195538..dcaa7775a 100644
--- a/.tool-versions
+++ b/.tool-versions
@@ -1,3 +1,4 @@
+bun 1.3.14
deno 2.8.1
nodejs 22.18.0
pnpm 10.34.5
diff --git a/packages/code-interpreter-js/src/messaging.ts b/packages/code-interpreter-js/src/messaging.ts
index 5f1e4e2ce..3bf67261f 100644
--- a/packages/code-interpreter-js/src/messaging.ts
+++ b/packages/code-interpreter-js/src/messaging.ts
@@ -1,20 +1,35 @@
import { NotFoundError, SandboxError, TimeoutError } from 'e2b'
import { ChartTypes } from './charts'
-export async function extractError(res: Response) {
+export async function extractError(res: Response, includeDiagnostics = false) {
if (res.ok) {
return
}
+ const traceId = includeDiagnostics ? res.headers.get('X-E2B-Trace-ID') : null
+ const traceSuffix = traceId ? ` (trace_id=${traceId})` : ''
+
switch (res.status) {
- case 502:
+ case 502: {
+ const body = await res.text()
return new TimeoutError(
- `${await res.text()}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.`
+ `${body}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.${traceSuffix}`
)
- case 404:
- return new NotFoundError(await res.text())
- default:
- return new SandboxError(`${res.status} ${res.statusText}`)
+ }
+ case 404: {
+ const body = await res.text()
+ return new NotFoundError(`${body}${traceSuffix}`)
+ }
+ default: {
+ if (!includeDiagnostics) {
+ return new SandboxError(`${res.status} ${res.statusText}`)
+ }
+
+ const body = (await res.text()).trim()
+ return new SandboxError(
+ `${res.status} ${res.statusText}${body ? `: ${body}` : ''}${traceSuffix}`
+ )
+ }
}
}
diff --git a/packages/code-interpreter-js/src/sandbox.ts b/packages/code-interpreter-js/src/sandbox.ts
index 00d60c845..1d4910b3d 100644
--- a/packages/code-interpreter-js/src/sandbox.ts
+++ b/packages/code-interpreter-js/src/sandbox.ts
@@ -144,6 +144,20 @@ export class Sandbox extends BaseSandbox {
})
}
+ private getJupyterRequestUrl(path: string): string {
+ const url = `${this.jupyterUrl}${path}`
+ const source = this.connectionConfig.requestSource
+ if (!source) {
+ return url
+ }
+
+ return `${url}${url.includes('?') ? '&' : '?'}source=${encodeURIComponent(source)}`
+ }
+
+ private get includeDiagnostics(): boolean {
+ return this.connectionConfig.requestSource === 'ci'
+ }
+
/**
* Run the code for the specified language.
*
@@ -227,7 +241,7 @@ export class Sandbox extends BaseSandbox {
}
try {
- const res = await fetch(`${this.jupyterUrl}/execute`, {
+ const res = await fetch(this.getJupyterRequestUrl('/execute'), {
method: 'POST',
headers,
body: JSON.stringify({
@@ -240,7 +254,7 @@ export class Sandbox extends BaseSandbox {
keepalive: true,
})
- const error = await extractError(res)
+ const error = await extractError(res, this.includeDiagnostics)
if (error) {
throw error
}
@@ -305,7 +319,7 @@ export class Sandbox extends BaseSandbox {
headers['E2B-Traffic-Access-Token'] = this.trafficAccessToken
}
- const res = await fetch(`${this.jupyterUrl}/contexts`, {
+ const res = await fetch(this.getJupyterRequestUrl('/contexts'), {
method: 'POST',
headers,
body: JSON.stringify({
@@ -316,7 +330,7 @@ export class Sandbox extends BaseSandbox {
signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
})
- const error = await extractError(res)
+ const error = await extractError(res, this.includeDiagnostics)
if (error) {
throw error
}
@@ -347,7 +361,7 @@ export class Sandbox extends BaseSandbox {
headers['E2B-Traffic-Access-Token'] = this.trafficAccessToken
}
- const res = await fetch(`${this.jupyterUrl}/contexts/${id}`, {
+ const res = await fetch(this.getJupyterRequestUrl(`/contexts/${id}`), {
method: 'DELETE',
headers,
keepalive: true,
@@ -356,7 +370,7 @@ export class Sandbox extends BaseSandbox {
),
})
- const error = await extractError(res)
+ const error = await extractError(res, this.includeDiagnostics)
if (error) {
throw error
}
@@ -382,7 +396,7 @@ export class Sandbox extends BaseSandbox {
headers['E2B-Traffic-Access-Token'] = this.trafficAccessToken
}
- const res = await fetch(`${this.jupyterUrl}/contexts`, {
+ const res = await fetch(this.getJupyterRequestUrl('/contexts'), {
method: 'GET',
headers,
keepalive: true,
@@ -391,7 +405,7 @@ export class Sandbox extends BaseSandbox {
),
})
- const error = await extractError(res)
+ const error = await extractError(res, this.includeDiagnostics)
if (error) {
throw error
}
@@ -422,16 +436,19 @@ export class Sandbox extends BaseSandbox {
headers['E2B-Traffic-Access-Token'] = this.trafficAccessToken
}
- const res = await fetch(`${this.jupyterUrl}/contexts/${id}/restart`, {
- method: 'POST',
- headers,
- keepalive: true,
- signal: this.connectionConfig.getSignal(
- this.connectionConfig.requestTimeoutMs
- ),
- })
+ const res = await fetch(
+ this.getJupyterRequestUrl(`/contexts/${id}/restart`),
+ {
+ method: 'POST',
+ headers,
+ keepalive: true,
+ signal: this.connectionConfig.getSignal(
+ this.connectionConfig.requestTimeoutMs
+ ),
+ }
+ )
- const error = await extractError(res)
+ const error = await extractError(res, this.includeDiagnostics)
if (error) {
throw error
}
diff --git a/packages/code-interpreter-js/tests/cwd.test.ts b/packages/code-interpreter-js/tests/cwd.test.ts
index 14b671d4e..683e1e283 100644
--- a/packages/code-interpreter-js/tests/cwd.test.ts
+++ b/packages/code-interpreter-js/tests/cwd.test.ts
@@ -1,6 +1,6 @@
import { expect } from 'vitest'
-import { isDebug, sandboxTest } from './setup'
+import { isDebug, sandboxTest, waitForKernel } from './setup'
// Skip these tests in debug mode — the pwd and user in the testing docker container
// are not the same as in the actual sandbox.
@@ -28,6 +28,8 @@ sandboxTest.skipIf(isDebug)('cwd typescript', async ({ sandbox }) => {
})
sandboxTest.skipIf(isDebug)('cwd r', async ({ sandbox }) => {
+ await waitForKernel(sandbox, 'r')
+
const result = await sandbox.runCode('getwd()', {
language: 'r',
})
@@ -35,6 +37,8 @@ sandboxTest.skipIf(isDebug)('cwd r', async ({ sandbox }) => {
})
sandboxTest.skipIf(isDebug)('cwd java', async ({ sandbox }) => {
+ await waitForKernel(sandbox, 'java')
+
const result = await sandbox.runCode('System.getProperty("user.dir")', {
language: 'java',
})
diff --git a/packages/code-interpreter-js/tests/env_vars/java.test.ts b/packages/code-interpreter-js/tests/env_vars/java.test.ts
index 9e7f4d8ef..a2810cdbf 100644
--- a/packages/code-interpreter-js/tests/env_vars/java.test.ts
+++ b/packages/code-interpreter-js/tests/env_vars/java.test.ts
@@ -1,6 +1,6 @@
import { expect } from 'vitest'
-import { isDebug, sandboxTest } from '../setup'
+import { isDebug, sandboxTest, waitForKernel } from '../setup'
import { Sandbox } from '../../src'
// Java Env Vars
@@ -12,6 +12,8 @@ sandboxTest.skipIf(isDebug)(
})
try {
+ await waitForKernel(sandbox, 'java')
+
const result = await sandbox.runCode(
'System.getProperty("TEST_ENV_VAR")',
{
@@ -27,6 +29,8 @@ sandboxTest.skipIf(isDebug)(
)
sandboxTest('env vars per execution (java)', async ({ sandbox }) => {
+ await waitForKernel(sandbox, 'java')
+
const result = await sandbox.runCode('System.getProperty("FOO")', {
envs: { FOO: 'bar' },
language: 'java',
@@ -49,6 +53,8 @@ sandboxTest.skipIf(isDebug)('env vars overwrite', async ({ template }) => {
})
try {
+ await waitForKernel(sandbox, 'java')
+
const result = await sandbox.runCode('System.getProperty("TEST_ENV_VAR")', {
language: 'java',
envs: { TEST_ENV_VAR: 'overwrite' },
diff --git a/packages/code-interpreter-js/tests/env_vars/r.test.ts b/packages/code-interpreter-js/tests/env_vars/r.test.ts
index 0103fec0e..62ebdef44 100644
--- a/packages/code-interpreter-js/tests/env_vars/r.test.ts
+++ b/packages/code-interpreter-js/tests/env_vars/r.test.ts
@@ -1,6 +1,6 @@
import { expect } from 'vitest'
-import { isDebug, sandboxTest } from '../setup'
+import { isDebug, sandboxTest, waitForKernel } from '../setup'
import { Sandbox } from '../../src'
// R Env Vars
@@ -10,6 +10,8 @@ sandboxTest.skipIf(isDebug)('env vars on sandbox (R)', async ({ template }) => {
})
try {
+ await waitForKernel(sandbox, 'r')
+
const result = await sandbox.runCode('Sys.getenv("TEST_ENV_VAR")', {
language: 'r',
})
@@ -21,6 +23,8 @@ sandboxTest.skipIf(isDebug)('env vars on sandbox (R)', async ({ template }) => {
})
sandboxTest('env vars per execution (R)', async ({ sandbox }) => {
+ await waitForKernel(sandbox, 'r')
+
const result = await sandbox.runCode('Sys.getenv("FOO")', {
envs: { FOO: 'bar' },
language: 'r',
@@ -43,6 +47,8 @@ sandboxTest.skipIf(isDebug)('env vars overwrite', async ({ template }) => {
})
try {
+ await waitForKernel(sandbox, 'r')
+
const result = await sandbox.runCode('Sys.getenv("TEST_ENV_VAR")', {
language: 'r',
envs: { TEST_ENV_VAR: 'overwrite' },
diff --git a/packages/code-interpreter-js/tests/javaKernelReadiness.test.ts b/packages/code-interpreter-js/tests/javaKernelReadiness.test.ts
new file mode 100644
index 000000000..f0470b58d
--- /dev/null
+++ b/packages/code-interpreter-js/tests/javaKernelReadiness.test.ts
@@ -0,0 +1,64 @@
+import { expect, test, vi } from 'vitest'
+
+import { Sandbox, SandboxError } from '../src'
+import { waitForKernel } from './setup'
+
+const javaNotReadyError = () => new SandboxError('500 Internal Server Error')
+const tracedNotReadyError = () =>
+ new SandboxError('500 Internal Server Error (trace_id=trace-123)')
+
+function mockSandbox(runCode: ReturnType<typeof vi.fn>) {
+ return { runCode } as unknown as Sandbox
+}
+
+test.each(['java', 'r'] as const)(
+ 'waits through repeated %s readiness 500s',
+ async (language) => {
+ const runCode = vi
+ .fn()
+ .mockRejectedValueOnce(javaNotReadyError())
+ .mockRejectedValueOnce(javaNotReadyError())
+ .mockRejectedValueOnce(javaNotReadyError())
+ .mockResolvedValueOnce(undefined)
+
+ await waitForKernel(mockSandbox(runCode), language)
+
+ expect(runCode).toHaveBeenCalledTimes(4)
+ expect(runCode).toHaveBeenNthCalledWith(1, '1', { language })
+ expect(runCode).toHaveBeenNthCalledWith(4, '1', { language })
+ }
+)
+
+test('propagates a persistent Java readiness 500', async () => {
+ const finalError = javaNotReadyError()
+ const runCode = vi
+ .fn()
+ .mockRejectedValueOnce(javaNotReadyError())
+ .mockRejectedValueOnce(javaNotReadyError())
+ .mockRejectedValueOnce(javaNotReadyError())
+ .mockRejectedValueOnce(finalError)
+
+ await expect(waitForKernel(mockSandbox(runCode), 'java')).rejects.toBe(
+ finalError
+ )
+ expect(runCode).toHaveBeenCalledTimes(4)
+})
+
+test('does not retry an unrelated Java error', async () => {
+ const error = new SandboxError('401 Unauthorized')
+ const runCode = vi.fn().mockRejectedValueOnce(error)
+
+ await expect(waitForKernel(mockSandbox(runCode), 'java')).rejects.toBe(error)
+ expect(runCode).toHaveBeenCalledTimes(1)
+})
+
+test('retries an empty readiness 500 that includes a trace ID', async () => {
+ const runCode = vi
+ .fn()
+ .mockRejectedValueOnce(tracedNotReadyError())
+ .mockResolvedValueOnce(undefined)
+
+ await waitForKernel(mockSandbox(runCode), 'r')
+
+ expect(runCode).toHaveBeenCalledTimes(2)
+})
diff --git a/packages/code-interpreter-js/tests/messaging.test.ts b/packages/code-interpreter-js/tests/messaging.test.ts
new file mode 100644
index 000000000..40009f893
--- /dev/null
+++ b/packages/code-interpreter-js/tests/messaging.test.ts
@@ -0,0 +1,52 @@
+import { expect, test, vi } from 'vitest'
+
+import { NotFoundError, SandboxError, TimeoutError } from '../src'
+import { extractError } from '../src/messaging'
+
+test('preserves response details and trace ID for CI server errors', async () => {
+ const error = await extractError(
+ new Response('R context failed to initialize', {
+ status: 500,
+ statusText: 'Internal Server Error',
+ headers: { 'X-E2B-Trace-ID': 'trace-123' },
+ }),
+ true
+ )
+
+ expect(error).toEqual(
+ new SandboxError(
+ '500 Internal Server Error: R context failed to initialize (trace_id=trace-123)'
+ )
+ )
+})
+
+test('keeps the existing message outside CI even when diagnostics are available', async () => {
+ const response = new Response('R context failed to initialize', {
+ status: 500,
+ statusText: 'Internal Server Error',
+ headers: { 'X-E2B-Trace-ID': 'trace-123' },
+ })
+ const text = vi.spyOn(response, 'text')
+
+ const error = await extractError(response, false)
+
+ expect(error).toEqual(new SandboxError('500 Internal Server Error'))
+ expect(text).not.toHaveBeenCalled()
+})
+
+test.each([
+ [404, ' missing ', NotFoundError, ' missing '],
+ [
+ 502,
+ ' timed out ',
+ TimeoutError,
+ " timed out : This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeoutMs' when starting the sandbox or calling '.setTimeout' on the sandbox with the desired timeout.",
+ ],
+])(
+ 'preserves the non-CI %s response body exactly',
+ async (status, body, ErrorClass, message) => {
+ const error = await extractError(new Response(body, { status }), false)
+
+ expect(error).toEqual(new ErrorClass(message))
+ }
+)
diff --git a/packages/code-interpreter-js/tests/runtimes/cloudflare/vitest.config.mts b/packages/code-interpreter-js/tests/runtimes/cloudflare/vitest.config.mts
index b5b071caa..8790a20e6 100644
--- a/packages/code-interpreter-js/tests/runtimes/cloudflare/vitest.config.mts
+++ b/packages/code-interpreter-js/tests/runtimes/cloudflare/vitest.config.mts
@@ -2,4 +2,6 @@ import { defineConfig } from 'vitest/config'
import { createCloudflareVitestConfig } from '../../../../../vitest.cloudflare.config.mts'
-export default defineConfig(createCloudflareVitestConfig())
+export default defineConfig(
+ createCloudflareVitestConfig({ testTimeout: 90_000, maxWorkers: 1 })
+)
diff --git a/packages/code-interpreter-js/tests/sandboxUrl.test.ts b/packages/code-interpreter-js/tests/sandboxUrl.test.ts
index 4566f6cd0..224c531bc 100644
--- a/packages/code-interpreter-js/tests/sandboxUrl.test.ts
+++ b/packages/code-interpreter-js/tests/sandboxUrl.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, expect, test } from 'vitest'
+import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { Sandbox } from '../src'
@@ -17,13 +17,14 @@ function createSandbox(opts: object = {}) {
const savedEnv: Record<string, string | undefined> = {}
beforeEach(() => {
- for (const key of ['E2B_SANDBOX_URL', 'E2B_DEBUG']) {
+ for (const key of ['E2B_SANDBOX_URL', 'E2B_DEBUG', 'E2B_USER_AGENT_SOURCE']) {
savedEnv[key] = process.env[key]
delete process.env[key]
}
})
afterEach(() => {
+ vi.unstubAllGlobals()
for (const [key, value] of Object.entries(savedEnv)) {
if (value === undefined) {
delete process.env[key]
@@ -48,3 +49,17 @@ test('jupyterUrl honors the E2B_SANDBOX_URL environment variable', () => {
const sandbox = createSandbox()
expect(sandbox.jupyterUrl).toBe('https://env.example.com')
})
+
+test('runCode tags CI traffic in the request URL', async () => {
+ process.env.E2B_USER_AGENT_SOURCE = 'ci'
+ const sandbox = createSandbox({ domain: 'example.dev' })
+ const fetchMock = vi.fn().mockResolvedValue(new Response(''))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await (sandbox as unknown as Sandbox).runCode('1 + 1')
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://49999-test-sandbox-id.example.dev/execute?source=ci',
+ expect.any(Object)
+ )
+})
diff --git a/packages/code-interpreter-js/tests/setup.ts b/packages/code-interpreter-js/tests/setup.ts
index 2f4be79c6..5b4380102 100644
--- a/packages/code-interpreter-js/tests/setup.ts
+++ b/packages/code-interpreter-js/tests/setup.ts
@@ -1,5 +1,5 @@
import { test as base } from 'vitest'
-import { Sandbox, SandboxOpts } from '../src'
+import { Sandbox, SandboxError, SandboxOpts } from '../src'
interface SandboxFixture {
sandbox: Sandbox
@@ -9,6 +9,7 @@ interface SandboxFixture {
}
const template = process.env.E2B_TESTS_TEMPLATE || 'code-interpreter-v1'
+const KERNEL_READINESS_ATTEMPTS = 4
export const sandboxTest = base.extend<SandboxFixture>({
template,
@@ -67,4 +68,26 @@ export async function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
+export async function waitForKernel(sandbox: Sandbox, language: 'java' | 'r') {
+ for (let attempt = 1; attempt <= KERNEL_READINESS_ATTEMPTS; attempt++) {
+ try {
+ await sandbox.runCode('1', { language })
+ return
+ } catch (error) {
+ // A newly running sandbox can briefly return this response while
+ // Foxtrot initializes a lazy language context. Retry only that known
+ // readiness failure; the test's actual execution still runs once.
+ const isReadinessError =
+ error instanceof SandboxError &&
+ /^500 Internal Server Error(?: \(trace_id=[^)]+\))?$/.test(
+ error.message
+ )
+
+ if (!isReadinessError || attempt === KERNEL_READINESS_ATTEMPTS) {
+ throw error
+ }
+ }
+ }
+}
+
export { template }
diff --git a/packages/code-interpreter-js/vitest.config.mts b/packages/code-interpreter-js/vitest.config.mts
index 7027d898b..7189b7513 100644
--- a/packages/code-interpreter-js/vitest.config.mts
+++ b/packages/code-interpreter-js/vitest.config.mts
@@ -6,8 +6,11 @@ import { createSdkVitestConfig } from '../../vitest.sdk.config.mts'
const env = config()
export default defineConfig(
- createSdkVitestConfig({
- ...(process.env as Record<string, string>),
- ...env.parsed,
- })
+ createSdkVitestConfig(
+ {
+ ...(process.env as Record<string, string>),
+ ...env.parsed,
+ },
+ { testTimeout: 90_000 }
+ )
)
diff --git a/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_async.py b/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_async.py
index e7d0a433c..072a531f0 100644
--- a/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_async.py
+++ b/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_async.py
@@ -68,6 +68,18 @@ class AsyncSandbox(BaseAsyncSandbox):
return sandbox_url
return f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(JUPYTER_PORT)}"
+ def _jupyter_request_url(self, path: str) -> str:
+ url = f"{self._jupyter_url}{path}"
+ source = getattr(self.connection_config, "request_source", None)
+ if not source:
+ return url
+ separator = "&" if "?" in url else "?"
+ return f"{url}{separator}source={source}"
+
+ @property
+ def _include_diagnostics(self) -> bool:
+ return getattr(self.connection_config, "request_source", None) == "ci"
+
@property
def _client(self) -> AsyncClient:
# TODO: Remove later
@@ -211,7 +223,7 @@ class AsyncSandbox(BaseAsyncSandbox):
async with self._client.stream(
"POST",
- f"{self._jupyter_url}/execute",
+ self._jupyter_request_url("/execute"),
json={
"code": code,
"context_id": context_id,
@@ -236,7 +248,7 @@ class AsyncSandbox(BaseAsyncSandbox):
else httpx.Timeout(None)
),
) as response:
- err = await aextract_exception(response)
+ err = await aextract_exception(response, self._include_diagnostics)
if err:
raise err
@@ -294,13 +306,13 @@ class AsyncSandbox(BaseAsyncSandbox):
headers["E2B-Traffic-Access-Token"] = self.traffic_access_token
response = await self._client.post(
- f"{self._jupyter_url}/contexts",
+ self._jupyter_request_url("/contexts"),
headers=headers,
json=data,
timeout=request_timeout or self.connection_config.request_timeout,
)
- err = await aextract_exception(response)
+ err = await aextract_exception(response, self._include_diagnostics)
if err:
raise err
@@ -335,12 +347,12 @@ class AsyncSandbox(BaseAsyncSandbox):
headers["E2B-Traffic-Access-Token"] = self.traffic_access_token
response = await self._client.delete(
- f"{self._jupyter_url}/contexts/{context_id}",
+ self._jupyter_request_url(f"/contexts/{context_id}"),
headers=headers,
timeout=self.connection_config.request_timeout,
)
- err = await aextract_exception(response)
+ err = await aextract_exception(response, self._include_diagnostics)
if err:
raise err
except httpx.TimeoutException:
@@ -365,12 +377,12 @@ class AsyncSandbox(BaseAsyncSandbox):
headers["E2B-Traffic-Access-Token"] = self.traffic_access_token
response = await self._client.get(
- f"{self._jupyter_url}/contexts",
+ self._jupyter_request_url("/contexts"),
headers=headers,
timeout=self.connection_config.request_timeout,
)
- err = await aextract_exception(response)
+ err = await aextract_exception(response, self._include_diagnostics)
if err:
raise err
@@ -404,12 +416,12 @@ class AsyncSandbox(BaseAsyncSandbox):
headers["E2B-Traffic-Access-Token"] = self.traffic_access_token
response = await self._client.post(
- f"{self._jupyter_url}/contexts/{context_id}/restart",
+ self._jupyter_request_url(f"/contexts/{context_id}/restart"),
headers=headers,
timeout=self.connection_config.request_timeout,
)
- err = await aextract_exception(response)
+ err = await aextract_exception(response, self._include_diagnostics)
if err:
raise err
except httpx.TimeoutException:
diff --git a/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_sync.py b/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_sync.py
index f4e4643f8..ebabcfc7e 100644
--- a/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_sync.py
+++ b/packages/code-interpreter-python/e2b_code_interpreter/code_interpreter_sync.py
@@ -65,6 +65,18 @@ class Sandbox(BaseSandbox):
return sandbox_url
return f"{'http' if self.connection_config.debug else 'https'}://{self.get_host(JUPYTER_PORT)}"
+ def _jupyter_request_url(self, path: str) -> str:
+ url = f"{self._jupyter_url}{path}"
+ source = getattr(self.connection_config, "request_source", None)
+ if not source:
+ return url
+ separator = "&" if "?" in url else "?"
+ return f"{url}{separator}source={source}"
+
+ @property
+ def _include_diagnostics(self) -> bool:
+ return getattr(self.connection_config, "request_source", None) == "ci"
+
@property
def _client(self) -> Client:
# TODO: Remove later
@@ -206,7 +218,7 @@ class Sandbox(BaseSandbox):
with self._client.stream(
"POST",
- f"{self._jupyter_url}/execute",
+ self._jupyter_request_url("/execute"),
json={
"code": code,
"context_id": context_id,
@@ -231,7 +243,7 @@ class Sandbox(BaseSandbox):
else httpx.Timeout(None)
),
) as response:
- err = extract_exception(response)
+ err = extract_exception(response, self._include_diagnostics)
if err:
raise err
@@ -289,13 +301,13 @@ class Sandbox(BaseSandbox):
headers["E2B-Traffic-Access-Token"] = self.traffic_access_token
response = self._client.post(
- f"{self._jupyter_url}/contexts",
+ self._jupyter_request_url("/contexts"),
json=data,
headers=headers,
timeout=request_timeout or self.connection_config.request_timeout,
)
- err = extract_exception(response)
+ err = extract_exception(response, self._include_diagnostics)
if err:
raise err
@@ -330,12 +342,12 @@ class Sandbox(BaseSandbox):
headers["E2B-Traffic-Access-Token"] = self.traffic_access_token
response = self._client.delete(
- f"{self._jupyter_url}/contexts/{context_id}",
+ self._jupyter_request_url(f"/contexts/{context_id}"),
headers=headers,
timeout=self.connection_config.request_timeout,
)
- err = extract_exception(response)
+ err = extract_exception(response, self._include_diagnostics)
if err:
raise err
except httpx.TimeoutException:
@@ -360,12 +372,12 @@ class Sandbox(BaseSandbox):
headers["E2B-Traffic-Access-Token"] = self.traffic_access_token
response = self._client.get(
- f"{self._jupyter_url}/contexts",
+ self._jupyter_request_url("/contexts"),
headers=headers,
timeout=self.connection_config.request_timeout,
)
- err = extract_exception(response)
+ err = extract_exception(response, self._include_diagnostics)
if err:
raise err
@@ -400,12 +412,12 @@ class Sandbox(BaseSandbox):
headers["E2B-Traffic-Access-Token"] = self.traffic_access_token
response = self._client.post(
- f"{self._jupyter_url}/contexts/{context_id}/restart",
+ self._jupyter_request_url(f"/contexts/{context_id}/restart"),
headers=headers,
timeout=self.connection_config.request_timeout,
)
- err = extract_exception(response)
+ err = extract_exception(response, self._include_diagnostics)
if err:
raise err
except httpx.TimeoutException:
diff --git a/packages/code-interpreter-python/e2b_code_interpreter/models.py b/packages/code-interpreter-python/e2b_code_interpreter/models.py
index d891e7f37..047422eb8 100644
--- a/packages/code-interpreter-python/e2b_code_interpreter/models.py
+++ b/packages/code-interpreter-python/e2b_code_interpreter/models.py
@@ -400,34 +400,41 @@ class Execution:
return json.dumps(data)
-async def aextract_exception(res: Response):
+async def aextract_exception(res: Response, include_diagnostics: bool = False):
if res.is_success:
return None
await res.aread()
- return extract_exception(res)
+ return extract_exception(res, include_diagnostics)
-def extract_exception(res: Response):
+def extract_exception(res: Response, include_diagnostics: bool = False):
if res.is_success:
return None
res.read()
- return format_exception(res)
+ return format_exception(res, include_diagnostics)
-def format_exception(res: Response):
+def format_exception(res: Response, include_diagnostics: bool = False):
if res.is_success:
return None
+ body = res.text
+ trace_id = res.headers.get("X-E2B-Trace-ID") if include_diagnostics else None
+ trace_suffix = f" (trace_id={trace_id})" if trace_id else ""
+
if res.status_code == 404:
- return NotFoundException(res.text)
+ return NotFoundException(f"{body}{trace_suffix}")
elif res.status_code == 502:
return TimeoutException(
- f"{res.text}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeout' when starting the sandbox or calling '.set_timeout' on the sandbox with the desired timeout."
+ f"{body}: This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeout' when starting the sandbox or calling '.set_timeout' on the sandbox with the desired timeout.{trace_suffix}"
)
else:
- return SandboxException(f"{res.status_code}: {res.text}")
+ body_separator = "" if trace_suffix and not body else " "
+ return SandboxException(
+ f"{res.status_code}:{body_separator}{body}{trace_suffix}"
+ )
def parse_output(
diff --git a/packages/code-interpreter-python/tests/async/env_vars/test_java.py b/packages/code-interpreter-python/tests/async/env_vars/test_java.py
index d33517c84..f1195ef35 100644
--- a/packages/code-interpreter-python/tests/async/env_vars/test_java.py
+++ b/packages/code-interpreter-python/tests/async/env_vars/test_java.py
@@ -3,11 +3,13 @@ from e2b_code_interpreter.code_interpreter_async import AsyncSandbox
@pytest.mark.skip_debug()
-async def test_env_vars_on_sandbox(template):
+async def test_env_vars_on_sandbox(template, wait_for_kernel_async):
sandbox = await AsyncSandbox.create(
template=template, envs={"TEST_ENV_VAR": "supertest"}
)
try:
+ await wait_for_kernel_async(sandbox, "java")
+
result = await sandbox.run_code(
'System.getProperty("TEST_ENV_VAR")', language="java"
)
@@ -17,12 +19,12 @@ async def test_env_vars_on_sandbox(template):
await sandbox.kill()
-async def test_env_vars_per_execution(async_sandbox: AsyncSandbox):
- result = await async_sandbox.run_code(
+async def test_env_vars_per_execution(async_java_sandbox: AsyncSandbox):
+ result = await async_java_sandbox.run_code(
'System.getProperty("FOO")', envs={"FOO": "bar"}, language="java"
)
- result_empty = await async_sandbox.run_code(
+ result_empty = await async_java_sandbox.run_code(
'System.getProperty("FOO", "default")', language="java"
)
@@ -33,11 +35,13 @@ async def test_env_vars_per_execution(async_sandbox: AsyncSandbox):
@pytest.mark.skip_debug()
-async def test_env_vars_overwrite(template):
+async def test_env_vars_overwrite(template, wait_for_kernel_async):
sandbox = await AsyncSandbox.create(
template=template, envs={"TEST_ENV_VAR": "supertest"}
)
try:
+ await wait_for_kernel_async(sandbox, "java")
+
result = await sandbox.run_code(
'System.getProperty("TEST_ENV_VAR")',
language="java",
diff --git a/packages/code-interpreter-python/tests/async/env_vars/test_r.py b/packages/code-interpreter-python/tests/async/env_vars/test_r.py
index 6ba95651e..e75b499ba 100644
--- a/packages/code-interpreter-python/tests/async/env_vars/test_r.py
+++ b/packages/code-interpreter-python/tests/async/env_vars/test_r.py
@@ -3,11 +3,12 @@ from e2b_code_interpreter.code_interpreter_async import AsyncSandbox
@pytest.mark.skip_debug()
-async def test_env_vars_on_sandbox(template):
+async def test_env_vars_on_sandbox(template, wait_for_kernel_async):
sandbox = await AsyncSandbox.create(
template=template, envs={"TEST_ENV_VAR": "supertest"}
)
try:
+ await wait_for_kernel_async(sandbox, "r")
result = await sandbox.run_code('Sys.getenv("TEST_ENV_VAR")', language="r")
assert result.results[0].text is not None
assert result.results[0].text.strip() == '[1] "supertest"'
@@ -15,7 +16,10 @@ async def test_env_vars_on_sandbox(template):
await sandbox.kill()
-async def test_env_vars_per_execution(async_sandbox: AsyncSandbox):
+async def test_env_vars_per_execution(
+ async_sandbox: AsyncSandbox, wait_for_kernel_async
+):
+ await wait_for_kernel_async(async_sandbox, "r")
result = await async_sandbox.run_code(
'Sys.getenv("FOO")', envs={"FOO": "bar"}, language="r"
)
@@ -31,11 +35,12 @@ async def test_env_vars_per_execution(async_sandbox: AsyncSandbox):
@pytest.mark.skip_debug()
-async def test_env_vars_overwrite(template):
+async def test_env_vars_overwrite(template, wait_for_kernel_async):
sandbox = await AsyncSandbox.create(
template=template, envs={"TEST_ENV_VAR": "supertest"}
)
try:
+ await wait_for_kernel_async(sandbox, "r")
result = await sandbox.run_code(
'Sys.getenv("TEST_ENV_VAR")',
language="r",
diff --git a/packages/code-interpreter-python/tests/async/test_async_cwd.py b/packages/code-interpreter-python/tests/async/test_async_cwd.py
index 1896d7670..257ca89a3 100644
--- a/packages/code-interpreter-python/tests/async/test_async_cwd.py
+++ b/packages/code-interpreter-python/tests/async/test_async_cwd.py
@@ -22,14 +22,15 @@ async def test_cwd_typescript(async_sandbox: AsyncSandbox):
@pytest.mark.skip_debug()
-async def test_cwd_r(async_sandbox: AsyncSandbox):
+async def test_cwd_r(async_sandbox: AsyncSandbox, wait_for_kernel_async):
+ await wait_for_kernel_async(async_sandbox, "r")
result = await async_sandbox.run_code("getwd()", language="r")
assert result.results[0].text.strip() == '[1] "/home/user"'
@pytest.mark.skip_debug()
-async def test_cwd_java(async_sandbox: AsyncSandbox):
- result = await async_sandbox.run_code(
+async def test_cwd_java(async_java_sandbox: AsyncSandbox):
+ result = await async_java_sandbox.run_code(
'System.getProperty("user.dir")', language="java"
)
assert result.results[0].text.strip() == "/home/user"
diff --git a/packages/code-interpreter-python/tests/conftest.py b/packages/code-interpreter-python/tests/conftest.py
index 199b0a120..fbe536667 100644
--- a/packages/code-interpreter-python/tests/conftest.py
+++ b/packages/code-interpreter-python/tests/conftest.py
@@ -1,13 +1,19 @@
import asyncio
import os
+import re
+import uuid
import pytest
+from e2b import SandboxException
from e2b_code_interpreter import (
AsyncSandbox,
Sandbox,
)
-import uuid
+
+
+DEFAULT_TEST_SANDBOX_TIMEOUT = 180
+KERNEL_READINESS_ATTEMPTS = 4
@pytest.fixture(scope="session")
@@ -24,7 +30,7 @@ def template():
def sandbox_factory(request, template, sandbox_test_id):
def factory(*, template_name: str = template, **kwargs):
kwargs.setdefault("secure", False)
- kwargs.setdefault("timeout", 60)
+ kwargs.setdefault("timeout", DEFAULT_TEST_SANDBOX_TIMEOUT)
metadata = kwargs.setdefault("metadata", dict())
metadata.setdefault("sandbox_test_id", sandbox_test_id)
@@ -48,7 +54,7 @@ async def async_sandbox_factory(template, sandbox_test_id):
sandboxes: list[AsyncSandbox] = []
async def factory(*, template_name: str = template, **kwargs):
- kwargs.setdefault("timeout", 60)
+ kwargs.setdefault("timeout", DEFAULT_TEST_SANDBOX_TIMEOUT)
metadata = kwargs.setdefault("metadata", dict())
metadata.setdefault("sandbox_test_id", sandbox_test_id)
@@ -69,6 +75,57 @@ async def async_sandbox(async_sandbox_factory):
return await async_sandbox_factory()
+def _wait_for_kernel(sandbox: Sandbox, language: str) -> None:
+ for attempt in range(KERNEL_READINESS_ATTEMPTS):
+ try:
+ sandbox.run_code("1", language=language)
+ return
+ except SandboxException as error:
+ # A newly running sandbox can briefly return this response while
+ # Foxtrot initializes a lazy language context. Retry only that known
+ # readiness failure; the test's actual execution still runs once.
+ is_readiness_error = re.fullmatch(
+ r"500:(?: \(trace_id=[^)]+\))?", str(error).strip()
+ )
+ if not is_readiness_error or attempt == KERNEL_READINESS_ATTEMPTS - 1:
+ raise
+
+
+async def _wait_for_kernel_async(sandbox: AsyncSandbox, language: str) -> None:
+ for attempt in range(KERNEL_READINESS_ATTEMPTS):
+ try:
+ await sandbox.run_code("1", language=language)
+ return
+ except SandboxException as error:
+ is_readiness_error = re.fullmatch(
+ r"500:(?: \(trace_id=[^)]+\))?", str(error).strip()
+ )
+ if not is_readiness_error or attempt == KERNEL_READINESS_ATTEMPTS - 1:
+ raise
+
+
+def wait_for_kernel():
+ return _wait_for_kernel
+
+
+def wait_for_kernel_async():
+ return _wait_for_kernel_async
+
+
+def java_sandbox(sandbox: Sandbox):
+ _wait_for_kernel(sandbox, "java")
+ return sandbox
+
+
+async def async_java_sandbox(async_sandbox: AsyncSandbox):
+ await _wait_for_kernel_async(async_sandbox, "java")
+ return async_sandbox
+
+
@pytest.fixture
def debug():
return os.getenv("E2B_DEBUG") is not None
diff --git a/packages/code-interpreter-python/tests/sync/env_vars/test_java.py b/packages/code-interpreter-python/tests/sync/env_vars/test_java.py
index b0950d9de..465aea946 100644
--- a/packages/code-interpreter-python/tests/sync/env_vars/test_java.py
+++ b/packages/code-interpreter-python/tests/sync/env_vars/test_java.py
@@ -3,9 +3,11 @@ from e2b_code_interpreter import Sandbox
@pytest.mark.skip_debug()
-def test_env_vars_on_sandbox(template):
+def test_env_vars_on_sandbox(template, wait_for_kernel):
sandbox = Sandbox.create(template=template, envs={"TEST_ENV_VAR": "supertest"})
try:
+ wait_for_kernel(sandbox, "java")
+
result = sandbox.run_code('System.getProperty("TEST_ENV_VAR")', language="java")
assert result.text is not None
assert result.text.strip() == "supertest"
@@ -13,13 +15,13 @@ def test_env_vars_on_sandbox(template):
sandbox.kill()
-def test_env_vars_per_execution(sandbox: Sandbox):
+def test_env_vars_per_execution(java_sandbox: Sandbox):
try:
- result = sandbox.run_code(
+ result = java_sandbox.run_code(
'System.getProperty("FOO")', envs={"FOO": "bar"}, language="java"
)
- result_empty = sandbox.run_code(
+ result_empty = java_sandbox.run_code(
'System.getProperty("FOO", "default")', language="java"
)
@@ -28,13 +30,15 @@ def test_env_vars_per_execution(sandbox: Sandbox):
assert result_empty.text is not None
assert result_empty.text.strip() == "default"
finally:
- sandbox.kill()
+ java_sandbox.kill()
@pytest.mark.skip_debug()
-def test_env_vars_overwrite(template):
+def test_env_vars_overwrite(template, wait_for_kernel):
sandbox = Sandbox.create(template=template, envs={"TEST_ENV_VAR": "supertest"})
try:
+ wait_for_kernel(sandbox, "java")
+
result = sandbox.run_code(
'System.getProperty("TEST_ENV_VAR")',
language="java",
diff --git a/packages/code-interpreter-python/tests/sync/env_vars/test_r.py b/packages/code-interpreter-python/tests/sync/env_vars/test_r.py
index c1641116c..9b44bd924 100644
--- a/packages/code-interpreter-python/tests/sync/env_vars/test_r.py
+++ b/packages/code-interpreter-python/tests/sync/env_vars/test_r.py
@@ -3,9 +3,10 @@ from e2b_code_interpreter import Sandbox
@pytest.mark.skip_debug()
-def test_env_vars_on_sandbox(template):
+def test_env_vars_on_sandbox(template, wait_for_kernel):
sandbox = Sandbox.create(template=template, envs={"TEST_ENV_VAR": "supertest"})
try:
+ wait_for_kernel(sandbox, "r")
result = sandbox.run_code("Sys.getenv('TEST_ENV_VAR')", language="r")
assert result.results[0].text is not None
assert result.results[0].text.strip() == '[1] "supertest"'
@@ -13,8 +14,9 @@ def test_env_vars_on_sandbox(template):
sandbox.kill()
-def test_env_vars_per_execution(sandbox: Sandbox):
+def test_env_vars_per_execution(sandbox: Sandbox, wait_for_kernel):
try:
+ wait_for_kernel(sandbox, "r")
result = sandbox.run_code(
"Sys.getenv('FOO')", envs={"FOO": "bar"}, language="r"
)
@@ -32,9 +34,10 @@ def test_env_vars_per_execution(sandbox: Sandbox):
@pytest.mark.skip_debug()
-def test_env_vars_overwrite(template):
+def test_env_vars_overwrite(template, wait_for_kernel):
sandbox = Sandbox.create(template=template, envs={"TEST_ENV_VAR": "supertest"})
try:
+ wait_for_kernel(sandbox, "r")
result = sandbox.run_code(
"Sys.getenv('TEST_ENV_VAR')",
language="r",
diff --git a/packages/code-interpreter-python/tests/sync/test_cwd.py b/packages/code-interpreter-python/tests/sync/test_cwd.py
index b238f7e96..d9ae3c985 100644
--- a/packages/code-interpreter-python/tests/sync/test_cwd.py
+++ b/packages/code-interpreter-python/tests/sync/test_cwd.py
@@ -22,14 +22,15 @@ def test_cwd_typescript(sandbox: Sandbox):
@pytest.mark.skip_debug()
-def test_cwd_r(sandbox: Sandbox):
+def test_cwd_r(sandbox: Sandbox, wait_for_kernel):
+ wait_for_kernel(sandbox, "r")
result = sandbox.run_code("getwd()", language="r")
assert result.results[0].text.strip() == '[1] "/home/user"'
@pytest.mark.skip_debug()
-def test_cwd_java(sandbox: Sandbox):
- result = sandbox.run_code('System.getProperty("user.dir")', language="java")
+def test_cwd_java(java_sandbox: Sandbox):
+ result = java_sandbox.run_code('System.getProperty("user.dir")', language="java")
assert result.results[0].text.strip() == "/home/user"
diff --git a/packages/code-interpreter-python/tests/sync/test_default_kernels.py b/packages/code-interpreter-python/tests/sync/test_default_kernels.py
index 8dfd4bf97..a4ce42012 100644
--- a/packages/code-interpreter-python/tests/sync/test_default_kernels.py
+++ b/packages/code-interpreter-python/tests/sync/test_default_kernels.py
@@ -9,14 +9,17 @@ def test_js_kernel(sandbox: Sandbox):
@pytest.mark.skip_debug()
-def test_r_kernel(sandbox: Sandbox):
+def test_r_kernel(sandbox: Sandbox, wait_for_kernel):
+ wait_for_kernel(sandbox, "r")
execution = sandbox.run_code('print("Hello, World!")', language="r")
assert execution.logs.stdout == ['[1] "Hello, World!"\n']
@pytest.mark.skip_debug()
-def test_java_kernel(sandbox: Sandbox):
- execution = sandbox.run_code('System.out.println("Hello, World!")', language="java")
+def test_java_kernel(java_sandbox: Sandbox):
+ execution = java_sandbox.run_code(
+ 'System.out.println("Hello, World!")', language="java"
+ )
assert execution.logs.stdout[0] == "Hello, World!"
diff --git a/packages/code-interpreter-python/tests/test_error_diagnostics.py b/packages/code-interpreter-python/tests/test_error_diagnostics.py
new file mode 100644
index 000000000..80baae7ed
--- /dev/null
+++ b/packages/code-interpreter-python/tests/test_error_diagnostics.py
@@ -0,0 +1,62 @@
+from httpx import Response
+from types import SimpleNamespace
+
+from e2b_code_interpreter.code_interpreter_async import AsyncSandbox
+from e2b_code_interpreter.code_interpreter_sync import Sandbox
+from e2b import NotFoundException, TimeoutException
+from e2b_code_interpreter.models import format_exception
+
+
+def test_preserves_response_details_and_trace_id_for_ci_server_errors():
+ error = format_exception(
+ Response(
+ 500,
+ text="R context failed to initialize",
+ headers={"X-E2B-Trace-ID": "trace-123"},
+ ),
+ include_diagnostics=True,
+ )
+
+ assert str(error) == "500: R context failed to initialize (trace_id=trace-123)"
+
+
+def test_keeps_existing_message_outside_ci():
+ error = format_exception(
+ Response(
+ 500,
+ text="R context failed to initialize",
+ headers={"X-E2B-Trace-ID": "trace-123"},
+ ),
+ include_diagnostics=False,
+ )
+
+ assert str(error) == "500: R context failed to initialize"
+
+
+def test_keeps_empty_generic_error_spacing_outside_ci():
+ error = format_exception(Response(500, text=""), include_diagnostics=False)
+
+ assert str(error) == "500: "
+
+
+def test_preserves_non_ci_response_body_exactly():
+ not_found = format_exception(
+ Response(404, text=" missing "), include_diagnostics=False
+ )
+ timeout = format_exception(
+ Response(502, text=" timed out "), include_diagnostics=False
+ )
+
+ assert isinstance(not_found, NotFoundException)
+ assert str(not_found) == " missing "
+ assert isinstance(timeout, TimeoutException)
+ assert str(timeout) == (
+ " timed out : This error is likely due to sandbox timeout. You can modify the sandbox timeout by passing 'timeout' when starting the sandbox or calling '.set_timeout' on the sandbox with the desired timeout."
+ )
+
+
+def test_older_base_sdk_without_request_source_disables_diagnostics():
+ sandbox = SimpleNamespace(connection_config=SimpleNamespace())
+
+ assert Sandbox._include_diagnostics.fget(sandbox) is False
+ assert AsyncSandbox._include_diagnostics.fget(sandbox) is False
diff --git a/packages/code-interpreter-python/tests/test_execute_timeout.py b/packages/code-interpreter-python/tests/test_execute_timeout.py
index 0ea523d93..28b59361a 100644
--- a/packages/code-interpreter-python/tests/test_execute_timeout.py
+++ b/packages/code-interpreter-python/tests/test_execute_timeout.py
@@ -31,15 +31,16 @@ class _CapturingClient:
self._captured = captured
def stream(self, *args, **kwargs):
+ self._captured["args"] = args
self._captured.update(kwargs)
raise _Stop
-def _sandbox(cls, captured: dict):
+def _sandbox(cls, captured: dict, connection_config=None):
class _Fake(cls):
@property
def connection_config(self):
- return ConnectionConfig(
+ return connection_config or ConnectionConfig(
api_key="x", domain="e2b.app", request_timeout=REQUEST_TIMEOUT
)
@@ -121,3 +122,53 @@ async def test_async_zero_timeout_disables_the_deadline():
tmo = _captured_timeout(captured)
assert (tmo.read, tmo.write, tmo.pool, tmo.connect) == (None, None, None, None)
+
+
+def test_execute_tags_ci_traffic_in_request_url(monkeypatch):
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
+ captured: dict = {}
+
+ with pytest.raises(_Stop):
+ _sandbox(Sandbox, captured).run_code("1 + 1")
+
+ assert captured["args"][:2] == (
+ "POST",
+ "http://127.0.0.1:9/execute?source=ci",
+ )
+
+
+async def test_async_execute_tags_ci_traffic_in_request_url(monkeypatch):
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
+ captured: dict = {}
+
+ with pytest.raises(_Stop):
+ await _sandbox(AsyncSandbox, captured).run_code("1 + 1")
+
+ assert captured["args"][:2] == (
+ "POST",
+ "http://127.0.0.1:9/execute?source=ci",
+ )
+
+
+class _LegacyConnectionConfig:
+ request_timeout = REQUEST_TIMEOUT
+
+
+def test_execute_supports_legacy_e2b_connection_config():
+ captured: dict = {}
+
+ with pytest.raises(_Stop):
+ _sandbox(Sandbox, captured, _LegacyConnectionConfig()).run_code("1 + 1")
+
+ assert captured["args"][:2] == ("POST", "http://127.0.0.1:9/execute")
+
+
+async def test_async_execute_supports_legacy_e2b_connection_config():
+ captured: dict = {}
+
+ with pytest.raises(_Stop):
+ await _sandbox(AsyncSandbox, captured, _LegacyConnectionConfig()).run_code(
+ "1 + 1"
+ )
+
+ assert captured["args"][:2] == ("POST", "http://127.0.0.1:9/execute")
diff --git a/packages/code-interpreter-python/tests/test_java_kernel_readiness.py b/packages/code-interpreter-python/tests/test_java_kernel_readiness.py
new file mode 100644
index 000000000..344cb57d6
--- /dev/null
+++ b/packages/code-interpreter-python/tests/test_java_kernel_readiness.py
@@ -0,0 +1,130 @@
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+from httpx import Response
+
+from e2b import SandboxException
+from e2b_code_interpreter.models import format_exception
+from tests.conftest import _wait_for_kernel, _wait_for_kernel_async
+
+
+def java_not_ready_error() -> SandboxException:
+ return SandboxException("500:")
+
+
+def traced_not_ready_error() -> SandboxException:
+ return format_exception(
+ Response(
+ 500,
+ text="",
+ headers={"X-E2B-Trace-ID": "trace-123"},
+ ),
+ include_diagnostics=True,
+ )
+
+
[email protected]("language", ["java", "r"])
+def test_waits_through_repeated_kernel_readiness_500s(language):
+ run_code = Mock(
+ side_effect=[
+ java_not_ready_error(),
+ java_not_ready_error(),
+ java_not_ready_error(),
+ None,
+ ]
+ )
+ sandbox = Mock(run_code=run_code)
+
+ _wait_for_kernel(sandbox, language)
+
+ assert run_code.call_count == 4
+ run_code.assert_called_with("1", language=language)
+
+
+def test_propagates_a_persistent_java_readiness_500():
+ final_error = java_not_ready_error()
+ run_code = Mock(
+ side_effect=[
+ java_not_ready_error(),
+ java_not_ready_error(),
+ java_not_ready_error(),
+ final_error,
+ ]
+ )
+ sandbox = Mock(run_code=run_code)
+
+ with pytest.raises(SandboxException) as raised:
+ _wait_for_kernel(sandbox, "java")
+
+ assert raised.value is final_error
+ assert run_code.call_count == 4
+
+
+def test_does_not_retry_an_unrelated_java_error():
+ error = SandboxException("401: unauthorized")
+ run_code = Mock(side_effect=error)
+ sandbox = Mock(run_code=run_code)
+
+ with pytest.raises(SandboxException) as raised:
+ _wait_for_kernel(sandbox, "java")
+
+ assert raised.value is error
+ run_code.assert_called_once_with("1", language="java")
+
+
[email protected]("language", ["java", "r"])
+async def test_async_waits_through_repeated_kernel_readiness_500s(language):
+ run_code = AsyncMock(
+ side_effect=[
+ java_not_ready_error(),
+ java_not_ready_error(),
+ java_not_ready_error(),
+ None,
+ ]
+ )
+ sandbox = Mock(run_code=run_code)
+
+ await _wait_for_kernel_async(sandbox, language)
+
+ assert run_code.await_count == 4
+ run_code.assert_awaited_with("1", language=language)
+
+
+async def test_async_propagates_a_persistent_java_readiness_500():
+ final_error = java_not_ready_error()
+ run_code = AsyncMock(
+ side_effect=[
+ java_not_ready_error(),
+ java_not_ready_error(),
+ java_not_ready_error(),
+ final_error,
+ ]
+ )
+ sandbox = Mock(run_code=run_code)
+
+ with pytest.raises(SandboxException) as raised:
+ await _wait_for_kernel_async(sandbox, "java")
+
+ assert raised.value is final_error
+ assert run_code.await_count == 4
+
+
+async def test_async_does_not_retry_an_unrelated_java_error():
+ error = SandboxException("401: unauthorized")
+ run_code = AsyncMock(side_effect=error)
+ sandbox = Mock(run_code=run_code)
+
+ with pytest.raises(SandboxException) as raised:
+ await _wait_for_kernel_async(sandbox, "java")
+
+ assert raised.value is error
+ run_code.assert_awaited_once_with("1", language="java")
+
+
+def test_retries_an_empty_readiness_500_with_trace_id():
+ run_code = Mock(side_effect=[traced_not_ready_error(), None])
+ sandbox = Mock(run_code=run_code)
+
+ _wait_for_kernel(sandbox, "r")
+
+ assert run_code.call_count == 2
diff --git a/packages/desktop-js/src/sandbox.ts b/packages/desktop-js/src/sandbox.ts
index 01ef93d38..7a561118a 100644
--- a/packages/desktop-js/src/sandbox.ts
+++ b/packages/desktop-js/src/sandbox.ts
@@ -198,7 +198,12 @@ export class Sandbox extends SandboxBase {
template,
sandboxOptsWithDisplay
)) as InstanceType<S>
- await sbx._start(display, sandboxOptsWithDisplay)
+ try {
+ await sbx._start(display, sandboxOptsWithDisplay)
+ } catch (error) {
+ await sbx.kill().catch(() => {})
+ throw error
+ }
return sbx
}
@@ -225,10 +230,9 @@ export class Sandbox extends SandboxBase {
return true
}
} catch (e) {
- if (e instanceof CommandExitError) {
- continue
+ if (!(e instanceof CommandExitError)) {
+ throw e
}
- throw e
}
await new Promise((resolve) => setTimeout(resolve, interval * 1000))
@@ -570,6 +574,15 @@ export class Sandbox extends SandboxBase {
this.lastXfce4Pid = result.pid
await result.disconnect()
}
+
+ const hasStarted = await this.waitAndVerify(
+ 'pgrep -x xfce4-session >/dev/null && pgrep -x xfwm4 >/dev/null && pgrep -x xfdesktop >/dev/null',
+ (r: CommandResult) => r.exitCode === 0,
+ 60
+ )
+ if (!hasStarted) {
+ throw new TimeoutError('Could not start XFCE')
+ }
}
private *breakIntoChunks(text: string, n: number): Generator<string> {
diff --git a/packages/desktop-js/tests/mouse.test.ts b/packages/desktop-js/tests/mouse.test.ts
index eb6058496..3f0f81607 100644
--- a/packages/desktop-js/tests/mouse.test.ts
+++ b/packages/desktop-js/tests/mouse.test.ts
@@ -1,5 +1,5 @@
import { expect } from 'vitest'
-import { sandboxTest, wait } from './setup'
+import { sandboxTest } from './setup'
sandboxTest('cursor position', async ({ sandbox }) => {
const pos = await sandbox.getCursorPosition()
@@ -13,7 +13,6 @@ sandboxTest('cursor position', async ({ sandbox }) => {
})
sandboxTest('mouse move', async ({ sandbox }) => {
- await wait(5_000)
await sandbox.moveMouse(100, 200)
const pos2 = await sandbox.getCursorPosition()
expect(pos2).toEqual({ x: 100, y: 200 })
diff --git a/packages/desktop-js/tests/readiness.test.ts b/packages/desktop-js/tests/readiness.test.ts
new file mode 100644
index 000000000..1962b8dc5
--- /dev/null
+++ b/packages/desktop-js/tests/readiness.test.ts
@@ -0,0 +1,93 @@
+import { afterEach, expect, test, vi } from 'vitest'
+import { CommandExitError, Sandbox as BaseSandbox } from 'e2b'
+
+import { Sandbox, TimeoutError } from '../src'
+
+afterEach(() => {
+ vi.restoreAllMocks()
+})
+
+function desktopWithCommands(run: ReturnType<typeof vi.fn>) {
+ const sandbox = Object.create(Sandbox.prototype) as Sandbox & {
+ lastXfce4Pid: number | null
+ startXfce4(): Promise<void>
+ }
+ sandbox.lastXfce4Pid = null
+ Object.defineProperty(sandbox, 'commands', { value: { run } })
+ return sandbox
+}
+
+test('waits for the XFCE desktop session before startup completes', async () => {
+ const disconnect = vi.fn().mockResolvedValue(undefined)
+ const sandbox = desktopWithCommands(
+ vi.fn().mockResolvedValue({ pid: 42, disconnect })
+ )
+ const waitAndVerify = vi
+ .spyOn(sandbox, 'waitAndVerify')
+ .mockResolvedValue(true)
+
+ await sandbox.startXfce4()
+
+ expect(waitAndVerify).toHaveBeenCalledWith(
+ expect.stringContaining('xfce4-session'),
+ expect.any(Function),
+ 60
+ )
+ expect(disconnect).toHaveBeenCalledOnce()
+})
+
+test('fails startup when the XFCE desktop session never becomes ready', async () => {
+ const sandbox = desktopWithCommands(
+ vi.fn().mockResolvedValue({
+ pid: 42,
+ disconnect: vi.fn().mockResolvedValue(undefined),
+ })
+ )
+ vi.spyOn(sandbox, 'waitAndVerify').mockResolvedValue(false)
+
+ await expect(sandbox.startXfce4()).rejects.toEqual(
+ new TimeoutError('Could not start XFCE')
+ )
+})
+
+test('kills a sandbox whose desktop session fails to initialize', async () => {
+ const startupError = new TimeoutError('Could not start XFCE')
+ const sandbox = {
+ _start: vi.fn().mockRejectedValue(startupError),
+ kill: vi.fn().mockResolvedValue(undefined),
+ }
+ vi.spyOn(BaseSandbox, 'create').mockResolvedValue(
+ sandbox as unknown as BaseSandbox
+ )
+
+ await expect(Sandbox.create()).rejects.toBe(startupError)
+
+ expect(sandbox.kill).toHaveBeenCalledOnce()
+})
+
+test('waits between readiness probes that exit unsuccessfully', async () => {
+ const run = vi
+ .fn()
+ .mockRejectedValueOnce(
+ new CommandExitError({
+ exitCode: 1,
+ stdout: '',
+ stderr: '',
+ })
+ )
+ .mockResolvedValueOnce({ exitCode: 0 })
+ const sandbox = desktopWithCommands(run)
+ const timeout = vi.spyOn(globalThis, 'setTimeout')
+
+ await expect(
+ sandbox.waitAndVerify(
+ 'readiness-probe',
+ (result) => result.exitCode === 0,
+ 10,
+ 0
+ )
+ ).resolves.toBe(true)
+
+ expect(timeout).toHaveBeenCalled()
+ expect(run).toHaveBeenCalledTimes(2)
+})
diff --git a/packages/desktop-js/tests/runtimes/cloudflare/vitest.config.mts b/packages/desktop-js/tests/runtimes/cloudflare/vitest.config.mts
index 2ff592880..f0cb75e40 100644
--- a/packages/desktop-js/tests/runtimes/cloudflare/vitest.config.mts
+++ b/packages/desktop-js/tests/runtimes/cloudflare/vitest.config.mts
@@ -7,7 +7,8 @@ import {
export default defineConfig(
createCloudflareVitestConfig({
- testTimeout: 60_000,
+ testTimeout: 90_000,
+ maxWorkers: 1,
isExpectedRejection: isConnectRpcRejection,
})
)
diff --git a/packages/desktop-js/tests/setup.ts b/packages/desktop-js/tests/setup.ts
index 2a2c08403..dba79881f 100644
--- a/packages/desktop-js/tests/setup.ts
+++ b/packages/desktop-js/tests/setup.ts
@@ -1,7 +1,7 @@
import { Sandbox } from '../src'
import { test as base } from 'vitest'
-const timeoutMs = 60_000
+const timeoutMs = 180_000
const template = 'desktop'
interface SandboxFixture {
diff --git a/packages/desktop-js/vitest.config.ts b/packages/desktop-js/vitest.config.ts
index 7027d898b..7189b7513 100644
--- a/packages/desktop-js/vitest.config.ts
+++ b/packages/desktop-js/vitest.config.ts
@@ -6,8 +6,11 @@ import { createSdkVitestConfig } from '../../vitest.sdk.config.mts'
const env = config()
export default defineConfig(
- createSdkVitestConfig({
- ...(process.env as Record<string, string>),
- ...env.parsed,
- })
+ createSdkVitestConfig(
+ {
+ ...(process.env as Record<string, string>),
+ ...env.parsed,
+ },
+ { testTimeout: 90_000 }
+ )
)
diff --git a/packages/desktop-python/e2b_desktop/main.py b/packages/desktop-python/e2b_desktop/main.py
index 744f5f0c7..1962df014 100644
--- a/packages/desktop-python/e2b_desktop/main.py
+++ b/packages/desktop-python/e2b_desktop/main.py
@@ -273,23 +273,30 @@ class Sandbox(SandboxBase):
**opts,
)
- sbx._display = display
- width, height = resolution or (1024, 768)
- xvfb_handle = sbx.commands.run(
- f"Xvfb {display} -ac -screen 0 {width}x{height}x24"
- f" -retro -dpi {dpi or 96} -nolisten tcp -nolisten unix",
- background=True,
- timeout=0,
- )
- xvfb_handle.disconnect()
+ try:
+ sbx._display = display
+ width, height = resolution or (1024, 768)
+ xvfb_handle = sbx.commands.run(
+ f"Xvfb {display} -ac -screen 0 {width}x{height}x24"
+ f" -retro -dpi {dpi or 96} -nolisten tcp -nolisten unix",
+ background=True,
+ timeout=0,
+ )
+ xvfb_handle.disconnect()
- if not sbx._wait_and_verify(
- f"xdpyinfo -display {display}", lambda r: r.exit_code == 0
- ):
- raise TimeoutException("Could not start Xvfb")
+ if not sbx._wait_and_verify(
+ f"xdpyinfo -display {display}", lambda r: r.exit_code == 0
+ ):
+ raise TimeoutException("Could not start Xvfb")
- sbx.__vnc_server = _VNCServer(sbx)
- sbx._start_xfce4()
+ sbx.__vnc_server = _VNCServer(sbx)
+ sbx._start_xfce4()
+ except Exception:
+ try:
+ sbx.kill()
+ except Exception:
+ pass
+ raise
return sbx
@@ -306,7 +313,7 @@ class Sandbox(SandboxBase):
if on_result(self.commands.run(cmd)):
return True
except CommandExitException:
- continue
+ pass
time.sleep(interval)
elapsed += interval
@@ -326,6 +333,13 @@ class Sandbox(SandboxBase):
self._last_xfce4_pid = xfce4_handle.pid
xfce4_handle.disconnect()
+ if not self._wait_and_verify(
+ "pgrep -x xfce4-session >/dev/null && pgrep -x xfwm4 >/dev/null && pgrep -x xfdesktop >/dev/null",
+ lambda r: r.exit_code == 0,
+ 60,
+ ):
+ raise TimeoutException("Could not start XFCE")
+
@property
def stream(self) -> _VNCServer:
return self.__vnc_server
diff --git a/packages/desktop-python/tests/conftest.py b/packages/desktop-python/tests/conftest.py
index fdc073114..7b96c2c4a 100644
--- a/packages/desktop-python/tests/conftest.py
+++ b/packages/desktop-python/tests/conftest.py
@@ -4,7 +4,7 @@ import logging
from e2b_desktop import Sandbox
# Set up timeout and logger
-timeout = 60
+timeout = 180
logger = logging.getLogger(__name__)
diff --git a/packages/desktop-python/tests/test_readiness.py b/packages/desktop-python/tests/test_readiness.py
new file mode 100644
index 000000000..1a274e32b
--- /dev/null
+++ b/packages/desktop-python/tests/test_readiness.py
@@ -0,0 +1,61 @@
+from unittest.mock import Mock
+
+import pytest
+from e2b import CommandExitException, Sandbox as BaseSandbox, TimeoutException
+
+from e2b_desktop import Sandbox
+
+
+def desktop_with_commands():
+ sandbox = Mock(spec=Sandbox)
+ sandbox._last_xfce4_pid = None
+ sandbox.commands.run.return_value.pid = 42
+ return sandbox
+
+
+def test_waits_for_xfce_desktop_session_before_startup_completes():
+ sandbox = desktop_with_commands()
+ sandbox._wait_and_verify.return_value = True
+
+ Sandbox._start_xfce4(sandbox)
+
+ sandbox._wait_and_verify.assert_called_once()
+ command, _, timeout = sandbox._wait_and_verify.call_args.args
+ assert "xfce4-session" in command
+ assert timeout == 60
+
+
+def test_fails_startup_when_xfce_desktop_session_never_becomes_ready():
+ sandbox = desktop_with_commands()
+ sandbox._wait_and_verify.return_value = False
+
+ with pytest.raises(TimeoutException, match="Could not start XFCE"):
+ Sandbox._start_xfce4(sandbox)
+
+
+def test_kills_sandbox_when_desktop_session_fails_to_initialize(monkeypatch):
+ sandbox = Mock(spec=Sandbox)
+ sandbox.commands.run.side_effect = TimeoutException("Could not start Xvfb")
+ monkeypatch.setattr(BaseSandbox, "create", Mock(return_value=sandbox))
+
+ with pytest.raises(TimeoutException, match="Could not start Xvfb"):
+ Sandbox.create()
+
+ sandbox.kill.assert_called_once_with()
+
+
+def test_waits_between_readiness_probes_that_exit_unsuccessfully(monkeypatch):
+ sandbox = desktop_with_commands()
+ sandbox.commands.run.side_effect = [
+ CommandExitException(stderr="", stdout="", exit_code=1, error=None),
+ Mock(exit_code=0),
+ ]
+ sleep = Mock()
+ monkeypatch.setattr("e2b_desktop.main.time.sleep", sleep)
+
+ assert Sandbox._wait_and_verify(
+ sandbox, "readiness-probe", lambda result: result.exit_code == 0
+ )
+
+ sleep.assert_called_once_with(0.5)
+ assert sandbox.commands.run.call_count == 2
diff --git a/packages/js-sdk/src/api/index.ts b/packages/js-sdk/src/api/index.ts
index 756f5efb6..8750ff112 100644
--- a/packages/js-sdk/src/api/index.ts
+++ b/packages/js-sdk/src/api/index.ts
@@ -106,8 +106,13 @@ class ApiClient {
},
})
- if (config.logger) {
- this.api.use(createApiLogger(config.logger))
+ if (config.logger || config.requestSource === 'ci') {
+ this.api.use(
+ createApiLogger(
+ config.logger ?? { error: (...args) => console.error(...args) },
+ config.requestSource === 'ci'
+ )
+ )
}
}
}
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index e1fd10d47..c243337bf 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -340,13 +340,24 @@ export class ConnectionConfig {
private static readonly sdkUserAgentPrefix = 'e2b-js-sdk/'
- private static buildUserAgent() {
+ private static getRequestSource() {
+ const source = getEnvVar('E2B_USER_AGENT_SOURCE')
+ return source && /^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/.test(source)
+ ? source
+ : undefined
+ }
+
+ private static buildUserAgent(requestSource?: string) {
const userAgentParts = [`${ConnectionConfig.sdkUserAgentPrefix}${version}`]
if (ConnectionConfig.integration) {
userAgentParts.push(ConnectionConfig.integration)
}
+ if (requestSource) {
+ userAgentParts.push(`source/${requestSource}`)
+ }
+
return userAgentParts.join(' ')
}
@@ -358,7 +369,10 @@ export class ConnectionConfig {
* rebuilt via `new ConnectionConfig({ ...config })`) is recognized by its
* prefix and rebuilt, so it stays in sync with the current integration.
*/
- private static applyUserAgent(headers: Record<string, string>) {
+ private static applyUserAgent(
+ headers: Record<string, string>,
+ requestSource?: string
+ ) {
const userAgent = headers['User-Agent']
if (
@@ -368,7 +382,7 @@ export class ConnectionConfig {
return
}
- headers['User-Agent'] = ConnectionConfig.buildUserAgent()
+ headers['User-Agent'] = ConnectionConfig.buildUserAgent(requestSource)
}
/**
@@ -404,6 +418,15 @@ export class ConnectionConfig {
readonly headers?: Record<string, string>
+ /**
+ * Validated traffic source used for request correlation.
+ *
+ * @internal
+ * @hidden
+ * @hide
+ */
+ readonly requestSource?: string
+
readonly proxy?: string
constructor(opts?: ConnectionOpts) {
@@ -413,8 +436,9 @@ export class ConnectionConfig {
this.domain = opts?.domain || ConnectionConfig.domain
this.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MS
this.logger = opts?.logger
+ this.requestSource = ConnectionConfig.getRequestSource()
this.headers = { ...(opts?.headers ?? {}), ...(opts?.apiHeaders ?? {}) }
- ConnectionConfig.applyUserAgent(this.headers)
+ ConnectionConfig.applyUserAgent(this.headers, this.requestSource)
this.proxy = opts?.proxy
this.apiUrl =
diff --git a/packages/js-sdk/src/logs.ts b/packages/js-sdk/src/logs.ts
index d3ed59f21..641acacc8 100644
--- a/packages/js-sdk/src/logs.ts
+++ b/packages/js-sdk/src/logs.ts
@@ -58,20 +58,28 @@ export function createRpcLogger(logger: Logger): Interceptor {
}
}
-export function createApiLogger(logger: Logger): Middleware {
+export function createApiLogger(
+ logger: Logger,
+ includeDiagnostics = false
+): Middleware {
return {
async onRequest({ request }) {
logger.info?.(`Request ${request.method} ${request.url}`)
- return request
},
async onResponse({ response }) {
if (response.status >= 400) {
- logger.error?.('Response:', response.status, response.statusText)
+ const traceId = includeDiagnostics
+ ? response.headers.get('X-E2B-Trace-ID')
+ : null
+ logger.error?.(
+ 'Response:',
+ response.status,
+ response.statusText,
+ ...(traceId ? [`trace_id=${traceId}`] : [])
+ )
} else {
logger.info?.('Response:', response.status, response.statusText)
}
-
- return response
},
}
}
diff --git a/packages/js-sdk/tests/api/handleApiError.test.ts b/packages/js-sdk/tests/api/handleApiError.test.ts
index 6d00483b0..82c24bb3d 100644
--- a/packages/js-sdk/tests/api/handleApiError.test.ts
+++ b/packages/js-sdk/tests/api/handleApiError.test.ts
@@ -1,4 +1,4 @@
-import { assert, test, describe } from 'vitest'
+import { afterEach, assert, test, describe } from 'vitest'
import { handleApiError } from '../../src/api'
import {
AuthenticationError,
@@ -6,17 +6,38 @@ import {
SandboxError,
} from '../../src/errors'
+const originalRequestSource = process.env.E2B_USER_AGENT_SOURCE
+
+afterEach(() => {
+ if (originalRequestSource === undefined) {
+ delete process.env.E2B_USER_AGENT_SOURCE
+ } else {
+ process.env.E2B_USER_AGENT_SOURCE = originalRequestSource
+ }
+})
+
function createMockResponse(
status: number,
error: unknown,
- data?: unknown
+ data?: unknown,
+ headers: Headers = new Headers()
): {
- response: { status: number; ok: boolean }
+ response: {
+ status: number
+ statusText: string
+ ok: boolean
+ headers: Headers
+ }
error: unknown
data: unknown
} {
return {
- response: { status, ok: status >= 200 && status < 300 },
+ response: {
+ status,
+ statusText: '',
+ ok: status >= 200 && status < 300,
+ headers,
+ },
error,
data,
}
@@ -117,6 +138,34 @@ describe('handleApiError', () => {
})
})
+ test('does not change failed response errors in CI', () => {
+ process.env.E2B_USER_AGENT_SOURCE = 'ci'
+ const res = createMockResponse(
+ 500,
+ { message: 'Internal error' },
+ undefined,
+ new Headers({ 'X-E2B-Trace-ID': 'trace-123' })
+ )
+
+ const err = handleApiError(res as any)
+
+ assert.equal(err?.message, '500: Internal error')
+ })
+
+ test('does not change failed response errors outside CI', () => {
+ delete process.env.E2B_USER_AGENT_SOURCE
+ const res = createMockResponse(
+ 500,
+ { message: 'Internal error' },
+ undefined,
+ new Headers({ 'X-E2B-Trace-ID': 'trace-123' })
+ )
+
+ const err = handleApiError(res as any)
+
+ assert.equal(err?.message, '500: Internal error')
+ })
+
describe('success responses', () => {
test('returns undefined for 200 success', () => {
const res = createMockResponse(200, undefined, { id: '123' })
diff --git a/packages/js-sdk/tests/api/snapshot.test.ts b/packages/js-sdk/tests/api/snapshot.test.ts
index 828389d14..a0a52308a 100644
--- a/packages/js-sdk/tests/api/snapshot.test.ts
+++ b/packages/js-sdk/tests/api/snapshot.test.ts
@@ -3,24 +3,32 @@ import { assert } from 'vitest'
import { sandboxTest, isDebug } from '../setup.js'
import { Sandbox } from '../../src'
-sandboxTest.skipIf(isDebug)('pause sandbox', async ({ sandbox }) => {
- await Sandbox.pause(sandbox.sandboxId)
- assert.isFalse(
- await sandbox.isRunning(),
- 'Sandbox should not be running after pause'
- )
-})
+sandboxTest.skipIf(isDebug)(
+ 'pause sandbox',
+ async ({ sandbox }) => {
+ await Sandbox.pause(sandbox.sandboxId)
+ assert.isFalse(
+ await sandbox.isRunning(),
+ 'Sandbox should not be running after pause'
+ )
+ },
+ 120_000
+)
-sandboxTest.skipIf(isDebug)('resume sandbox', async ({ sandbox }) => {
- await Sandbox.pause(sandbox.sandboxId)
- assert.isFalse(
- await sandbox.isRunning(),
- 'Sandbox should not be running after pause'
- )
+sandboxTest.skipIf(isDebug)(
+ 'resume sandbox',
+ async ({ sandbox }) => {
+ await Sandbox.pause(sandbox.sandboxId)
+ assert.isFalse(
+ await sandbox.isRunning(),
+ 'Sandbox should not be running after pause'
+ )
- await Sandbox.connect(sandbox.sandboxId)
- assert.isTrue(
- await sandbox.isRunning(),
- 'Sandbox should be running after resume'
- )
-})
+ await Sandbox.connect(sandbox.sandboxId)
+ assert.isTrue(
+ await sandbox.isRunning(),
+ 'Sandbox should be running after resume'
+ )
+ },
+ 120_000
+)
diff --git a/packages/js-sdk/tests/connectionConfig.test.ts b/packages/js-sdk/tests/connectionConfig.test.ts
index df826d969..a81de70ac 100644
--- a/packages/js-sdk/tests/connectionConfig.test.ts
+++ b/packages/js-sdk/tests/connectionConfig.test.ts
@@ -14,6 +14,7 @@ beforeEach(() => {
E2B_DOMAIN: process.env.E2B_DOMAIN,
E2B_SANDBOX_URL: process.env.E2B_SANDBOX_URL,
E2B_DEBUG: process.env.E2B_DEBUG,
+ E2B_USER_AGENT_SOURCE: process.env.E2B_USER_AGENT_SOURCE,
}
})
@@ -169,10 +170,23 @@ test('setIntegration appends the integration to the user agent', () => {
const config = new ConnectionConfig()
assert.equal(config.headers?.['User-Agent']?.startsWith('e2b-js-sdk/'), true)
- assert.equal(
- config.headers?.['User-Agent']?.endsWith(' testing/version'),
- true
- )
+ assert.include(config.headers?.['User-Agent']?.split(' '), 'testing/version')
+})
+
+test('user agent includes the configured traffic source', () => {
+ process.env.E2B_USER_AGENT_SOURCE = 'ci'
+
+ const config = new ConnectionConfig()
+
+ assert.equal(config.headers?.['User-Agent']?.endsWith(' source/ci'), true)
+})
+
+test('user agent ignores an unsafe traffic source', () => {
+ process.env.E2B_USER_AGENT_SOURCE = 'ci bad\nheader'
+
+ const config = new ConnectionConfig()
+
+ assert.equal(config.headers?.['User-Agent']?.includes('source/'), false)
})
test('integration survives config rebuilds', () => {
@@ -180,9 +194,9 @@ test('integration survives config rebuilds', () => {
const config = new ConnectionConfig()
const rebuiltConfig = new ConnectionConfig({ ...config })
- assert.equal(
- rebuiltConfig.headers?.['User-Agent']?.endsWith(' testing/version'),
- true
+ assert.include(
+ rebuiltConfig.headers?.['User-Agent']?.split(' '),
+ 'testing/version'
)
})
@@ -192,10 +206,7 @@ test('setIntegration does not retro-tag configs built earlier', () => {
const after = new ConnectionConfig()
assert.equal(before.headers?.['User-Agent']?.includes('testing'), false)
- assert.equal(
- after.headers?.['User-Agent']?.endsWith(' testing/version'),
- true
- )
+ assert.include(after.headers?.['User-Agent']?.split(' '), 'testing/version')
})
test('clearing the integration restores the plain user agent', () => {
diff --git a/packages/js-sdk/tests/logs.test.ts b/packages/js-sdk/tests/logs.test.ts
index e22dc3dac..7d9b491da 100644
--- a/packages/js-sdk/tests/logs.test.ts
+++ b/packages/js-sdk/tests/logs.test.ts
@@ -1,7 +1,16 @@
-import { assert, describe, test } from 'vitest'
-import { createRpcLogger } from '../src/logs'
+import { afterEach, assert, describe, test } from 'vitest'
+import { createApiLogger, createRpcLogger } from '../src/logs'
const req = { url: 'http://localhost:49983/process.Process/Start' } as any
+const originalRequestSource = process.env.E2B_USER_AGENT_SOURCE
+
+afterEach(() => {
+ if (originalRequestSource === undefined) {
+ delete process.env.E2B_USER_AGENT_SOURCE
+ } else {
+ process.env.E2B_USER_AGENT_SOURCE = originalRequestSource
+ }
+})
describe('createRpcLogger', () => {
test('logs unary responses containing bigint fields without throwing', async () => {
@@ -37,3 +46,60 @@ describe('createRpcLogger', () => {
])
})
})
+
+describe('createApiLogger', () => {
+ test('observes requests without replacing them', async () => {
+ const logs: any[][] = []
+ const middleware = createApiLogger({
+ info: (...args) => logs.push(args),
+ })
+ const request = new Request('https://api.e2b.app/sandboxes')
+
+ const result = await middleware.onRequest?.({ request } as any)
+
+ assert.isUndefined(result)
+ assert.deepEqual(logs, [['Request GET https://api.e2b.app/sandboxes']])
+ })
+
+ test('logs the E2B trace ID for CI failed responses', async () => {
+ const logs: any[][] = []
+ const middleware = createApiLogger(
+ {
+ error: (...args) => logs.push(args),
+ },
+ true
+ )
+ const response = new Response(null, {
+ status: 500,
+ statusText: 'Internal Server Error',
+ headers: { 'X-E2B-Trace-ID': 'trace-123' },
+ })
+
+ const result = await middleware.onResponse?.({ response } as any)
+
+ assert.isUndefined(result)
+ assert.deepEqual(logs, [
+ ['Response:', 500, 'Internal Server Error', 'trace_id=trace-123'],
+ ])
+ })
+
+ test('does not log the E2B trace ID outside CI', async () => {
+ const logs: any[][] = []
+ const middleware = createApiLogger(
+ {
+ error: (...args) => logs.push(args),
+ },
+ false
+ )
+ const response = new Response(null, {
+ status: 500,
+ statusText: 'Internal Server Error',
+ headers: { 'X-E2B-Trace-ID': 'trace-123' },
+ })
+
+ const result = await middleware.onResponse?.({ response } as any)
+
+ assert.isUndefined(result)
+ assert.deepEqual(logs, [['Response:', 500, 'Internal Server Error']])
+ })
+})
diff --git a/packages/js-sdk/tests/runtimes/cloudflare-deploy/wrangler.jsonc b/packages/js-sdk/tests/runtimes/cloudflare-deploy/wrangler.jsonc
index 5594e5be3..013e14409 100644
--- a/packages/js-sdk/tests/runtimes/cloudflare-deploy/wrangler.jsonc
+++ b/packages/js-sdk/tests/runtimes/cloudflare-deploy/wrangler.jsonc
@@ -3,4 +3,5 @@
"main": "worker.mjs",
"compatibility_date": "2026-03-01",
"compatibility_flags": ["nodejs_compat"],
+ "vars": { "E2B_USER_AGENT_SOURCE": "ci" },
}
diff --git a/packages/js-sdk/tests/runtimes/cloudflare/vitest.config.mts b/packages/js-sdk/tests/runtimes/cloudflare/vitest.config.mts
index 6b55b8a82..838f38bce 100644
--- a/packages/js-sdk/tests/runtimes/cloudflare/vitest.config.mts
+++ b/packages/js-sdk/tests/runtimes/cloudflare/vitest.config.mts
@@ -33,6 +33,9 @@ const SDK_ERROR_NAMES = new Set([
// Cloudflare infrastructure.
export default defineConfig(
createCloudflareVitestConfig({
+ maxWorkers: process.env.E2B_TEST_MAX_WORKERS
+ ? Number(process.env.E2B_TEST_MAX_WORKERS)
+ : undefined,
exclude: [
'tests/template/**',
// Inspects the host-built dist/index.mjs via node:fs, which workerd's
diff --git a/packages/js-sdk/tests/sandbox/commands/sandboxKilledDuringRun.test.ts b/packages/js-sdk/tests/sandbox/commands/sandboxKilledDuringRun.test.ts
index 511a7a38a..a6f9bfbef 100644
--- a/packages/js-sdk/tests/sandbox/commands/sandboxKilledDuringRun.test.ts
+++ b/packages/js-sdk/tests/sandbox/commands/sandboxKilledDuringRun.test.ts
@@ -12,9 +12,10 @@ sandboxTest.skipIf(isDebug)(
const err = await cmd.wait().catch((e) => e)
expect(err).toBeInstanceOf(TimeoutError)
- // The health check confirms the sandbox is gone, so the error states it outright
- expect(err.message).toContain(
- 'sandbox was killed or reached its end of life'
+ // The proxy emits Unavailable at a frame boundary; a partial frame remains a
+ // transport failure and is disambiguated by the SDK's sandbox health check.
+ expect(err.message).toMatch(
+ /ended before the stream completed|sandbox was killed or reached its end of life/
)
}
)
diff --git a/packages/js-sdk/tests/sandbox/fork.test.ts b/packages/js-sdk/tests/sandbox/fork.test.ts
index da3d30b9a..b33959e4c 100644
--- a/packages/js-sdk/tests/sandbox/fork.test.ts
+++ b/packages/js-sdk/tests/sandbox/fork.test.ts
@@ -4,42 +4,50 @@ import { sandboxTest, isDebug, TEST_API_KEY } from '../setup.js'
import { Sandbox } from '../../src'
import { InvalidArgumentError, SandboxNotFoundError } from '../../src/errors'
-sandboxTest.skipIf(isDebug)('fork a sandbox', async ({ sandbox }) => {
- await sandbox.files.write('/home/user/state.txt', 'state before fork')
-
- const forks = await sandbox.fork()
- assert.equal(forks.length, 1)
-
- const fork = forks[0]
- assert.instanceOf(fork, Sandbox)
- if (!(fork instanceof Sandbox)) {
- return
- }
-
- try {
- assert.notEqual(fork.sandboxId, sandbox.sandboxId)
-
- // The original sandbox keeps running
- assert.isTrue(await sandbox.isRunning())
- assert.isTrue(await fork.isRunning())
-
- // The fork inherits the filesystem state
- const content = await fork.files.read('/home/user/state.txt')
- assert.equal(content, 'state before fork')
-
- // The fork is independent of the original
- await fork.files.write('/home/user/state.txt', 'modified in fork')
- const originalContent = await sandbox.files.read('/home/user/state.txt')
- assert.equal(originalContent, 'state before fork')
- } finally {
- await fork.kill()
- }
-})
+sandboxTest.skipIf(isDebug)(
+ 'fork a sandbox',
+ async ({ sandbox }) => {
+ await sandbox.files.write('/home/user/state.txt', 'state before fork')
+
+ const forks = await sandbox.fork({ requestTimeoutMs: 60_000 })
+ assert.equal(forks.length, 1)
+
+ const fork = forks[0]
+ assert.instanceOf(fork, Sandbox)
+ if (!(fork instanceof Sandbox)) {
+ return
+ }
+
+ try {
+ assert.notEqual(fork.sandboxId, sandbox.sandboxId)
+
+ // The original sandbox keeps running
+ assert.isTrue(await sandbox.isRunning())
+ assert.isTrue(await fork.isRunning())
+
+ // The fork inherits the filesystem state
+ const content = await fork.files.read('/home/user/state.txt')
+ assert.equal(content, 'state before fork')
+
+ // The fork is independent of the original
+ await fork.files.write('/home/user/state.txt', 'modified in fork')
+ const originalContent = await sandbox.files.read('/home/user/state.txt')
+ assert.equal(originalContent, 'state before fork')
+ } finally {
+ await fork.kill()
+ }
+ },
+ 90_000
+)
sandboxTest.skipIf(isDebug)(
'fork a sandbox multiple times',
async ({ sandbox }) => {
- const forks = await sandbox.fork({ count: 2, timeoutMs: 60_000 })
+ const forks = await sandbox.fork({
+ count: 2,
+ timeoutMs: 60_000,
+ requestTimeoutMs: 60_000,
+ })
assert.equal(forks.length, 2)
const forkedSandboxes = forks.filter(
@@ -59,13 +67,16 @@ sandboxTest.skipIf(isDebug)(
} finally {
await Promise.all(forkedSandboxes.map((s) => s.kill()))
}
- }
+ },
+ 90_000
)
sandboxTest.skipIf(isDebug)(
'fork a sandbox by ID with the static method',
async ({ sandbox }) => {
- const forks = await Sandbox.fork(sandbox.sandboxId)
+ const forks = await Sandbox.fork(sandbox.sandboxId, {
+ requestTimeoutMs: 60_000,
+ })
assert.equal(forks.length, 1)
const fork = forks[0]
@@ -77,7 +88,8 @@ sandboxTest.skipIf(isDebug)(
await fork.kill()
}
}
- }
+ },
+ 90_000
)
test.skipIf(isDebug)('fork a killed sandbox fails', async () => {
diff --git a/packages/js-sdk/tests/sandbox/git/helpers.test.ts b/packages/js-sdk/tests/sandbox/git/helpers.test.ts
new file mode 100644
index 000000000..d20d0c68c
--- /dev/null
+++ b/packages/js-sdk/tests/sandbox/git/helpers.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test, vi } from 'vitest'
+
+import { cleanupBaseDir } from './helpers.js'
+
+describe('cleanupBaseDir', () => {
+ test('retries a Cloudflare dropped connection once', async () => {
+ const run = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('2: [unknown] Network connection lost.'))
+ .mockResolvedValueOnce(undefined)
+
+ await cleanupBaseDir({ commands: { run } }, '/tmp/test-git/example')
+
+ expect(run).toHaveBeenCalledTimes(2)
+ expect(run).toHaveBeenNthCalledWith(1, 'rm -rf "/tmp/test-git/example"')
+ expect(run).toHaveBeenNthCalledWith(2, 'rm -rf "/tmp/test-git/example"')
+ })
+
+ test('does not retry other cleanup failures', async () => {
+ const error = new Error('permission denied')
+ const run = vi.fn().mockRejectedValue(error)
+
+ await expect(
+ cleanupBaseDir({ commands: { run } }, '/tmp/test-git/example')
+ ).rejects.toBe(error)
+
+ expect(run).toHaveBeenCalledTimes(1)
+ })
+
+ test('propagates the second dropped connection after one retry', async () => {
+ const firstError = new Error('2: [unknown] Network connection lost.')
+ const secondError = new Error('2: [unknown] Network connection lost again.')
+ const run = vi
+ .fn()
+ .mockRejectedValueOnce(firstError)
+ .mockRejectedValueOnce(secondError)
+
+ await expect(
+ cleanupBaseDir({ commands: { run } }, '/tmp/test-git/example')
+ ).rejects.toBe(secondError)
+
+ expect(run).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/packages/js-sdk/tests/sandbox/git/helpers.ts b/packages/js-sdk/tests/sandbox/git/helpers.ts
index 797682f05..4e82ef6a9 100644
--- a/packages/js-sdk/tests/sandbox/git/helpers.ts
+++ b/packages/js-sdk/tests/sandbox/git/helpers.ts
@@ -16,7 +16,20 @@ export async function createBaseDir(sandbox: any) {
}
export async function cleanupBaseDir(sandbox: any, baseDir: string) {
- await sandbox.commands.run(`rm -rf "${baseDir}"`)
+ const command = `rm -rf "${baseDir}"`
+
+ try {
+ await sandbox.commands.run(command)
+ } catch (error) {
+ if (
+ !(error instanceof Error) ||
+ !error.message.includes('Network connection lost')
+ ) {
+ throw error
+ }
+
+ await sandbox.commands.run(command)
+ }
}
export async function createRepo(sandbox: any, baseDir: string) {
@@ -47,11 +60,21 @@ export async function startGitDaemon(sandbox: any, baseDir: string) {
`--enable=receive-pack --informative-errors --listen=127.0.0.1 --port=${port}`,
{ background: true }
)
- await sandbox.commands.run('sleep 1')
+ const remoteUrl = `git://127.0.0.1:${port}/remote.git`
+
+ try {
+ await sandbox.commands.run(
+ `for i in $(seq 1 50); do git ls-remote "${remoteUrl}" >/dev/null 2>&1 && exit 0; sleep 0.1; done; exit 1`
+ )
+ } catch (error) {
+ await handle.kill().catch(() => {})
+ throw error
+ }
+
return {
handle,
remotePath,
- remoteUrl: `git://127.0.0.1:${port}/remote.git`,
+ remoteUrl,
port,
}
}
diff --git a/packages/js-sdk/tests/sandbox/git/reset.test.ts b/packages/js-sdk/tests/sandbox/git/reset.test.ts
index daf8bcd38..a23e1bae0 100644
--- a/packages/js-sdk/tests/sandbox/git/reset.test.ts
+++ b/packages/js-sdk/tests/sandbox/git/reset.test.ts
@@ -7,24 +7,28 @@ import {
createRepoWithCommit,
} from './helpers.js'
-sandboxTest('git reset --hard discards changes', async ({ sandbox }) => {
- const baseDir = await createBaseDir(sandbox)
+sandboxTest(
+ 'git reset --hard discards changes',
+ async ({ sandbox }) => {
+ const baseDir = await createBaseDir(sandbox)
- try {
- const repoPath = await createRepoWithCommit(sandbox, baseDir)
- await sandbox.files.write(`${repoPath}/README.md`, 'changed\n')
+ try {
+ const repoPath = await createRepoWithCommit(sandbox, baseDir)
+ await sandbox.files.write(`${repoPath}/README.md`, 'changed\n')
- const status = await sandbox.git.status(repoPath)
- expect(status.isClean).toBe(false)
+ const status = await sandbox.git.status(repoPath)
+ expect(status.isClean).toBe(false)
- await sandbox.git.reset(repoPath, { mode: 'hard', target: 'HEAD' })
+ await sandbox.git.reset(repoPath, { mode: 'hard', target: 'HEAD' })
- const statusAfter = await sandbox.git.status(repoPath)
- expect(statusAfter.isClean).toBe(true)
+ const statusAfter = await sandbox.git.status(repoPath)
+ expect(statusAfter.isClean).toBe(true)
- const contents = await sandbox.files.read(`${repoPath}/README.md`)
- expect(contents).toBe('hello\n')
- } finally {
- await cleanupBaseDir(sandbox, baseDir)
- }
-})
+ const contents = await sandbox.files.read(`${repoPath}/README.md`)
+ expect(contents).toBe('hello\n')
+ } finally {
+ await cleanupBaseDir(sandbox, baseDir)
+ }
+ },
+ 60_000
+)
diff --git a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
index 28a1999b7..3ad684502 100644
--- a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
+++ b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
@@ -1,7 +1,57 @@
-import { assert, expect, test } from 'vitest'
+import { assert, expect, test, vi } from 'vitest'
import { InvalidArgumentError, Sandbox } from '../../src'
-import { isDebug, template, wait } from '../setup.js'
+import { isDebug, sandboxTest, template } from '../setup.js'
+
+async function waitForState(
+ sandbox: Sandbox,
+ state: 'paused' | 'running'
+): Promise<void> {
+ await vi.waitFor(
+ async () => {
+ assert.equal(
+ (await sandbox.getInfo({ requestTimeoutMs: 5_000 })).state,
+ state
+ )
+ },
+ { timeout: 30_000, interval: 500 }
+ )
+}
+
+async function waitForStatus(url: string, status: number): Promise<void> {
+ await vi.waitFor(
+ async () => {
+ const response = await fetch(url, {
+ signal: AbortSignal.timeout(5_000),
+ })
+ const actualStatus = response.status
+ await response.body?.cancel()
+ assert.equal(actualStatus, status)
+ },
+ { timeout: 30_000, interval: 500 }
+ )
+}
+
+async function triggerAutoResume(url: string): Promise<void> {
+ try {
+ const response = await fetch(url, {
+ signal: AbortSignal.timeout(5_000),
+ })
+ await response.body?.cancel()
+ } catch (error) {
+ // The request itself is the wake signal. A gateway timeout while the
+ // sandbox resumes is an allowed transitional response; other failures
+ // should remain visible.
+ if (!(error instanceof Error) || error.name !== 'TimeoutError') {
+ throw error
+ }
+ }
+}
+
+function withRequestSource(url: string): string {
+ const source = process.env.E2B_USER_AGENT_SOURCE
+ return source ? `${url}?source=${encodeURIComponent(source)}` : url
+}
test.skipIf(isDebug)(
'filesystem-only auto-pause cannot be combined with auto-resume',
@@ -50,20 +100,18 @@ test.skipIf(isDebug)(
})
try {
- await wait(5_000)
-
- assert.equal((await sandbox.getInfo()).state, 'paused')
+ await waitForState(sandbox, 'paused')
assert.isFalse(await sandbox.isRunning())
- await sandbox.connect()
+ await sandbox.connect({ requestTimeoutMs: 120_000 })
- assert.equal((await sandbox.getInfo()).state, 'running')
+ await waitForState(sandbox, 'running')
assert.isTrue(await sandbox.isRunning())
} finally {
await sandbox.kill().catch(() => {})
}
},
- 60_000
+ 210_000
)
test.skipIf(isDebug)(
@@ -87,13 +135,11 @@ test.skipIf(isDebug)(
await sandbox.commands.run('cat /proc/sys/kernel/random/boot_id')
).stdout.trim()
- await wait(5_000)
-
- assert.equal((await sandbox.getInfo()).state, 'paused')
+ await waitForState(sandbox, 'paused')
// A filesystem-only snapshot cannot auto-resume on traffic; connect
// resumes it by cold-booting.
- await sandbox.connect()
+ await sandbox.connect({ requestTimeoutMs: 120_000 })
const persisted = (
await sandbox.files.read('/home/user/auto-pause-marker.txt')
@@ -108,13 +154,14 @@ test.skipIf(isDebug)(
await sandbox.kill().catch(() => {})
}
},
- 60_000
+ 210_000
)
-test.skipIf(isDebug)(
+sandboxTest.skipIf(isDebug)(
'auto-resume wakes paused sandbox on http request',
- async () => {
+ async ({ sandboxTestId }) => {
const sandbox = await Sandbox.create(template, {
+ metadata: { sandboxTestId },
timeoutMs: 3_000,
lifecycle: {
onTimeout: 'pause',
@@ -127,17 +174,25 @@ test.skipIf(isDebug)(
background: true,
})
- await wait(5_000)
-
- const url = `https://${sandbox.getHost(8000)}`
- const res = await fetch(url, { signal: AbortSignal.timeout(15_000) })
+ await waitForState(sandbox, 'paused')
- assert.equal(res.status, 200)
- assert.equal((await sandbox.getInfo()).state, 'running')
+ const url = withRequestSource(`https://${sandbox.getHost(8000)}`)
+ await triggerAutoResume(url)
+ await waitForState(sandbox, 'running')
+ await waitForStatus(url, 200)
assert.isTrue(await sandbox.isRunning())
+ } catch (error) {
+ let state = 'unknown'
+ try {
+ state = (await sandbox.getInfo({ requestTimeoutMs: 5_000 })).state
+ } catch {}
+ console.error(
+ `\n[AUTO-RESUME FAILED] Sandbox ID: ${sandbox.sandboxId}, state=${state}`
+ )
+ throw error
} finally {
await sandbox.kill().catch(() => {})
}
},
- 60_000
+ 150_000
)
diff --git a/packages/js-sdk/tests/sandbox/network.test.ts b/packages/js-sdk/tests/sandbox/network.test.ts
index 82a8f2000..ef6359f42 100644
--- a/packages/js-sdk/tests/sandbox/network.test.ts
+++ b/packages/js-sdk/tests/sandbox/network.test.ts
@@ -1,9 +1,28 @@
-import { assert, expect, describe } from 'vitest'
+import { assert, expect, describe, vi } from 'vitest'
import { CommandExitError, Sandbox } from '../../src'
import { sandboxTest, isDebug, template } from '../setup.js'
import { httpbinTemplate } from '../template.js'
+async function waitForStatus(
+ url: string,
+ status: number,
+ init?: RequestInit
+): Promise<void> {
+ await vi.waitFor(
+ async () => {
+ const response = await fetch(url, {
+ ...init,
+ signal: AbortSignal.timeout(5_000),
+ })
+ const actualStatus = response.status
+ await response.body?.cancel()
+ assert.equal(actualStatus, status)
+ },
+ { timeout: 20_000, interval: 500 }
+ )
+}
+
describe('allow only 1.1.1.1', () => {
sandboxTest.override({
sandboxOpts: {
@@ -142,24 +161,20 @@ describe('allowPublicTraffic=false', () => {
background: true,
})
- // Wait for server to start
- await new Promise((resolve) => setTimeout(resolve, 3000))
-
// Get the public URL for the sandbox
const sandboxUrl = `https://${sandbox.getHost(port)}`
// Test 1: Request without traffic access token should fail with 403
- const response1 = await fetch(sandboxUrl)
- assert.equal(response1.status, 403)
+ await waitForStatus(sandboxUrl, 403)
// Test 2: Request with valid traffic access token should succeed
- const response2 = await fetch(sandboxUrl, {
+ await waitForStatus(sandboxUrl, 200, {
headers: {
'e2b-traffic-access-token': sandbox.trafficAccessToken,
},
})
- assert.equal(response2.status, 200)
- }
+ },
+ 60_000
)
})
@@ -181,16 +196,13 @@ describe('allowPublicTraffic=true', () => {
background: true,
})
- // Wait for server to start
- await new Promise((resolve) => setTimeout(resolve, 3000))
-
// Get the public URL for the sandbox
const sandboxUrl = `https://${sandbox.getHost(port)}`
// Request without traffic access token should succeed (public access enabled)
- const response = await fetch(sandboxUrl)
- assert.equal(response.status, 200)
- }
+ await waitForStatus(sandboxUrl, 200)
+ },
+ 60_000
)
})
@@ -336,7 +348,7 @@ describe('maskRequestHost option', () => {
const outputFile = '/tmp/headers.txt'
// Start a Python HTTP server that captures request headers and writes them to a file
- sandbox.commands.run(
+ await sandbox.commands.run(
`python3 -c "
import http.server
class H(http.server.BaseHTTPRequestHandler):
@@ -352,28 +364,21 @@ http.server.HTTPServer(('', ${port}), H).handle_request()
{ background: true }
)
- await new Promise((resolve) => setTimeout(resolve, 2000))
-
// Get the public URL for the sandbox
const sandboxUrl = `https://${sandbox.getHost(port)}`
// Make a request from OUTSIDE the sandbox through the proxy
// The Host header should be modified according to maskRequestHost
- try {
- await fetch(sandboxUrl, { signal: AbortSignal.timeout(5000) })
- } catch (error) {
- // Request may timeout, but headers are captured by the server
- }
-
- await new Promise((resolve) => setTimeout(resolve, 1000))
+ await waitForStatus(sandboxUrl, 200)
// Read the captured headers from inside the sandbox
- const result = await sandbox.commands.run(`cat ${outputFile}`)
+ const headers = await sandbox.files.read(outputFile)
// Verify the Host header was modified according to maskRequestHost
- assert.include(result.stdout, 'Host:')
- assert.include(result.stdout, 'custom-host.example.com')
- assert.include(result.stdout, `${port}`)
- }
+ assert.include(headers, 'Host:')
+ assert.include(headers, 'custom-host.example.com')
+ assert.include(headers, `${port}`)
+ },
+ 60_000
)
})
diff --git a/packages/js-sdk/tests/sandbox/pty/kill.test.ts b/packages/js-sdk/tests/sandbox/pty/kill.test.ts
index f60251577..1b8cec15a 100644
--- a/packages/js-sdk/tests/sandbox/pty/kill.test.ts
+++ b/packages/js-sdk/tests/sandbox/pty/kill.test.ts
@@ -1,6 +1,5 @@
import { sandboxTest } from '../../setup'
import { assert, expect } from 'vitest'
-import { ProcessExitError } from '../../../src/index.js'
sandboxTest('kill PTY', async ({ sandbox }) => {
const terminal = await sandbox.pty.create({
@@ -12,10 +11,12 @@ sandboxTest('kill PTY', async ({ sandbox }) => {
const result = await sandbox.pty.kill(terminal.pid)
assert.isTrue(result)
- // The PTY process should no longer be running.
+ // PTY teardown is asynchronous, so wait for the process to disappear.
await expect(
- sandbox.commands.run(`kill -0 ${terminal.pid}`)
- ).rejects.toThrowError(ProcessExitError)
+ sandbox.commands.run(
+ `for i in $(seq 1 50); do kill -0 ${terminal.pid} 2>/dev/null || exit 0; sleep 0.1; done; exit 1`
+ )
+ ).resolves.toMatchObject({ exitCode: 0 })
})
sandboxTest('kill non-existing PTY', async ({ sandbox }) => {
diff --git a/packages/js-sdk/tests/sandbox/snapshot-api.test.ts b/packages/js-sdk/tests/sandbox/snapshot-api.test.ts
index 3c6432af6..1fb573e8a 100644
--- a/packages/js-sdk/tests/sandbox/snapshot-api.test.ts
+++ b/packages/js-sdk/tests/sandbox/snapshot-api.test.ts
@@ -3,6 +3,8 @@ import { assert } from 'vitest'
import { sandboxTest, isDebug } from '../setup.js'
import { Sandbox } from '../../src'
+const SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS = 120_000
+
sandboxTest.skipIf(isDebug)(
'create a snapshot from sandbox',
async ({ sandbox }) => {
@@ -35,6 +37,7 @@ sandboxTest.skipIf(isDebug)(
// Create a new sandbox from the snapshot
const newSandbox = await Sandbox.create(snapshot.snapshotId, {
metadata: { sandboxTestId: `${sandboxTestId}-from-snapshot` },
+ requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
})
try {
@@ -47,7 +50,8 @@ sandboxTest.skipIf(isDebug)(
} finally {
await Sandbox.deleteSnapshot(snapshot.snapshotId)
}
- }
+ },
+ 180_000
)
sandboxTest.skipIf(isDebug)(
@@ -59,46 +63,48 @@ sandboxTest.skipIf(isDebug)(
const snapshot = await sandbox.createSnapshot()
+ let sandbox1: Sandbox | undefined
+ let sandbox2: Sandbox | undefined
try {
// Create two sandboxes from the same snapshot
- const sandbox1 = await Sandbox.create(snapshot.snapshotId, {
+ sandbox1 = await Sandbox.create(snapshot.snapshotId, {
metadata: { sandboxTestId: `${sandboxTestId}-branch-1` },
+ requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
})
- const sandbox2 = await Sandbox.create(snapshot.snapshotId, {
+ sandbox2 = await Sandbox.create(snapshot.snapshotId, {
metadata: { sandboxTestId: `${sandboxTestId}-branch-2` },
+ requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
})
- try {
- // Both should have the same initial content
- const content1 = await sandbox1.files.read('/home/user/shared.txt')
- const content2 = await sandbox2.files.read('/home/user/shared.txt')
-
- assert.equal(content1, testContent)
- assert.equal(content2, testContent)
-
- // Modify one sandbox - should not affect the other
- await sandbox1.files.write(
- '/home/user/shared.txt',
- 'modified in sandbox1'
- )
-
- const modifiedContent = await sandbox1.files.read(
- '/home/user/shared.txt'
- )
- const unchangedContent = await sandbox2.files.read(
- '/home/user/shared.txt'
- )
-
- assert.equal(modifiedContent, 'modified in sandbox1')
- assert.equal(unchangedContent, testContent)
- } finally {
- await sandbox1.kill()
- await sandbox2.kill()
- }
+ // Both should have the same initial content
+ const content1 = await sandbox1.files.read('/home/user/shared.txt')
+ const content2 = await sandbox2.files.read('/home/user/shared.txt')
+
+ assert.equal(content1, testContent)
+ assert.equal(content2, testContent)
+
+ // Modify one sandbox - should not affect the other
+ await sandbox1.files.write(
+ '/home/user/shared.txt',
+ 'modified in sandbox1'
+ )
+
+ const modifiedContent = await sandbox1.files.read('/home/user/shared.txt')
+ const unchangedContent = await sandbox2.files.read(
+ '/home/user/shared.txt'
+ )
+
+ assert.equal(modifiedContent, 'modified in sandbox1')
+ assert.equal(unchangedContent, testContent)
} finally {
+ await Promise.all([
+ sandbox1?.kill().catch(() => {}),
+ sandbox2?.kill().catch(() => {}),
+ ])
await Sandbox.deleteSnapshot(snapshot.snapshotId)
}
- }
+ },
+ 300_000
)
sandboxTest.skipIf(isDebug)('list snapshots', async ({ sandbox }) => {
@@ -217,6 +223,7 @@ sandboxTest.skipIf(isDebug)(
try {
const newSandbox = await Sandbox.create(snapshot.snapshotId, {
metadata: { sandboxTestId: `${sandboxTestId}-fs-test` },
+ requestTimeoutMs: SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS,
})
try {
@@ -236,5 +243,6 @@ sandboxTest.skipIf(isDebug)(
} finally {
await Sandbox.deleteSnapshot(snapshot.snapshotId)
}
- }
+ },
+ 180_000
)
diff --git a/packages/js-sdk/tests/sandbox/snapshot.test.ts b/packages/js-sdk/tests/sandbox/snapshot.test.ts
index ac0dead40..1ae5d6b9d 100644
--- a/packages/js-sdk/tests/sandbox/snapshot.test.ts
+++ b/packages/js-sdk/tests/sandbox/snapshot.test.ts
@@ -2,6 +2,39 @@ import { assert, describe } from 'vitest'
import { sandboxTest, isDebug } from '../setup.js'
+async function waitForHttpStatus(
+ url: string,
+ expectedStatus: number,
+ timeoutMs = 30_000
+) {
+ const deadline = Date.now() + timeoutMs
+ let lastStatus: number | undefined
+
+ while (Date.now() < deadline) {
+ const requestTimeoutMs = Math.min(5_000, deadline - Date.now())
+ const controller = new AbortController()
+ const requestTimeout = setTimeout(
+ () => controller.abort(),
+ requestTimeoutMs
+ )
+ try {
+ const response = await fetch(url, { signal: controller.signal })
+ lastStatus = response.status
+ await response.body?.cancel()
+ if (lastStatus === expectedStatus) return
+ } catch {
+ // The sandbox proxy may not have a route until the guest server is ready.
+ } finally {
+ clearTimeout(requestTimeout)
+ }
+ await new Promise((resolve) => setTimeout(resolve, 500))
+ }
+
+ assert.fail(
+ `Timed out waiting for ${url} to return ${expectedStatus}; last status: ${lastStatus ?? 'request failed'}`
+ )
+}
+
sandboxTest.skipIf(isDebug)(
'pause and resume a sandbox',
async ({ sandbox }) => {
@@ -146,21 +179,18 @@ sandboxTest.skipIf(isDebug)(
let url = await sandbox.getHost(8000)
- await new Promise((resolve) => setTimeout(resolve, 5000))
+ await waitForHttpStatus(`https://${url}`, 200)
- const response1 = await fetch(`https://${url}`)
- assert.equal(response1.status, 200)
-
- await sandbox.pause()
+ await sandbox.pause({ requestTimeoutMs: 120_000 })
assert.isFalse(await sandbox.isRunning())
- await sandbox.connect()
+ await sandbox.connect({ requestTimeoutMs: 120_000 })
assert.isTrue(await sandbox.isRunning())
url = await sandbox.getHost(8000)
- const response2 = await fetch(`https://${url}`)
- assert.equal(response2.status, 200)
- }
+ await waitForHttpStatus(`https://${url}`, 200)
+ },
+ 150_000
)
sandboxTest.skipIf(isDebug)(
@@ -183,14 +213,30 @@ sandboxTest.skipIf(isDebug)(
).stdout.trim()
// Filesystem-only snapshot: no memory is captured, so resuming cold-boots.
- await sandbox.pause({ keepMemory: false })
+ await sandbox.pause({
+ keepMemory: false,
+ requestTimeoutMs: 120_000,
+ })
assert.isFalse(await sandbox.isRunning())
// Resume the paused sandbox; a filesystem-only pause keeps no memory, so
// connect() cold-boots (reboots) it. connect() returns the same handle, and
// its credentials stay valid across the resume (the backend re-binds the
// same envd access token on the cold boot).
- const resumedSandbox = await sandbox.connect()
+ let resumedSandbox
+ try {
+ resumedSandbox = await sandbox.connect({ requestTimeoutMs: 120_000 })
+ } catch (error) {
+ // Placement can transiently time out while the cold boot is scheduled.
+ // Retry only the backend response that explicitly asks the caller to do so.
+ if (
+ !(error instanceof Error) ||
+ !error.message.includes('Failed to place sandbox: placement timed out')
+ ) {
+ throw error
+ }
+ resumedSandbox = await sandbox.connect({ requestTimeoutMs: 120_000 })
+ }
assert.equal(resumedSandbox.sandboxId, sandbox.sandboxId)
assert.isTrue(await resumedSandbox.isRunning())
@@ -203,5 +249,6 @@ sandboxTest.skipIf(isDebug)(
await resumedSandbox.commands.run('cat /proc/sys/kernel/random/boot_id')
).stdout.trim()
assert.notEqual(bootAfter, bootBefore)
- }
+ },
+ 270_000
)
diff --git a/packages/js-sdk/vitest.config.mts b/packages/js-sdk/vitest.config.mts
index 63439b011..455550601 100644
--- a/packages/js-sdk/vitest.config.mts
+++ b/packages/js-sdk/vitest.config.mts
@@ -3,8 +3,12 @@ import { playwright } from '@vitest/browser-playwright'
import { config } from 'dotenv'
const env = config()
+const maxWorkers = process.env.E2B_TEST_MAX_WORKERS
+ ? Number(process.env.E2B_TEST_MAX_WORKERS)
+ : undefined
export default defineConfig({
test: {
+ maxWorkers,
projects: [
{
test: {
@@ -23,6 +27,7 @@ export default defineConfig({
isolate: true,
globals: false,
testTimeout: 30_000,
+ maxWorkers,
environment: 'node',
bail: 0,
setupFiles: ['tests/globalFetchFallback.setup.ts'],
@@ -59,6 +64,7 @@ export default defineConfig({
include: ['tests/template/**/*.test.ts'],
globals: false,
testTimeout: 180_000,
+ maxWorkers,
environment: 'node',
setupFiles: ['tests/globalFetchFallback.setup.ts'],
},
diff --git a/packages/python-sdk/e2b/api/__init__.py b/packages/python-sdk/e2b/api/__init__.py
index b33fdba62..d36df92a2 100644
--- a/packages/python-sdk/e2b/api/__init__.py
+++ b/packages/python-sdk/e2b/api/__init__.py
@@ -34,40 +34,58 @@ def encode_path_param(value: str) -> str:
return quote(value, safe="")
-def make_logging_event_hooks(log: Optional[logging.Logger]) -> dict:
+def make_logging_event_hooks(
+ log: Optional[logging.Logger], include_diagnostics: bool = False
+) -> dict:
"""Build synchronous httpx ``event_hooks`` that log requests and responses
to the given ``logging.Logger``. Requests log at ``INFO``, successful
responses at ``INFO`` and responses with status >= 400 at ``ERROR``.
- Returns no hooks when ``log`` is ``None`` so that nothing is logged unless a
- logger was explicitly supplied."""
- if log is None:
+ Returns no hooks when ``log`` is ``None`` unless CI diagnostics are enabled;
+ that mode logs failed responses only."""
+ if log is None and not include_diagnostics:
return {}
+ response_log = log or logging.getLogger("e2b.ci")
+
def on_request(request) -> None:
- log.info(f"Request {request.method} {request.url}")
+ if log is not None:
+ log.info(f"Request {request.method} {request.url}")
def on_response(response: Response) -> None:
if response.status_code >= 400:
- log.error(f"Response {response.status_code}")
- else:
+ trace_id = (
+ response.headers.get("X-E2B-Trace-ID") if include_diagnostics else None
+ )
+ trace_suffix = f" trace_id={trace_id}" if trace_id else ""
+ response_log.error(f"Response {response.status_code}{trace_suffix}")
+ elif log is not None:
log.info(f"Response {response.status_code}")
return {"request": [on_request], "response": [on_response]}
-def make_async_logging_event_hooks(log: Optional[logging.Logger]) -> dict:
+def make_async_logging_event_hooks(
+ log: Optional[logging.Logger], include_diagnostics: bool = False
+) -> dict:
"""Asynchronous counterpart of :func:`make_logging_event_hooks`."""
- if log is None:
+ if log is None and not include_diagnostics:
return {}
+ response_log = log or logging.getLogger("e2b.ci")
+
async def on_request(request) -> None:
- log.info(f"Request {request.method} {request.url}")
+ if log is not None:
+ log.info(f"Request {request.method} {request.url}")
async def on_response(response: Response) -> None:
if response.status_code >= 400:
- log.error(f"Response {response.status_code}")
- else:
+ trace_id = (
+ response.headers.get("X-E2B-Trace-ID") if include_diagnostics else None
+ )
+ trace_suffix = f" trace_id={trace_id}" if trace_id else ""
+ response_log.error(f"Response {response.status_code}{trace_suffix}")
+ elif log is not None:
log.info(f"Response {response.status_code}")
return {"request": [on_request], "response": [on_response]}
@@ -182,7 +200,10 @@ def handle_api_exception(
)
return api_exception_from_code(
- e.status_code, message, default_exception_class, stack_trace
+ e.status_code,
+ message,
+ default_exception_class,
+ stack_trace,
)
@@ -225,6 +246,7 @@ class ApiClient(AuthenticatedClient):
prefix = ""
self._logger = config.logger
+ self._include_diagnostics = config.request_source == "ci"
headers = {
**default_headers,
@@ -265,10 +287,14 @@ class ApiClient(AuthenticatedClient):
)
def _logging_event_hooks(self) -> dict:
- return make_logging_event_hooks(self._logger)
+ return make_logging_event_hooks(
+ self._logger, include_diagnostics=self._include_diagnostics
+ )
# We need to override the logging hooks for the async usage
class AsyncApiClient(ApiClient):
def _logging_event_hooks(self) -> dict:
- return make_async_logging_event_hooks(self._logger)
+ return make_async_logging_event_hooks(
+ self._logger, include_diagnostics=self._include_diagnostics
+ )
diff --git a/packages/python-sdk/e2b/connection_config.py b/packages/python-sdk/e2b/connection_config.py
index 71bef0991..2ffa7160b 100644
--- a/packages/python-sdk/e2b/connection_config.py
+++ b/packages/python-sdk/e2b/connection_config.py
@@ -1,5 +1,6 @@
import logging
import os
+import re
from typing import cast, Mapping, Optional, Dict, TypedDict, Union
@@ -184,12 +185,22 @@ class ConnectionConfig:
return os.getenv("E2B_SANDBOX_URL")
@staticmethod
- def _build_user_agent() -> str:
+ def _get_request_source() -> Optional[str]:
+ source = os.getenv("E2B_USER_AGENT_SOURCE")
+ if source and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,31}", source):
+ return source
+ return None
+
+ @staticmethod
+ def _build_user_agent(request_source: Optional[str] = None) -> str:
user_agent_parts = [f"e2b-python-sdk/{package_version}"]
if ConnectionConfig._integration:
user_agent_parts.append(ConnectionConfig._integration)
+ if request_source:
+ user_agent_parts.append(f"source/{request_source}")
+
return " ".join(user_agent_parts)
def _apply_user_agent(
@@ -209,7 +220,7 @@ class ConnectionConfig:
headers["User-Agent"] = user_agent_override
return False
- headers["User-Agent"] = self._build_user_agent()
+ headers["User-Agent"] = self._build_user_agent(self.request_source)
return True
def __init__(
@@ -232,6 +243,7 @@ class ConnectionConfig:
self.debug = debug if debug is not None else ConnectionConfig._debug()
self.api_key = api_key or ConnectionConfig._api_key()
self.validate_api_key = validate_api_key
+ self.request_source = ConnectionConfig._get_request_source()
self.headers = {**(headers or {}), **(api_headers or {})}
self._user_agent_is_sdk_built = self._apply_user_agent(
self.headers,
diff --git a/packages/python-sdk/tests/async/sandbox_async/commands/test_sandbox_killed_during_run.py b/packages/python-sdk/tests/async/sandbox_async/commands/test_sandbox_killed_during_run.py
index 2f83f210b..1d99926a6 100644
--- a/packages/python-sdk/tests/async/sandbox_async/commands/test_sandbox_killed_during_run.py
+++ b/packages/python-sdk/tests/async/sandbox_async/commands/test_sandbox_killed_during_run.py
@@ -12,5 +12,10 @@ async def test_kill_sandbox_while_command_is_running(async_sandbox: AsyncSandbox
with pytest.raises(TimeoutException) as exc_info:
await cmd.wait()
- # The health check confirms the sandbox is gone, so the error states it outright
- assert "sandbox was killed or reached its end of life" in str(exc_info.value)
+ # The proxy emits UNAVAILABLE at a frame boundary; a partial frame remains a
+ # transport failure and is disambiguated by the SDK's sandbox health check.
+ message = str(exc_info.value)
+ assert (
+ "ended before the stream completed" in message
+ or "sandbox was killed or reached its end of life" in message
+ )
diff --git a/packages/python-sdk/tests/async/sandbox_async/pty/test_pty_kill.py b/packages/python-sdk/tests/async/sandbox_async/pty/test_pty_kill.py
index 2547270b0..868d1131c 100644
--- a/packages/python-sdk/tests/async/sandbox_async/pty/test_pty_kill.py
+++ b/packages/python-sdk/tests/async/sandbox_async/pty/test_pty_kill.py
@@ -1,6 +1,4 @@
-import pytest
-
-from e2b import AsyncSandbox, CommandExitException
+from e2b import AsyncSandbox
from e2b.sandbox.commands.command_handle import PtySize
@@ -9,9 +7,11 @@ async def test_kill_pty(async_sandbox: AsyncSandbox):
assert await async_sandbox.pty.kill(terminal.pid)
- # The PTY process should no longer be running.
- with pytest.raises(CommandExitException):
- await async_sandbox.commands.run(f"kill -0 {terminal.pid}")
+ # PTY teardown is asynchronous, so wait for the process to disappear.
+ await async_sandbox.commands.run(
+ f"for i in $(seq 1 50); do kill -0 {terminal.pid} 2>/dev/null || exit 0; "
+ "sleep 0.1; done; exit 1"
+ )
async def test_kill_non_existing_pty(async_sandbox: AsyncSandbox):
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py b/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
index feada7d5e..c2a852016 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_config_propagation.py
@@ -98,6 +98,7 @@ async def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_ke
monkeypatch.setattr(sandbox_async_main.SandboxApi, "_cls_connect", mock_connect)
monkeypatch.setattr(ConnectionConfig, "_integration", "testing/version")
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
config = ConnectionConfig(
api_key=test_api_key,
headers=BASE_HEADERS,
@@ -112,9 +113,9 @@ async def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_ke
assert sandbox.connection_config.sandbox_headers["User-Agent"].startswith(
"e2b-python-sdk/"
)
- assert sandbox.connection_config.sandbox_headers["User-Agent"].endswith(
- " testing/version"
- )
+ user_agent_tokens = sandbox.connection_config.sandbox_headers["User-Agent"].split()
+ assert "testing/version" in user_agent_tokens
+ assert "source/ci" in user_agent_tokens
assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Id"] == "sbx-test"
assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Port"] == str(
ConnectionConfig.envd_port
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_create.py b/packages/python-sdk/tests/async/sandbox_async/test_create.py
index f5615974f..79bcabe3e 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_create.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_create.py
@@ -15,6 +15,40 @@ from e2b.exceptions import InvalidArgumentException
from e2b.sandbox.sandbox_api import build_iam_config
+async def wait_for_state(
+ sandbox: AsyncSandbox, state: SandboxState, timeout: float = 30
+) -> None:
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + timeout
+ current_state: SandboxState | None = None
+
+ while loop.time() < deadline:
+ current_state = (await sandbox.get_info()).state
+ if current_state == state:
+ return
+ await asyncio.sleep(0.2)
+
+ pytest.fail(f"sandbox did not reach {state}; last state was {current_state}")
+
+
+async def wait_for_http_status(url: str, status: int, timeout: float = 30) -> None:
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + timeout
+ current_status: int | None = None
+
+ async with httpx.AsyncClient(timeout=5.0) as client:
+ while loop.time() < deadline:
+ try:
+ current_status = (await client.get(url)).status_code
+ except httpx.HTTPError:
+ pass
+ if current_status == status:
+ return
+ await asyncio.sleep(0.5)
+
+ pytest.fail(f"endpoint did not return {status}; last status was {current_status}")
+
+
@pytest.mark.skip_debug()
async def test_start(async_sandbox):
assert await async_sandbox.is_running()
@@ -233,6 +267,7 @@ async def test_keep_memory_none_defaults_to_full_memory(async_sandbox_factory):
@pytest.mark.skip_debug()
async def test_auto_pause_filesystem_only_reboots(async_sandbox_factory):
# keep_memory=False makes the timeout auto-pause filesystem-only, so resuming
# cold-boots the sandbox from disk.
@@ -245,13 +280,18 @@ async def test_auto_pause_filesystem_only_reboots(async_sandbox_factory):
await sandbox.files.write("/home/user/auto-pause-marker.txt", marker)
boot_before = (await sandbox.files.read("/proc/sys/kernel/random/boot_id")).strip()
- await asyncio.sleep(5)
-
- assert (await sandbox.get_info()).state == SandboxState.PAUSED
+ await wait_for_state(sandbox, SandboxState.PAUSED)
# A filesystem-only snapshot cannot auto-resume on traffic; connect resumes
# it by cold-booting.
- resumed = await sandbox.connect()
+ try:
+ resumed = await sandbox.connect(request_timeout=120)
+ except SandboxException as error:
+ # Placement can transiently time out while the cold boot is scheduled.
+ # Retry only the backend response that explicitly asks the caller to do so.
+ if "Failed to place sandbox: placement timed out" not in str(error):
+ raise
+ resumed = await sandbox.connect(request_timeout=120)
persisted = (await resumed.files.read("/home/user/auto-pause-marker.txt")).strip()
assert persisted == marker
@@ -261,24 +301,24 @@ async def test_auto_pause_filesystem_only_reboots(async_sandbox_factory):
@pytest.mark.skip_debug()
async def test_auto_pause_without_auto_resume_requires_connect(async_sandbox_factory):
sandbox = await async_sandbox_factory(
timeout=3,
lifecycle={"on_timeout": "pause", "auto_resume": False},
)
- await asyncio.sleep(5)
-
- assert (await sandbox.get_info()).state == SandboxState.PAUSED
+ await wait_for_state(sandbox, SandboxState.PAUSED)
assert not await sandbox.is_running()
await sandbox.connect()
- assert (await sandbox.get_info()).state == SandboxState.RUNNING
+ await wait_for_state(sandbox, SandboxState.RUNNING)
assert await sandbox.is_running()
@pytest.mark.skip_debug()
async def test_auto_resume_wakes_on_http_request(async_sandbox_factory):
sandbox = await async_sandbox_factory(
timeout=3,
@@ -287,14 +327,12 @@ async def test_auto_resume_wakes_on_http_request(async_sandbox_factory):
cmd = await sandbox.commands.run("python3 -m http.server 8000", background=True)
try:
- await asyncio.sleep(5)
+ await wait_for_state(sandbox, SandboxState.PAUSED)
url = f"https://{sandbox.get_host(8000)}"
- async with httpx.AsyncClient(timeout=15.0) as client:
- res = await client.get(url)
+ await wait_for_http_status(url, 200)
- assert res.status_code == 200
- assert (await sandbox.get_info()).state == SandboxState.RUNNING
+ await wait_for_state(sandbox, SandboxState.RUNNING)
assert await sandbox.is_running()
finally:
try:
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_fork.py b/packages/python-sdk/tests/async/sandbox_async/test_fork.py
index 19f8c7ef2..19f79be4f 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_fork.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_fork.py
@@ -5,10 +5,11 @@ from e2b.exceptions import InvalidArgumentException, SandboxNotFoundException
@pytest.mark.skip_debug()
async def test_fork(async_sandbox: AsyncSandbox):
await async_sandbox.files.write("/home/user/state.txt", "state before fork")
- forks = await async_sandbox.fork()
+ forks = await async_sandbox.fork(request_timeout=60)
assert len(forks) == 1
fork = forks[0]
@@ -35,8 +36,9 @@ async def test_fork(async_sandbox: AsyncSandbox):
@pytest.mark.skip_debug()
async def test_fork_multiple(async_sandbox: AsyncSandbox):
- forks = await async_sandbox.fork(count=2, timeout=60)
+ forks = await async_sandbox.fork(count=2, timeout=60, request_timeout=60)
assert len(forks) == 2
forked_sandboxes = [fork for fork in forks if isinstance(fork, AsyncSandbox)]
@@ -56,8 +58,9 @@ async def test_fork_multiple(async_sandbox: AsyncSandbox):
@pytest.mark.skip_debug()
async def test_fork_by_id(async_sandbox: AsyncSandbox):
- forks = await AsyncSandbox.fork(async_sandbox.sandbox_id)
+ forks = await AsyncSandbox.fork(async_sandbox.sandbox_id, request_timeout=60)
assert len(forks) == 1
fork = forks[0]
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_network.py b/packages/python-sdk/tests/async/sandbox_async/test_network.py
index a174047a0..d99e3c2a3 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_network.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_network.py
@@ -1,5 +1,6 @@
import asyncio
import json
+from unittest.mock import AsyncMock
import httpx
import pytest
@@ -17,15 +18,31 @@ async def wait_for_status(
) -> httpx.Response:
deadline = asyncio.get_running_loop().time() + timeout
response: httpx.Response | None = None
+ last_transport_error: httpx.TransportError | None = None
while asyncio.get_running_loop().time() < deadline:
- response = await client.get(url, headers=headers, follow_redirects=True)
- if response.status_code == status_code:
- return response
+ try:
+ response = await client.get(url, headers=headers, follow_redirects=True)
+ except httpx.TransportError as error:
+ last_transport_error = error
+ else:
+ if response.status_code == status_code:
+ return response
await asyncio.sleep(1)
- assert response is not None
- return response
+ if response is not None:
+ return response
+ assert last_transport_error is not None
+ raise last_transport_error
+
+
+async def test_wait_for_status_retries_transport_errors():
+ response = httpx.Response(200)
+ client = AsyncMock()
+ client.get.side_effect = [httpx.ConnectError("not ready"), response]
+
+ assert await wait_for_status(client, "https://sandbox.test", 200) is response
+ assert client.get.await_count == 2
@pytest.mark.skip_debug()
@@ -287,10 +304,6 @@ async def test_mask_request_host(async_sandbox_factory):
timeout=60,
)
- import asyncio
-
- import httpx
-
port = 8080
output_file = "/tmp/headers.txt"
@@ -306,7 +319,7 @@ class H(http.server.BaseHTTPRequestHandler):
self.send_response(200)
self.end_headers()
def log_message(self, *a): pass
-http.server.HTTPServer(('', {port}), H).handle_request()
+http.server.HTTPServer(('', {port}), H).serve_forever()
" """,
background=True,
)
@@ -319,12 +332,8 @@ http.server.HTTPServer(('', {port}), H).handle_request()
# Make a request from OUTSIDE the sandbox through the proxy
# The Host header should be modified according to mask_request_host
async with httpx.AsyncClient() as client:
- try:
- await client.get(sandbox_url, timeout=5.0)
- except Exception:
- pass
-
- await asyncio.sleep(1)
+ response = await wait_for_status(client, sandbox_url, 200)
+ assert response.status_code == 200
# Read the captured headers from inside the sandbox
result = await async_sandbox.commands.run(f"cat {output_file}")
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_snapshot_api.py b/packages/python-sdk/tests/async/sandbox_async/test_snapshot_api.py
index 80354a62e..086d99d75 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_snapshot_api.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_snapshot_api.py
@@ -1,5 +1,7 @@
import pytest
-from e2b import AsyncSandbox
+from e2b import AsyncSandbox, SandboxException
+
+pytestmark = pytest.mark.timeout(120)
@pytest.mark.skip_debug()
@@ -148,6 +150,7 @@ async def test_delete_snapshot(async_sandbox: AsyncSandbox):
@pytest.mark.skip_debug()
async def test_snapshot_preserves_filesystem(async_sandbox: AsyncSandbox):
app_dir = "/home/user/app"
config_path = f"{app_dir}/config.json"
@@ -162,7 +165,14 @@ async def test_snapshot_preserves_filesystem(async_sandbox: AsyncSandbox):
snapshot = await async_sandbox.create_snapshot()
try:
- new_sandbox = await AsyncSandbox.create(snapshot.snapshot_id)
+ try:
+ new_sandbox = await AsyncSandbox.create(snapshot.snapshot_id)
+ except SandboxException as error:
+ # Placement can transiently time out while the snapshot is restored.
+ # Retry only the backend response that explicitly asks the caller to do so.
+ if "Failed to place sandbox: placement timed out" not in str(error):
+ raise
+ new_sandbox = await AsyncSandbox.create(snapshot.snapshot_id)
try:
dir_exists = await new_sandbox.files.exists(app_dir)
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_snapshot_filesystem_only.py b/packages/python-sdk/tests/async/sandbox_async/test_snapshot_filesystem_only.py
index cdfa597d4..8f6acddb5 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_snapshot_filesystem_only.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_snapshot_filesystem_only.py
@@ -1,5 +1,7 @@
import pytest
-from e2b import AsyncSandbox
+from e2b import AsyncSandbox, SandboxException
+
+pytestmark = pytest.mark.timeout(270)
@pytest.mark.skip_debug()
@@ -11,11 +13,18 @@ async def test_pause_filesystem_only(async_sandbox: AsyncSandbox):
).strip()
# Filesystem-only pause: only the rootfs is persisted, no memory snapshot.
- assert await async_sandbox.pause(keep_memory=False)
+ assert await async_sandbox.pause(keep_memory=False, request_timeout=120)
assert not await async_sandbox.is_running()
# Resuming a filesystem-only snapshot cold-boots (reboots) from the rootfs.
- resumed = await async_sandbox.connect()
+ try:
+ resumed = await async_sandbox.connect(request_timeout=120)
+ except SandboxException as error:
+ # Placement can transiently time out while the cold boot is scheduled.
+ # Retry only the backend response that explicitly asks the caller to do so.
+ if "Failed to place sandbox: placement timed out" not in str(error):
+ raise
+ resumed = await async_sandbox.connect(request_timeout=120)
assert await resumed.is_running()
assert resumed.sandbox_id == async_sandbox.sandbox_id
diff --git a/packages/python-sdk/tests/shared/git/conftest.py b/packages/python-sdk/tests/shared/git/conftest.py
index 60a5e0bdf..7268f3613 100644
--- a/packages/python-sdk/tests/shared/git/conftest.py
+++ b/packages/python-sdk/tests/shared/git/conftest.py
@@ -8,7 +8,9 @@ BASE_DIR = "/tmp/test-git"
@pytest.fixture
def git_sandbox(sandbox_factory):
- return sandbox_factory(timeout=10)
+ # Git suites can cross the old 10-second lifetime while the live backend is
+ # busy, which kills the sandbox in the middle of an otherwise healthy RPC.
+ return sandbox_factory(timeout=60)
@pytest.fixture
@@ -62,11 +64,15 @@ def git_daemon(git_sandbox, git_base_dir):
f"--enable=receive-pack --informative-errors --listen=127.0.0.1 --port={port}"
)
handle = git_sandbox.commands.run(cmd, background=True)
- git_sandbox.commands.run("sleep 1")
+ remote_url = f"git://127.0.0.1:{port}/remote.git"
try:
+ git_sandbox.commands.run(
+ f'for i in $(seq 1 50); do git ls-remote "{remote_url}" >/dev/null 2>&1 '
+ "&& exit 0; sleep 0.1; done; exit 1"
+ )
yield {
"remote_path": remote_path,
- "remote_url": f"git://127.0.0.1:{port}/remote.git",
+ "remote_url": remote_url,
"port": port,
"base_dir": git_base_dir,
}
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/commands/test_sandbox_killed_during_run.py b/packages/python-sdk/tests/sync/sandbox_sync/commands/test_sandbox_killed_during_run.py
index 81dd1cb28..f2b222af3 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/commands/test_sandbox_killed_during_run.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/commands/test_sandbox_killed_during_run.py
@@ -12,5 +12,10 @@ def test_kill_sandbox_while_command_is_running(sandbox: Sandbox):
with pytest.raises(TimeoutException) as exc_info:
cmd.wait()
- # The health check confirms the sandbox is gone, so the error states it outright
- assert "sandbox was killed or reached its end of life" in str(exc_info.value)
+ # The proxy emits UNAVAILABLE at a frame boundary; a partial frame remains a
+ # transport failure and is disambiguated by the SDK's sandbox health check.
+ message = str(exc_info.value)
+ assert (
+ "ended before the stream completed" in message
+ or "sandbox was killed or reached its end of life" in message
+ )
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/pty/test_pty_kill.py b/packages/python-sdk/tests/sync/sandbox_sync/pty/test_pty_kill.py
index e651a8415..a292aa698 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/pty/test_pty_kill.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/pty/test_pty_kill.py
@@ -1,6 +1,4 @@
-import pytest
-
-from e2b import Sandbox, CommandExitException
+from e2b import Sandbox
from e2b.sandbox.commands.command_handle import PtySize
@@ -9,9 +7,11 @@ def test_kill_pty(sandbox: Sandbox):
assert sandbox.pty.kill(terminal.pid)
- # The PTY process should no longer be running.
- with pytest.raises(CommandExitException):
- sandbox.commands.run(f"kill -0 {terminal.pid}")
+ # PTY teardown is asynchronous, so wait for the process to disappear.
+ sandbox.commands.run(
+ f"for i in $(seq 1 50); do kill -0 {terminal.pid} 2>/dev/null || exit 0; "
+ "sleep 0.1; done; exit 1"
+ )
def test_kill_non_existing_pty(sandbox: Sandbox):
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
index 4b0c9c533..f3cfe0c9b 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_config_propagation.py
@@ -91,6 +91,7 @@ def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_key):
monkeypatch.setattr(sandbox_sync_main.SandboxApi, "_cls_connect", mock_connect)
monkeypatch.setattr(ConnectionConfig, "_integration", "testing/version")
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
config = ConnectionConfig(
api_key=test_api_key,
headers=BASE_HEADERS,
@@ -105,9 +106,9 @@ def test_connect_sets_stable_host_routing_headers(monkeypatch, test_api_key):
assert sandbox.connection_config.sandbox_headers["User-Agent"].startswith(
"e2b-python-sdk/"
)
- assert sandbox.connection_config.sandbox_headers["User-Agent"].endswith(
- " testing/version"
- )
+ user_agent_tokens = sandbox.connection_config.sandbox_headers["User-Agent"].split()
+ assert "testing/version" in user_agent_tokens
+ assert "source/ci" in user_agent_tokens
assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Id"] == "sbx-test"
assert sandbox.connection_config.sandbox_headers["E2b-Sandbox-Port"] == str(
ConnectionConfig.envd_port
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py b/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
index ad97fe798..c41fa6387 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
@@ -1,4 +1,4 @@
-from time import sleep
+from time import monotonic, sleep
from typing import Any, cast
from uuid import uuid4
@@ -15,6 +15,36 @@ from e2b.exceptions import InvalidArgumentException
from e2b.sandbox.sandbox_api import SandboxQuery, build_iam_config
+def wait_for_state(sandbox: Sandbox, state: SandboxState, timeout: float = 30) -> None:
+ deadline = monotonic() + timeout
+ current_state: SandboxState | None = None
+
+ while monotonic() < deadline:
+ current_state = sandbox.get_info().state
+ if current_state == state:
+ return
+ sleep(0.2)
+
+ pytest.fail(f"sandbox did not reach {state}; last state was {current_state}")
+
+
+def wait_for_http_status(url: str, status: int, timeout: float = 30) -> None:
+ deadline = monotonic() + timeout
+ current_status: int | None = None
+
+ with httpx.Client(timeout=5.0) as client:
+ while monotonic() < deadline:
+ try:
+ current_status = client.get(url).status_code
+ except httpx.HTTPError:
+ pass
+ if current_status == status:
+ return
+ sleep(0.5)
+
+ pytest.fail(f"endpoint did not return {status}; last status was {current_status}")
+
+
@pytest.mark.skip_debug()
def test_start(sandbox_factory):
sbx = sandbox_factory(timeout=5)
@@ -231,6 +261,7 @@ def test_keep_memory_none_defaults_to_full_memory(sandbox_factory):
@pytest.mark.skip_debug()
def test_auto_pause_filesystem_only_reboots(sandbox_factory):
# keep_memory=False makes the timeout auto-pause filesystem-only, so resuming
# cold-boots the sandbox from disk.
@@ -243,13 +274,18 @@ def test_auto_pause_filesystem_only_reboots(sandbox_factory):
sandbox.files.write("/home/user/auto-pause-marker.txt", marker)
boot_before = sandbox.files.read("/proc/sys/kernel/random/boot_id").strip()
- sleep(5)
-
- assert sandbox.get_info().state == SandboxState.PAUSED
+ wait_for_state(sandbox, SandboxState.PAUSED)
# A filesystem-only snapshot cannot auto-resume on traffic; connect resumes
# it by cold-booting.
- resumed = sandbox.connect()
+ try:
+ resumed = sandbox.connect(request_timeout=120)
+ except SandboxException as error:
+ # Placement can transiently time out while the cold boot is scheduled.
+ # Retry only the backend response that explicitly asks the caller to do so.
+ if "Failed to place sandbox: placement timed out" not in str(error):
+ raise
+ resumed = sandbox.connect(request_timeout=120)
persisted = resumed.files.read("/home/user/auto-pause-marker.txt").strip()
assert persisted == marker
@@ -259,24 +295,24 @@ def test_auto_pause_filesystem_only_reboots(sandbox_factory):
@pytest.mark.skip_debug()
def test_auto_pause_without_auto_resume_requires_connect(sandbox_factory):
sandbox = sandbox_factory(
timeout=3,
lifecycle={"on_timeout": "pause", "auto_resume": False},
)
- sleep(5)
-
- assert sandbox.get_info().state == SandboxState.PAUSED
+ wait_for_state(sandbox, SandboxState.PAUSED)
assert not sandbox.is_running()
sandbox.connect()
- assert sandbox.get_info().state == SandboxState.RUNNING
+ wait_for_state(sandbox, SandboxState.RUNNING)
assert sandbox.is_running()
@pytest.mark.skip_debug()
def test_auto_resume_wakes_on_http_request(sandbox_factory):
sandbox = sandbox_factory(
timeout=3,
@@ -285,13 +321,12 @@ def test_auto_resume_wakes_on_http_request(sandbox_factory):
cmd = sandbox.commands.run("python3 -m http.server 8000", background=True)
try:
- sleep(5)
+ wait_for_state(sandbox, SandboxState.PAUSED)
url = f"https://{sandbox.get_host(8000)}"
- res = httpx.get(url, timeout=15.0)
+ wait_for_http_status(url, 200)
- assert res.status_code == 200
- assert sandbox.get_info().state == SandboxState.RUNNING
+ wait_for_state(sandbox, SandboxState.RUNNING)
assert sandbox.is_running()
finally:
try:
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_fork.py b/packages/python-sdk/tests/sync/sandbox_sync/test_fork.py
index 7159a5310..bf0486f0a 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_fork.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_fork.py
@@ -5,10 +5,11 @@ from e2b.exceptions import InvalidArgumentException, SandboxNotFoundException
@pytest.mark.skip_debug()
def test_fork(sandbox: Sandbox):
sandbox.files.write("/home/user/state.txt", "state before fork")
- forks = sandbox.fork()
+ forks = sandbox.fork(request_timeout=60)
assert len(forks) == 1
fork = forks[0]
@@ -32,8 +33,9 @@ def test_fork(sandbox: Sandbox):
@pytest.mark.skip_debug()
def test_fork_multiple(sandbox: Sandbox):
- forks = sandbox.fork(count=2, timeout=60)
+ forks = sandbox.fork(count=2, timeout=60, request_timeout=60)
assert len(forks) == 2
forked_sandboxes = [fork for fork in forks if isinstance(fork, Sandbox)]
@@ -53,8 +55,9 @@ def test_fork_multiple(sandbox: Sandbox):
@pytest.mark.skip_debug()
def test_fork_by_id(sandbox: Sandbox):
- forks = Sandbox.fork(sandbox.sandbox_id)
+ forks = Sandbox.fork(sandbox.sandbox_id, request_timeout=60)
assert len(forks) == 1
fork = forks[0]
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_network.py b/packages/python-sdk/tests/sync/sandbox_sync/test_network.py
index 0124ce718..60b0cf5c0 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_network.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_network.py
@@ -1,5 +1,6 @@
import json
import time
+from unittest.mock import Mock
import httpx
@@ -18,15 +19,31 @@ def wait_for_status(
) -> httpx.Response:
deadline = time.monotonic() + timeout
response: httpx.Response | None = None
+ last_transport_error: httpx.TransportError | None = None
while time.monotonic() < deadline:
- response = client.get(url, headers=headers, follow_redirects=True)
- if response.status_code == status_code:
- return response
+ try:
+ response = client.get(url, headers=headers, follow_redirects=True)
+ except httpx.TransportError as error:
+ last_transport_error = error
+ else:
+ if response.status_code == status_code:
+ return response
time.sleep(1)
- assert response is not None
- return response
+ if response is not None:
+ return response
+ assert last_transport_error is not None
+ raise last_transport_error
+
+
+def test_wait_for_status_retries_transport_errors():
+ response = httpx.Response(200)
+ client = Mock()
+ client.get.side_effect = [httpx.ConnectError("not ready"), response]
+
+ assert wait_for_status(client, "https://sandbox.test", 200) is response
+ assert client.get.call_count == 2
@pytest.mark.skip_debug()
@@ -280,10 +297,6 @@ def test_mask_request_host(sandbox_factory):
timeout=60,
)
- import time
-
- import httpx
-
port = 8080
output_file = "/tmp/headers.txt"
@@ -299,7 +312,7 @@ class H(http.server.BaseHTTPRequestHandler):
self.send_response(200)
self.end_headers()
def log_message(self, *a): pass
-http.server.HTTPServer(('', {port}), H).handle_request()
+http.server.HTTPServer(('', {port}), H).serve_forever()
" """,
background=True,
)
@@ -312,12 +325,8 @@ http.server.HTTPServer(('', {port}), H).handle_request()
# Make a request from OUTSIDE the sandbox through the proxy
# The Host header should be modified according to mask_request_host
with httpx.Client() as client:
- try:
- client.get(sandbox_url, timeout=5.0)
- except Exception:
- pass
-
- time.sleep(1)
+ response = wait_for_status(client, sandbox_url, 200)
+ assert response.status_code == 200
# Read the captured headers from inside the sandbox
result = sandbox.commands.run(f"cat {output_file}")
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot_api.py b/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot_api.py
index 2fa6d2982..e8d00d3dd 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot_api.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot_api.py
@@ -1,5 +1,7 @@
import pytest
-from e2b import Sandbox
+from e2b import Sandbox, SandboxException
+
+pytestmark = pytest.mark.timeout(120)
@pytest.mark.skip_debug()
@@ -142,6 +144,7 @@ def test_delete_snapshot(sandbox: Sandbox):
@pytest.mark.skip_debug()
def test_snapshot_preserves_filesystem(sandbox: Sandbox):
app_dir = "/home/user/app"
config_path = f"{app_dir}/config.json"
@@ -156,7 +159,14 @@ def test_snapshot_preserves_filesystem(sandbox: Sandbox):
snapshot = sandbox.create_snapshot()
try:
- new_sandbox = Sandbox.create(snapshot.snapshot_id)
+ try:
+ new_sandbox = Sandbox.create(snapshot.snapshot_id)
+ except SandboxException as error:
+ # Placement can transiently time out while the snapshot is restored.
+ # Retry only the backend response that explicitly asks the caller to do so.
+ if "Failed to place sandbox: placement timed out" not in str(error):
+ raise
+ new_sandbox = Sandbox.create(snapshot.snapshot_id)
try:
dir_exists = new_sandbox.files.exists(app_dir)
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot_filesystem_only.py b/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot_filesystem_only.py
index 0493b9714..85851038c 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot_filesystem_only.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_snapshot_filesystem_only.py
@@ -1,5 +1,7 @@
import pytest
-from e2b import Sandbox
+from e2b import Sandbox, SandboxException
+
+pytestmark = pytest.mark.timeout(270)
@pytest.mark.skip_debug()
@@ -9,11 +11,18 @@ def test_pause_filesystem_only(sandbox: Sandbox):
boot_before = sandbox.files.read("/proc/sys/kernel/random/boot_id").strip()
# Filesystem-only pause: only the rootfs is persisted, no memory snapshot.
- assert sandbox.pause(keep_memory=False)
+ assert sandbox.pause(keep_memory=False, request_timeout=120)
assert not sandbox.is_running()
# Resuming a filesystem-only snapshot cold-boots (reboots) from the rootfs.
- resumed = sandbox.connect()
+ try:
+ resumed = sandbox.connect(request_timeout=120)
+ except SandboxException as error:
+ # Placement can transiently time out while the cold boot is scheduled.
+ # Retry only the backend response that explicitly asks the caller to do so.
+ if "Failed to place sandbox: placement timed out" not in str(error):
+ raise
+ resumed = sandbox.connect(request_timeout=120)
assert resumed.is_running()
assert resumed.sandbox_id == sandbox.sandbox_id
diff --git a/packages/python-sdk/tests/test_connection_config.py b/packages/python-sdk/tests/test_connection_config.py
index a9df7733b..94443302e 100644
--- a/packages/python-sdk/tests/test_connection_config.py
+++ b/packages/python-sdk/tests/test_connection_config.py
@@ -116,7 +116,7 @@ def test_set_integration_appends_to_user_agent():
config = ConnectionConfig()
assert config.headers["User-Agent"].startswith("e2b-python-sdk/")
- assert config.headers["User-Agent"].endswith(" testing/version")
+ assert "testing/version" in config.headers["User-Agent"].split()
finally:
ConnectionConfig.set_integration(None)
@@ -124,6 +124,22 @@ def test_set_integration_appends_to_user_agent():
assert "testing" not in config.headers["User-Agent"]
+def test_user_agent_includes_configured_traffic_source(monkeypatch):
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
+
+ config = ConnectionConfig()
+
+ assert config.headers["User-Agent"].endswith(" source/ci")
+
+
+def test_user_agent_ignores_unsafe_traffic_source(monkeypatch):
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci bad\nheader")
+
+ config = ConnectionConfig()
+
+ assert "source/" not in config.headers["User-Agent"]
+
+
def test_custom_user_agent_is_preserved_without_integration():
config = ConnectionConfig(api_headers={"User-Agent": "custom/1.0"})
@@ -144,10 +160,11 @@ def test_integration_survives_api_param_rebuilds(monkeypatch):
config = ConnectionConfig()
rebuilt_config = ConnectionConfig(**config.get_api_params())
- assert rebuilt_config.headers["User-Agent"].endswith(" testing/version")
- assert rebuilt_config.get_api_params(api_headers={"X-Test": "1"})["headers"][
- "User-Agent"
- ].endswith(" testing/version")
+ assert "testing/version" in rebuilt_config.headers["User-Agent"].split()
+ rebuilt_user_agent = rebuilt_config.get_api_params(api_headers={"X-Test": "1"})[
+ "headers"
+ ]["User-Agent"]
+ assert "testing/version" in rebuilt_user_agent.split()
def test_cleared_integration_does_not_leak_into_api_param_rebuilds():
diff --git a/packages/python-sdk/tests/test_logging_option.py b/packages/python-sdk/tests/test_logging_option.py
index c10592075..79995edbd 100644
--- a/packages/python-sdk/tests/test_logging_option.py
+++ b/packages/python-sdk/tests/test_logging_option.py
@@ -1,11 +1,13 @@
import inspect
import logging
+import asyncio
from types import SimpleNamespace
from e2b import AsyncSandbox, ConnectionConfig, Sandbox
from e2b.envd.interceptors import LoggingInterceptor, build_interceptors
from e2b.api import (
ApiClient,
+ handle_api_exception,
make_async_logging_event_hooks,
make_logging_event_hooks,
)
@@ -72,9 +74,10 @@ def test_api_client_uses_config_logger():
client.get_httpx_client().close()
-def test_api_client_without_logger_emits_no_hooks():
+def test_api_client_without_logger_outside_ci_emits_no_hooks(monkeypatch):
# With no logger supplied, nothing should be logged (matching the JS SDK,
# which only attaches its logging middleware when a logger is given).
+ monkeypatch.delenv("E2B_USER_AGENT_SOURCE", raising=False)
config = ConnectionConfig(api_key="e2b_" + "0" * 40)
client = ApiClient(config)
try:
@@ -164,7 +167,8 @@ def test_logging_event_hooks_without_logger_are_empty():
assert make_async_logging_event_hooks(None) == {}
-def test_sync_logging_event_hooks_emit_records(caplog):
+def test_sync_logging_event_hooks_emit_records(caplog, monkeypatch):
+ monkeypatch.delenv("E2B_USER_AGENT_SOURCE", raising=False)
log = logging.getLogger("test.hooks.sync")
hooks = make_logging_event_hooks(log)
@@ -173,13 +177,14 @@ def test_sync_logging_event_hooks_emit_records(caplog):
url = "https://example.com/foo"
class _Resp:
- def __init__(self, status_code):
+ def __init__(self, status_code, headers=None):
self.status_code = status_code
+ self.headers = headers or {}
with caplog.at_level(logging.DEBUG, logger="test.hooks.sync"):
hooks["request"][0](_Req())
hooks["response"][0](_Resp(200))
- hooks["response"][0](_Resp(500))
+ hooks["response"][0](_Resp(500, {"X-E2B-Trace-ID": "trace-123"}))
levels = [(r.levelno, r.getMessage()) for r in caplog.records]
assert (logging.INFO, "Request GET https://example.com/foo") in levels
@@ -192,3 +197,67 @@ def test_make_async_logging_event_hooks_shape():
assert set(hooks) == {"request", "response"}
assert len(hooks["request"]) == 1
assert len(hooks["response"]) == 1
+
+
+def test_async_logging_event_hooks_log_trace_id_for_ci_failure(caplog, monkeypatch):
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
+ log = logging.getLogger("test.hooks.async")
+ hooks = make_async_logging_event_hooks(log, include_diagnostics=True)
+ response = SimpleNamespace(
+ status_code=500,
+ headers={"X-E2B-Trace-ID": "trace-123"},
+ )
+
+ with caplog.at_level(logging.ERROR, logger="test.hooks.async"):
+ asyncio.run(hooks["response"][0](response))
+
+ assert (logging.ERROR, "Response 500 trace_id=trace-123") in [
+ (record.levelno, record.getMessage()) for record in caplog.records
+ ]
+
+
+def test_api_client_diagnostics_follow_captured_request_source(caplog, monkeypatch):
+ api_key = "e2b_" + "0" * 40
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
+ ci_client = ApiClient(ConnectionConfig(api_key=api_key))
+ monkeypatch.delenv("E2B_USER_AGENT_SOURCE")
+ normal_client = ApiClient(ConnectionConfig(api_key=api_key))
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
+
+ response = SimpleNamespace(
+ status_code=500,
+ headers={"X-E2B-Trace-ID": "trace-123"},
+ )
+ with caplog.at_level(logging.ERROR, logger="e2b.ci"):
+ ci_client._logging_event_hooks()["response"][0](response)
+
+ assert (logging.ERROR, "Response 500 trace_id=trace-123") in [
+ (record.levelno, record.getMessage()) for record in caplog.records
+ ]
+ assert normal_client._logging_event_hooks() == {}
+
+
+def test_ci_api_exception_keeps_public_message(monkeypatch):
+ monkeypatch.setenv("E2B_USER_AGENT_SOURCE", "ci")
+ response = SimpleNamespace(
+ status_code=500,
+ content=b'{"message":"Internal error"}',
+ headers={"X-E2B-Trace-ID": "trace-123"},
+ )
+
+ error = handle_api_exception(response)
+
+ assert str(error) == "500: Internal error"
+
+
+def test_api_exception_does_not_include_trace_id_outside_ci(monkeypatch):
+ monkeypatch.delenv("E2B_USER_AGENT_SOURCE", raising=False)
+ response = SimpleNamespace(
+ status_code=500,
+ content=b'{"message":"Internal error"}',
+ headers={"X-E2B-Trace-ID": "trace-123"},
+ )
+
+ error = handle_api_exception(response)
+
+ assert str(error) == "500: Internal error"
diff --git a/vitest.cloudflare.config.mts b/vitest.cloudflare.config.mts
index dd5f93060..7d74e4164 100644
--- a/vitest.cloudflare.config.mts
+++ b/vitest.cloudflare.config.mts
@@ -22,6 +22,7 @@ export interface CloudflareVitestConfigOptions {
/** Globs excluded on top of `tests/runtimes/**`. */
exclude?: string[]
testTimeout?: number
+ maxWorkers?: number
/** Additional rejection shapes to drop, on top of the shared ones. */
isExpectedRejection?: (error: UnhandledError, message: string) => boolean
}
@@ -34,6 +35,7 @@ export interface CloudflareVitestConfigOptions {
export function createCloudflareVitestConfig({
exclude = [],
testTimeout = 30_000,
+ maxWorkers,
isExpectedRejection,
}: CloudflareVitestConfigOptions = {}): ViteUserConfig {
const env = config()
@@ -51,6 +53,10 @@ export function createCloudflareVitestConfig({
E2B_API_KEY:
process.env.E2B_API_KEY ?? env.parsed?.E2B_API_KEY ?? '',
E2B_DOMAIN: process.env.E2B_DOMAIN ?? env.parsed?.E2B_DOMAIN ?? '',
+ E2B_USER_AGENT_SOURCE:
+ process.env.E2B_USER_AGENT_SOURCE ??
+ env.parsed?.E2B_USER_AGENT_SOURCE ??
+ '',
},
},
}),
@@ -61,6 +67,7 @@ export function createCloudflareVitestConfig({
exclude: ['tests/runtimes/**', ...exclude],
globals: false,
testTimeout,
+ maxWorkers,
bail: 0,
// workerd reports a rejection as unhandled unless a handler is attached
// within the same microtask drain, and vitest never processes the
diff --git a/vitest.sdk.config.mts b/vitest.sdk.config.mts
index c4875cf75..6e2d4e268 100644
--- a/vitest.sdk.config.mts
+++ b/vitest.sdk.config.mts
@@ -1,14 +1,22 @@
import type { ViteUserConfig } from 'vitest/config'
export function createSdkVitestConfig(
- env: Record<string, string>
+ env: Record<string, string>,
+ options: { testTimeout?: number } = {}
): ViteUserConfig {
+ const maxWorkers = env.E2B_TEST_MAX_WORKERS
+ ? Number(env.E2B_TEST_MAX_WORKERS)
+ : undefined
+
return {
test: {
include: ['tests/**/*.test.ts'],
exclude: ['tests/runtimes/**'],
globals: false,
- testTimeout: 30_000,
+ // Live sandbox creation and language startup share this budget with the
+ // assertion body; slower kernels regularly need more than 30 seconds.
+ testTimeout: options.testTimeout ?? 60_000,
+ maxWorkers,
environment: 'node',
bail: 0,
server: {},