Skip to content

armgit / E2B

Public Imported from GitHub
0

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

fix(sdk): omit autoPause when no timeout lifecycle is configured (#1693)

cursor[bot]15bd48b73daf
diff --git a/.changeset/omit-auto-pause-when-lifecycle-unset.md b/.changeset/omit-auto-pause-when-lifecycle-unset.md
new file mode 100644
index 000000000..618e398ac
--- /dev/null
+++ b/.changeset/omit-auto-pause-when-lifecycle-unset.md
@@ -0,0 +1,38 @@
+---
+'e2b': patch
+'@e2b/python-sdk': patch
+---
+
+Omit `autoPause` from the create-sandbox request when no timeout lifecycle is configured, and omit `autoPauseMemory` unless `keepMemory` / `keep_memory` was chosen. Sending the SDK's local defaults for those fields was indistinguishable from an explicit choice, so the API could not tell "no preference" from a client choice and own its defaults. Explicit values are still always sent:
+
+```ts
+import { Sandbox } from 'e2b'
+
+// No timeout lifecycle: autoPause is omitted, the API applies its default.
+await Sandbox.create()
+
+// Explicit action: autoPause: false / autoPause: true, as before.
+await Sandbox.create({ lifecycle: { onTimeout: 'kill' } })
+await Sandbox.create({ lifecycle: { onTimeout: 'pause' } })
+
+// Snapshot kind is only sent when keepMemory is set.
+await Sandbox.create({
+ lifecycle: { onTimeout: { action: 'pause', keepMemory: false } },
+})
+```
+
+```python
+from e2b import Sandbox
+
+# No timeout lifecycle: auto_pause is omitted, the API applies its default.
+Sandbox.create()
+
+# Explicit action: autoPause: false / autoPause: true, as before.
+Sandbox.create(lifecycle={"on_timeout": "kill"})
+Sandbox.create(lifecycle={"on_timeout": "pause"})
+
+# Snapshot kind is only sent when keep_memory is set.
+Sandbox.create(
+ lifecycle={"on_timeout": {"action": "pause", "keep_memory": False}}
+)
+```
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 270faddea..5d8842633 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -439,7 +439,8 @@ export type SandboxOnTimeout =
* be woken transparently by traffic and must be resumed explicitly via
* `connect()`.
*
- * @default true
+ * Left unset, the flag is omitted from the create request and the API's own
+ * default (currently enabled) applies.
*/
keepMemory?: boolean
}
@@ -452,7 +453,8 @@ export type SandboxLifecycle = {
/**
* Action to take when sandbox timeout is reached. Accepts either `'pause'` /
* `'kill'`, or `{ action, keepMemory }` to also control the pause snapshot kind.
- * @default "kill"
+ * Omitted from the create request when unset, leaving the API's default
+ * (currently `kill`) in effect.
*/
onTimeout: SandboxOnTimeout
@@ -1569,8 +1571,13 @@ export class SandboxApi {
const client = new ApiClient(config)
// onTimeout accepts a bare action (`'pause'` / `'kill'`) or the object form
// `{ action, keepMemory }`. The discriminated union type forbids `keepMemory`
- // on `action: 'kill'`; re-check at runtime for untyped (JS) callers.
- const onTimeout = opts?.lifecycle?.onTimeout ?? 'kill'
+ // on `action: 'kill'`; re-check at runtime for untyped callers.
+ const requestedOnTimeout = opts?.lifecycle?.onTimeout
+ // A missing (or explicitly nullish, for untyped callers) onTimeout is not a
+ // choice of `kill` — it leaves the timeout action to the API. Locally it
+ // still resolves to kill semantics for the validation below.
+ const onTimeoutConfigured = requestedOnTimeout != null
+ const onTimeout = requestedOnTimeout ?? 'kill'
const action = typeof onTimeout === 'string' ? onTimeout : onTimeout.action
const hasKeepMemory =
typeof onTimeout !== 'string' && 'keepMemory' in onTimeout
@@ -1612,8 +1619,9 @@ export class SandboxApi {
allow_internet_access: opts?.allowInternetAccess ?? true,
network: buildNetworkBody(opts?.network, iam),
iam,
- autoPause: action === 'pause',
- autoPauseMemory: action === 'pause' ? keepMemory : undefined,
+ autoPause: onTimeoutConfigured ? action === 'pause' : undefined,
+ autoPauseMemory:
+ action === 'pause' && hasKeepMemory ? keepMemory : undefined,
autoResume: { enabled: autoResume },
}
diff --git a/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts b/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts
new file mode 100644
index 000000000..03fad1990
--- /dev/null
+++ b/packages/js-sdk/tests/sandbox/lifecycleRequest.test.ts
@@ -0,0 +1,120 @@
+import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'
+import { http, HttpResponse } from 'msw'
+import { setupServer } from 'msw/node'
+
+import { InvalidArgumentError, Sandbox } from '../../src'
+import { TEST_API_KEY, apiUrl } from '../setup'
+
+let lastCreateBody: Record<string, unknown> | undefined
+
+const server = setupServer(
+ http.post(apiUrl('/sandboxes'), async ({ request }) => {
+ lastCreateBody = (await request.json()) as Record<string, unknown>
+ return HttpResponse.json({
+ sandboxID: 'test-sandbox-id',
+ templateID: 'base',
+ envdVersion: '0.2.4',
+ })
+ })
+)
+
+beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
+
+afterAll(() => server.close())
+
+afterEach(() => {
+ lastCreateBody = undefined
+ server.resetHandlers()
+})
+
+test('Sandbox.create omits autoPause when no lifecycle is configured', async () => {
+ // An omitted lifecycle expresses no preference; autoPause: false would be
+ // indistinguishable from an explicit 'kill' and would override the API default.
+ await Sandbox.create('base', { apiKey: TEST_API_KEY })
+
+ expect(lastCreateBody).toBeDefined()
+ expect(lastCreateBody).not.toHaveProperty('autoPause')
+ expect(lastCreateBody).not.toHaveProperty('autoPauseMemory')
+})
+
+test('Sandbox.create sends autoPause: false for an explicit kill', async () => {
+ await Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ lifecycle: { onTimeout: 'kill' },
+ })
+
+ expect(lastCreateBody?.autoPause).toBe(false)
+ expect(lastCreateBody).not.toHaveProperty('autoPauseMemory')
+})
+
+test('Sandbox.create sends autoPause: true for an explicit pause', async () => {
+ await Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ lifecycle: { onTimeout: 'pause' },
+ })
+
+ expect(lastCreateBody?.autoPause).toBe(true)
+ // Bare 'pause' expresses no preference about the snapshot kind.
+ expect(lastCreateBody).not.toHaveProperty('autoPauseMemory')
+})
+
+test('Sandbox.create omits autoPauseMemory when pause omits keepMemory', async () => {
+ await Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ lifecycle: { onTimeout: { action: 'pause' } },
+ })
+
+ expect(lastCreateBody?.autoPause).toBe(true)
+ expect(lastCreateBody).not.toHaveProperty('autoPauseMemory')
+})
+
+test('Sandbox.create sends the pause snapshot kind alongside autoPause', async () => {
+ await Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ lifecycle: { onTimeout: { action: 'pause', keepMemory: false } },
+ })
+
+ expect(lastCreateBody?.autoPause).toBe(true)
+ expect(lastCreateBody?.autoPauseMemory).toBe(false)
+
+ await Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ lifecycle: { onTimeout: { action: 'pause', keepMemory: true } },
+ })
+
+ expect(lastCreateBody?.autoPause).toBe(true)
+ expect(lastCreateBody?.autoPauseMemory).toBe(true)
+})
+
+test('Sandbox.create omits autoPause for a lifecycle without onTimeout', async () => {
+ // Untyped callers can build the lifecycle conditionally and leave
+ // onTimeout out, or pass it as null; neither selects an action.
+ await Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ lifecycle: { autoResume: false } as never,
+ })
+
+ expect(lastCreateBody).toBeDefined()
+ expect(lastCreateBody).not.toHaveProperty('autoPause')
+
+ await Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ lifecycle: { onTimeout: null } as never,
+ })
+
+ expect(lastCreateBody).toBeDefined()
+ expect(lastCreateBody).not.toHaveProperty('autoPause')
+})
+
+test('Sandbox.create rejects autoResume without a timeout action', async () => {
+ // An unconfigured onTimeout still resolves to kill semantics locally, so
+ // autoResume has no pause to attach to.
+ await expect(
+ Sandbox.create('base', {
+ apiKey: TEST_API_KEY,
+ lifecycle: { autoResume: true } as never,
+ })
+ ).rejects.toThrowError(InvalidArgumentError)
+
+ expect(lastCreateBody).toBeUndefined()
+})
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index b6ebf2ea2..dc5b46e0e 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -22,6 +22,9 @@ from e2b.api.client.models import (
SandboxDetail,
SandboxState,
)
+from e2b.api.client.models import (
+ SandboxAutoResumeConfig as ClientSandboxAutoResumeConfig,
+)
from e2b.api.client.models import (
SandboxLifecycle as ClientSandboxLifecycle,
)
@@ -58,7 +61,7 @@ from e2b.api.client.models import (
from e2b.api.client.models import (
SandboxNetworkUpdateConfigRules,
)
-from e2b.api.client.types import Unset
+from e2b.api.client.types import UNSET, Unset
from e2b.connection_config import ApiParams
from e2b.exceptions import InvalidArgumentException
from e2b.sandbox.mcp import McpServer as BaseMcpServer
@@ -488,10 +491,12 @@ class SandboxOnTimeoutPause(TypedDict):
keep_memory: NotRequired[bool]
"""
- Whether the timeout auto-pause keeps a full memory snapshot. Defaults to `True`.
- When `False`, the auto-pause drops the in-memory state and persists only the
- filesystem (a filesystem-only snapshot); resuming such a sandbox cold-boots
- (reboots) it from disk, losing running processes and open connections.
+ Whether the timeout auto-pause keeps a full memory snapshot. Left unset, it is
+ omitted from the create request and the API's own default (currently enabled)
+ applies. When `False`, the auto-pause drops the in-memory state and persists
+ only the filesystem (a filesystem-only snapshot); resuming such a sandbox
+ cold-boots (reboots) it from disk, losing running processes and open
+ connections.
Cannot be combined with `auto_resume`: auto-resume wakes a paused sandbox on
inbound traffic by restoring its memory snapshot in place, so the request that
@@ -524,8 +529,9 @@ error.
class SandboxLifecycle(TypedDict):
"""
- Sandbox lifecycle configuration; defines post-timeout behavior and auto-resume settings.
- Defaults to `on_timeout="kill"` and `auto_resume=False`.
+ Sandbox lifecycle configuration; defines post-timeout behavior and auto-resume
+ settings. An omitted `on_timeout` leaves the choice to the API (currently
+ `"kill"`); `auto_resume` defaults to `False`.
"""
on_timeout: SandboxOnTimeout
@@ -533,8 +539,9 @@ class SandboxLifecycle(TypedDict):
What should happen to the sandbox when timeout is reached. `"kill"` terminates
the sandbox; `"pause"` pauses it for later resume. Accepts either the bare
action or an object `{"action": "pause", "keep_memory": ...}` /
- `{"action": "kill"}` to also control the pause snapshot kind. Defaults to
- `"kill"`.
+ `{"action": "kill"}` to also control the pause snapshot kind. Omitted from the
+ create request when unset, leaving the API's default (currently `"kill"`) in
+ effect.
"""
auto_resume: NotRequired[bool]
@@ -782,6 +789,81 @@ def build_iam_config(
return body
+@dataclass(frozen=True)
+class SandboxLifecycleBody:
+ """Lifecycle fields of a create-sandbox request, as ``NewSandbox`` takes them."""
+
+ auto_pause: Union[Unset, bool]
+ auto_pause_memory: Union[Unset, bool]
+ auto_resume: ClientSandboxAutoResumeConfig
+
+
+def build_lifecycle_config(
+ lifecycle: Optional[SandboxLifecycle],
+) -> SandboxLifecycleBody:
+ """Resolve a :class:`SandboxLifecycle` into the create-request lifecycle fields.
+
+ ``auto_pause`` is left unset when no ``on_timeout`` was configured: sending
+ ``False`` would be indistinguishable from an explicit ``"kill"`` and would
+ override the default the API owns. ``auto_pause_memory`` is likewise left
+ unset unless the caller chose ``keep_memory``.
+ """
+ # on_timeout accepts a bare action or {"action", "keep_memory"}; normalize.
+ # Only the object form carries keep_memory; anything else (a bare action
+ # string, or an unexpected value from an untyped caller) passes through as
+ # the action, so a non-"pause" value resolves to kill instead of crashing.
+ on_timeout_raw = lifecycle.get("on_timeout") if lifecycle else None
+ # A missing on_timeout — or an explicit None from an untyped caller — is not
+ # a choice of kill. It only resolves to kill semantics locally, for the
+ # validation below and for keep_memory.
+ on_timeout_configured = on_timeout_raw is not None
+ if isinstance(on_timeout_raw, dict):
+ on_timeout = on_timeout_raw.get("action", "kill")
+ keep_memory_provided = "keep_memory" in on_timeout_raw
+ keep_memory = on_timeout_raw.get("keep_memory")
+ else:
+ # Only fall back when unconfigured, not on other falsy-but-present
+ # values an untyped caller might pass.
+ on_timeout = on_timeout_raw if on_timeout_configured else "kill"
+ keep_memory = None
+ keep_memory_provided = False
+
+ # keep_memory only governs a pause action. The discriminated union type
+ # forbids it on action="kill"; re-check at runtime for callers that
+ # bypass the type.
+ if keep_memory_provided and on_timeout != "pause":
+ raise InvalidArgumentException(
+ "keep_memory is only allowed when on_timeout action is 'pause'."
+ )
+
+ # A missing or explicit None keep_memory defaults to True (full memory) for
+ # local validation below. The wire field is omitted unless keep_memory was
+ # actually provided.
+ if keep_memory is None:
+ keep_memory = True
+ auto_resume = lifecycle.get("auto_resume", False) if lifecycle else False
+
+ if auto_resume and on_timeout != "pause":
+ raise InvalidArgumentException(
+ "auto_resume can only be True when on_timeout action is 'pause'."
+ )
+
+ if not keep_memory and auto_resume:
+ raise InvalidArgumentException(
+ "auto_resume: True is not a valid value when keep_memory: False - "
+ "a filesystem-only snapshot cannot be auto-resumed by traffic and "
+ "must be resumed explicitly using Sandbox.connect()."
+ )
+
+ return SandboxLifecycleBody(
+ auto_pause=(on_timeout == "pause") if on_timeout_configured else UNSET,
+ auto_pause_memory=(
+ keep_memory if on_timeout == "pause" and keep_memory_provided else UNSET
+ ),
+ auto_resume=ClientSandboxAutoResumeConfig(enabled=auto_resume),
+ )
+
+
def build_network_update_body(
network: SandboxNetworkUpdate,
) -> SandboxNetworkUpdateConfig:
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 34beeca9d..67121bf67 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -196,7 +196,7 @@ class AsyncSandbox(SandboxApi):
:param mcp: MCP server to enable in the sandbox
:param network: Sandbox network configuration. ``allow_out``/``deny_out`` may also be a callable receiving a :class:`SandboxNetworkSelectorContext` (``ctx.all_traffic``, ``ctx.rules``) and returning a list of strings. Per-host transform rules are nested under ``network.rules``; a rule's ``transform`` may be a callable receiving a :class:`SandboxNetworkTransformContext` of placeholder strings (``ctx.iam.tokens[name]``).
:param iam: Sandbox workload identity configuration. A non-empty ``tokens`` map enables workload identity for the sandbox; token definitions can be created with :meth:`Secret.iam_token`. Example: ``{"tokens": {"aws": Secret.iam_token(audience="sts.amazonaws.com", token_type="JWT-SVID")}}``. Registered tokens are exposed to ``network.rules`` ``transform`` callables as ``ctx.iam.tokens[name]`` placeholders, which the egress proxy resolves per request
- :param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``, or an object ``{"action": "pause"|"kill", "keep_memory": bool}`` where ``keep_memory`` (default ``True``) set to ``False`` makes a timeout auto-pause filesystem-only (cold-boots on resume; cannot be combined with ``auto_resume``); ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout`` action is ``"pause"``). Example: ``{"on_timeout": {"action": "pause", "keep_memory": False}}``
+ :param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` or ``"pause"`` (omitted from the request when unset, leaving the API's default, currently ``"kill"``, in effect), or an object ``{"action": "pause"|"kill", "keep_memory": bool}`` where ``keep_memory`` set to ``False`` makes a timeout auto-pause filesystem-only (cold-boots on resume; cannot be combined with ``auto_resume``); an omitted ``keep_memory`` leaves the snapshot kind to the API; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout`` action is ``"pause"``). Example: ``{"on_timeout": {"action": "pause", "keep_memory": False}}``
:param volume_mounts: Dictionary mapping mount paths to AsyncVolume instances or volume names
:param logger: Logger used for request and response logging for this sandbox. Accepts any standard library `logging.Logger`. When omitted, no request/response logging is emitted.
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index ce65ddc33..934f71e39 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -30,7 +30,6 @@ from e2b.api.client.models import (
NewSandbox,
SandboxSnapshotRequest,
SandboxTimeoutRequest,
- SandboxAutoResumeConfig,
SandboxForkRequest,
SandboxNetworkConfig,
SandboxPauseRequest,
@@ -59,6 +58,7 @@ from e2b.sandbox.sandbox_api import (
SandboxQuery,
SnapshotInfo,
build_iam_config,
+ build_lifecycle_config,
build_network_config,
)
from e2b.sandbox_async.paginator import AsyncSandboxPaginator
@@ -218,45 +218,7 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
config = ConnectionConfig(logger=logger, **opts)
- # on_timeout accepts a bare action or {"action", "keep_memory"}; normalize.
- # Only the object form carries keep_memory; anything else (a bare action
- # string, or an unexpected value from an untyped caller) passes through as
- # the action, so a non-"pause" value resolves to kill instead of crashing.
- on_timeout_raw = lifecycle.get("on_timeout", "kill") if lifecycle else "kill"
- if isinstance(on_timeout_raw, dict):
- on_timeout = on_timeout_raw.get("action", "kill")
- keep_memory_provided = "keep_memory" in on_timeout_raw
- keep_memory = on_timeout_raw.get("keep_memory")
- else:
- on_timeout = on_timeout_raw
- keep_memory = None
- keep_memory_provided = False
-
- # keep_memory only governs a pause action. The discriminated union type
- # forbids it on action="kill"; re-check at runtime for callers that
- # bypass the type.
- if keep_memory_provided and on_timeout != "pause":
- raise InvalidArgumentException(
- "keep_memory is only allowed when on_timeout action is 'pause'."
- )
-
- # A missing or explicit None keep_memory defaults to True (full memory),
- # mirroring the JS SDK; sending null would wrongly read as filesystem-only.
- if keep_memory is None:
- keep_memory = True
- auto_resume = lifecycle.get("auto_resume", False) if lifecycle else False
-
- if auto_resume and on_timeout != "pause":
- raise InvalidArgumentException(
- "auto_resume can only be True when on_timeout action is 'pause'."
- )
-
- if not keep_memory and auto_resume:
- raise InvalidArgumentException(
- "auto_resume: True is not a valid value when keep_memory: False - "
- "a filesystem-only snapshot cannot be auto-resumed by traffic and "
- "must be resumed explicitly using Sandbox.connect()."
- )
+ lifecycle_body = build_lifecycle_config(lifecycle)
# Built before the network config: ``transform`` callables are resolved
# against the workload tokens this request registers.
@@ -264,9 +226,9 @@ class SandboxApi(SandboxBase):
network_body = build_network_config(network, iam_body)
body = NewSandbox(
template_id=template,
- auto_pause=on_timeout == "pause",
- auto_pause_memory=keep_memory if on_timeout == "pause" else UNSET,
- auto_resume=SandboxAutoResumeConfig(enabled=auto_resume),
+ auto_pause=lifecycle_body.auto_pause,
+ auto_pause_memory=lifecycle_body.auto_pause_memory,
+ auto_resume=lifecycle_body.auto_resume,
metadata=metadata or {},
timeout=timeout,
env_vars=env_vars or {},
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index 851a8a426..03a11dc34 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -192,7 +192,7 @@ class Sandbox(SandboxApi):
:param mcp: MCP server to enable in the sandbox
:param network: Sandbox network configuration. ``allow_out``/``deny_out`` may also be a callable receiving a :class:`SandboxNetworkSelectorContext` (``ctx.all_traffic``, ``ctx.rules``) and returning a list of strings. Per-host transform rules are nested under ``network.rules``; a rule's ``transform`` may be a callable receiving a :class:`SandboxNetworkTransformContext` of placeholder strings (``ctx.iam.tokens[name]``).
:param iam: Sandbox workload identity configuration. A non-empty ``tokens`` map enables workload identity for the sandbox; token definitions can be created with :meth:`Secret.iam_token`. Example: ``{"tokens": {"aws": Secret.iam_token(audience="sts.amazonaws.com", token_type="JWT-SVID")}}``. Registered tokens are exposed to ``network.rules`` ``transform`` callables as ``ctx.iam.tokens[name]`` placeholders, which the egress proxy resolves per request
- :param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``, or an object ``{"action": "pause"|"kill", "keep_memory": bool}`` where ``keep_memory`` (default ``True``) set to ``False`` makes a timeout auto-pause filesystem-only (cold-boots on resume; cannot be combined with ``auto_resume``); ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout`` action is ``"pause"``). Example: ``{"on_timeout": {"action": "pause", "keep_memory": False}}``
+ :param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` or ``"pause"`` (omitted from the request when unset, leaving the API's default, currently ``"kill"``, in effect), or an object ``{"action": "pause"|"kill", "keep_memory": bool}`` where ``keep_memory`` set to ``False`` makes a timeout auto-pause filesystem-only (cold-boots on resume; cannot be combined with ``auto_resume``); an omitted ``keep_memory`` leaves the snapshot kind to the API; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout`` action is ``"pause"``). Example: ``{"on_timeout": {"action": "pause", "keep_memory": False}}``
:param volume_mounts: Dictionary mapping mount paths to Volume instances or volume names
:param logger: Logger used for request and response logging for this sandbox. Accepts any standard library `logging.Logger`. When omitted, no request/response logging is emitted.
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index e30555ea0..a19864c13 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -30,7 +30,6 @@ from e2b.api.client.models import (
NewSandbox,
SandboxSnapshotRequest,
SandboxTimeoutRequest,
- SandboxAutoResumeConfig,
SandboxForkRequest,
SandboxNetworkConfig,
SandboxPauseRequest,
@@ -58,6 +57,7 @@ from e2b.sandbox.sandbox_api import (
SandboxQuery,
SnapshotInfo,
build_iam_config,
+ build_lifecycle_config,
build_network_config,
)
from e2b.sandbox_sync.paginator import SandboxPaginator, get_api_client
@@ -217,45 +217,7 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
config = ConnectionConfig(logger=logger, **opts)
- # on_timeout accepts a bare action or {"action", "keep_memory"}; normalize.
- # Only the object form carries keep_memory; anything else (a bare action
- # string, or an unexpected value from an untyped caller) passes through as
- # the action, so a non-"pause" value resolves to kill instead of crashing.
- on_timeout_raw = lifecycle.get("on_timeout", "kill") if lifecycle else "kill"
- if isinstance(on_timeout_raw, dict):
- on_timeout = on_timeout_raw.get("action", "kill")
- keep_memory_provided = "keep_memory" in on_timeout_raw
- keep_memory = on_timeout_raw.get("keep_memory")
- else:
- on_timeout = on_timeout_raw
- keep_memory = None
- keep_memory_provided = False
-
- # keep_memory only governs a pause action. The discriminated union type
- # forbids it on action="kill"; re-check at runtime for callers that
- # bypass the type.
- if keep_memory_provided and on_timeout != "pause":
- raise InvalidArgumentException(
- "keep_memory is only allowed when on_timeout action is 'pause'."
- )
-
- # A missing or explicit None keep_memory defaults to True (full memory),
- # mirroring the JS SDK; sending null would wrongly read as filesystem-only.
- if keep_memory is None:
- keep_memory = True
- auto_resume = lifecycle.get("auto_resume", False) if lifecycle else False
-
- if auto_resume and on_timeout != "pause":
- raise InvalidArgumentException(
- "auto_resume can only be True when on_timeout action is 'pause'."
- )
-
- if not keep_memory and auto_resume:
- raise InvalidArgumentException(
- "auto_resume: True is not a valid value when keep_memory: False - "
- "a filesystem-only snapshot cannot be auto-resumed by traffic and "
- "must be resumed explicitly using Sandbox.connect()."
- )
+ lifecycle_body = build_lifecycle_config(lifecycle)
# Built before the network config: ``transform`` callables are resolved
# against the workload tokens this request registers.
@@ -263,9 +225,9 @@ class SandboxApi(SandboxBase):
network_body = build_network_config(network, iam_body)
body = NewSandbox(
template_id=template,
- auto_pause=on_timeout == "pause",
- auto_pause_memory=keep_memory if on_timeout == "pause" else UNSET,
- auto_resume=SandboxAutoResumeConfig(enabled=auto_resume),
+ auto_pause=lifecycle_body.auto_pause,
+ auto_pause_memory=lifecycle_body.auto_pause_memory,
+ auto_resume=lifecycle_body.auto_resume,
metadata=metadata or {},
timeout=timeout,
env_vars=env_vars or {},
diff --git a/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py b/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py
new file mode 100644
index 000000000..8446809da
--- /dev/null
+++ b/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py
@@ -0,0 +1,147 @@
+from types import SimpleNamespace
+from typing import Any, Dict, Optional, cast
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from e2b import AsyncSandbox, Sandbox
+from e2b.api.client.api.sandboxes import post_sandboxes
+from e2b.api.client.models import Sandbox as SandboxModel
+from e2b.exceptions import InvalidArgumentException
+
+
+def _created_sandbox():
+ return SimpleNamespace(
+ status_code=200,
+ parsed=SandboxModel(
+ client_id="client-id",
+ envd_version="0.2.4",
+ sandbox_id="sbx-test",
+ template_id="template-id",
+ ),
+ )
+
+
+def _sync_request_body(monkeypatch, api_key: str, lifecycle) -> Dict[str, Any]:
+ request = Mock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_sandboxes, "sync_detailed", request)
+
+ Sandbox.create(api_key=api_key, lifecycle=lifecycle)
+
+ return request.call_args.kwargs["body"].to_dict()
+
+
+async def _async_request_body(monkeypatch, api_key: str, lifecycle) -> Dict[str, Any]:
+ request = AsyncMock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_sandboxes, "asyncio_detailed", request)
+
+ await AsyncSandbox.create(api_key=api_key, lifecycle=lifecycle)
+
+ return request.call_args.kwargs["body"].to_dict()
+
+
+# `None` expects autoPause to be absent from the payload: an unconfigured
+# timeout action is not a choice of kill, so the API keeps ownership of the
+# default instead of receiving autoPause: False.
+AUTO_PAUSE_CASES = [
+ pytest.param(None, None, id="no-lifecycle"),
+ pytest.param({"on_timeout": "kill"}, False, id="explicit-kill"),
+ pytest.param({"on_timeout": "pause"}, True, id="explicit-pause"),
+ # Untyped callers can build the lifecycle conditionally and leave on_timeout
+ # out, or pass it as None; neither selects an action.
+ pytest.param(cast(Any, {"auto_resume": False}), None, id="no-on-timeout-key"),
+ pytest.param(cast(Any, {"on_timeout": None}), None, id="none-on-timeout"),
+]
+
+
[email protected]("lifecycle, auto_pause", AUTO_PAUSE_CASES)
+def test_create_sends_auto_pause_only_when_configured(
+ monkeypatch, test_api_key, lifecycle, auto_pause: Optional[bool]
+):
+ body = _sync_request_body(monkeypatch, test_api_key, lifecycle)
+
+ if auto_pause is None:
+ assert "autoPause" not in body
+ else:
+ assert body["autoPause"] is auto_pause
+ assert "autoPauseMemory" not in body
+
+
[email protected]("lifecycle, auto_pause", AUTO_PAUSE_CASES)
+async def test_async_create_sends_auto_pause_only_when_configured(
+ monkeypatch, test_api_key, lifecycle, auto_pause: Optional[bool]
+):
+ body = await _async_request_body(monkeypatch, test_api_key, lifecycle)
+
+ if auto_pause is None:
+ assert "autoPause" not in body
+ else:
+ assert body["autoPause"] is auto_pause
+ assert "autoPauseMemory" not in body
+
+
+def test_create_omits_auto_pause_memory_when_pause_omits_keep_memory(
+ monkeypatch, test_api_key
+):
+ body = _sync_request_body(
+ monkeypatch,
+ test_api_key,
+ {"on_timeout": {"action": "pause"}},
+ )
+
+ assert body["autoPause"] is True
+ assert "autoPauseMemory" not in body
+
+
+def test_create_sends_the_pause_snapshot_kind_alongside_auto_pause(
+ monkeypatch, test_api_key
+):
+ body = _sync_request_body(
+ monkeypatch,
+ test_api_key,
+ {"on_timeout": {"action": "pause", "keep_memory": False}},
+ )
+
+ assert body["autoPause"] is True
+ assert body["autoPauseMemory"] is False
+
+ body = _sync_request_body(
+ monkeypatch,
+ test_api_key,
+ {"on_timeout": {"action": "pause", "keep_memory": True}},
+ )
+
+ assert body["autoPause"] is True
+ assert body["autoPauseMemory"] is True
+
+
+ "lifecycle",
+ [
+ pytest.param(cast(Any, {"auto_resume": True}), id="no-on-timeout-key"),
+ pytest.param(
+ cast(Any, {"on_timeout": None, "auto_resume": True}), id="none-on-timeout"
+ ),
+ ],
+)
+def test_create_rejects_auto_resume_without_a_timeout_action(test_api_key, lifecycle):
+ # An unconfigured on_timeout still resolves to kill semantics locally, so
+ # auto_resume has no pause to attach to.
+ with pytest.raises(InvalidArgumentException):
+ Sandbox.create(api_key=test_api_key, lifecycle=lifecycle)
+
+
+ "lifecycle",
+ [
+ pytest.param(cast(Any, {"auto_resume": True}), id="no-on-timeout-key"),
+ pytest.param(
+ cast(Any, {"on_timeout": None, "auto_resume": True}), id="none-on-timeout"
+ ),
+ ],
+)
+async def test_async_create_rejects_auto_resume_without_a_timeout_action(
+ test_api_key, lifecycle
+):
+ with pytest.raises(InvalidArgumentException):
+ await AsyncSandbox.create(api_key=test_api_key, lifecycle=lifecycle)