Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat(sdk): filesystem-only auto-pause via lifecycle.onTimeout object form (#1471)

Babis Chalios7e7e9514dfc1
diff --git a/.changeset/auto-pause-filesystem-only.md b/.changeset/auto-pause-filesystem-only.md
new file mode 100644
index 000000000..5c26f80c7
--- /dev/null
+++ b/.changeset/auto-pause-filesystem-only.md
@@ -0,0 +1,35 @@
+---
+"e2b": minor
+"@e2b/python-sdk": minor
+---
+
+Add an object form to the sandbox `lifecycle.onTimeout` (`on_timeout` in Python)
+that controls the snapshot kind taken when a sandbox auto-pauses on timeout, via
+`keepMemory` (`keep_memory`).
+
+`onTimeout` now accepts either the existing bare action (`'pause'` / `'kill'`) or
+the object form. The object form is a discriminated union on `action`:
+`keepMemory` is only accepted alongside `action: 'pause'` — pairing it with
+`action: 'kill'` is a compile-time type error (and is rejected at runtime for
+untyped callers). When `keepMemory` is `false`, a timeout 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. Defaults to `true` (full memory snapshot). It
+cannot be combined with auto-resume: auto-resume wakes a paused sandbox on
+inbound traffic by restoring its memory snapshot in place, and a filesystem-only
+snapshot has no memory to restore (resuming cold-boots it), so it must be resumed
+explicitly. The bare string form is unchanged.
+
+```python
+# Python
+sbx = Sandbox.create(
+ lifecycle={"on_timeout": {"action": "pause", "keep_memory": False}}
+)
+```
+
+```ts
+// JS/TS
+const sbx = await Sandbox.create({
+ lifecycle: { onTimeout: { action: 'pause', keepMemory: false } },
+})
+```
diff --git a/packages/js-sdk/src/api/schema.gen.ts b/packages/js-sdk/src/api/schema.gen.ts
index 060944176..c6f357d03 100644
--- a/packages/js-sdk/src/api/schema.gen.ts
+++ b/packages/js-sdk/src/api/schema.gen.ts
@@ -2013,6 +2013,11 @@ export interface components {
* @default false
*/
autoPause?: boolean;
+ /**
+ * @description Controls the snapshot kind taken when the sandbox auto-pauses on timeout (only relevant when autoPause is true). When false, the auto-pause drops the in-memory state and persists only the filesystem (a filesystem-only snapshot); resuming it cold-boots (reboots) the sandbox from disk. Such a snapshot cannot be auto-resumed by traffic and must be resumed explicitly, so it cannot be combined with autoResume. Defaults to true (full memory snapshot).
+ * @default true
+ */
+ autoPauseMemory?: boolean;
autoResume?: components["schemas"]["SandboxAutoResumeConfig"];
envVars?: components["schemas"]["EnvVars"];
mcp?: components["schemas"]["Mcp"];
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 21ad4589d..237b90650 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -66,6 +66,7 @@ export type {
SandboxNetworkRules,
SandboxNetworkTransform,
SandboxNetworkUpdate,
+ SandboxOnTimeout,
SandboxLifecycle,
SandboxInfoLifecycle,
SnapshotInfo,
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 4fba4bdc0..6211e10ea 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -197,17 +197,60 @@ export type SandboxNetworkUpdate = {
allowInternetAccess?: boolean
}
+/**
+ * What happens when the sandbox timeout is reached. Either the bare action
+ * (`'pause'` / `'kill'`), or an object form that also controls the pause
+ * snapshot kind via `keepMemory`.
+ *
+ * The object form is a discriminated union on `action`: `keepMemory` is only
+ * accepted alongside `action: 'pause'`. Passing `keepMemory` with
+ * `action: 'kill'` is a compile-time type error.
+ */
+export type SandboxOnTimeout =
+ | 'pause'
+ | 'kill'
+ | {
+ /** Auto-pause the sandbox when the timeout is reached. */
+ action: 'pause'
+
+ /**
+ * Whether the timeout auto-pause keeps a full memory snapshot.
+ *
+ * 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 `autoResume`: auto-resume wakes a paused sandbox
+ * on inbound traffic by restoring its memory snapshot in place, so the
+ * request that woke it hits an already-running process. A filesystem-only
+ * snapshot has no memory to restore — resuming cold-boots it — so it can't
+ * be woken transparently by traffic and must be resumed explicitly via
+ * `connect()`.
+ *
+ * @default true
+ */
+ keepMemory?: boolean
+ }
+ | {
+ /** Kill the sandbox when the timeout is reached. */
+ action: 'kill'
+ }
+
export type SandboxLifecycle = {
/**
- * Action to take when sandbox timeout is reached.
+ * Action to take when sandbox timeout is reached. Accepts either `'pause'` /
+ * `'kill'`, or `{ action, keepMemory }` to also control the pause snapshot kind.
* @default "kill"
*/
- onTimeout: 'pause' | 'kill'
+ onTimeout: SandboxOnTimeout
/**
* Auto-resume enabled flag.
* @default false
- * Can be `true` only when `onTimeout` is `pause`.
+ * Can be `true` only when `onTimeout` is `pause`. Not supported when
+ * `keepMemory` is `false` (a filesystem-only snapshot must be resumed
+ * explicitly via `connect()`).
*/
autoResume?: boolean
}
@@ -1079,12 +1122,34 @@ export class SandboxApi {
) {
const config = new ConnectionConfig(opts)
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'
+ const action = typeof onTimeout === 'string' ? onTimeout : onTimeout.action
+ const hasKeepMemory =
+ typeof onTimeout !== 'string' && 'keepMemory' in onTimeout
+ const keepMemory =
+ typeof onTimeout !== 'string' && 'keepMemory' in onTimeout
+ ? (onTimeout.keepMemory ?? true)
+ : true
const autoResume = opts?.lifecycle?.autoResume ?? false
- if (autoResume && onTimeout !== 'pause') {
+ if (hasKeepMemory && action !== 'pause') {
+ throw new InvalidArgumentError(
+ "onTimeout.keepMemory is only allowed when action is 'pause'."
+ )
+ }
+
+ if (autoResume && action !== 'pause') {
+ throw new InvalidArgumentError(
+ "autoResume can only be true when onTimeout action is 'pause'."
+ )
+ }
+
+ if (!keepMemory && autoResume) {
throw new InvalidArgumentError(
- "autoResume can only be true when the resolved onTimeout is 'pause'."
+ 'autoResume: true is not a valid value when keepMemory: false - a filesystem-only snapshot cannot be auto-resumed by traffic and must be resumed explicitly using Sandbox.connect().'
)
}
@@ -1097,7 +1162,8 @@ export class SandboxApi {
secure: opts?.secure ?? true,
allow_internet_access: opts?.allowInternetAccess ?? true,
network: buildNetworkBody(opts?.network),
- autoPause: onTimeout === 'pause',
+ autoPause: action === 'pause',
+ autoPauseMemory: action === 'pause' ? keepMemory : undefined,
autoResume: { enabled: autoResume },
}
diff --git a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
index 3c930a7fa..2f8628c84 100644
--- a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
+++ b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
@@ -1,8 +1,43 @@
-import { assert, test } from 'vitest'
+import { assert, expect, test } from 'vitest'
-import { Sandbox } from '../../src'
+import { InvalidArgumentError, Sandbox } from '../../src'
import { isDebug, template, wait } from '../setup.js'
+test.skipIf(isDebug)(
+ 'filesystem-only auto-pause cannot be combined with auto-resume',
+ async () => {
+ // A filesystem-only auto-pause snapshot can only be resumed explicitly, so
+ // keepMemory:false with autoResume is rejected client-side.
+ await expect(
+ Sandbox.create(template, {
+ timeoutMs: 3_000,
+ lifecycle: {
+ onTimeout: { action: 'pause', keepMemory: false },
+ autoResume: true,
+ },
+ })
+ ).rejects.toThrowError(InvalidArgumentError)
+ }
+)
+
+test.skipIf(isDebug)(
+ 'keepMemory is not allowed when onTimeout action is kill',
+ async () => {
+ // The discriminated union forbids keepMemory on `action: 'kill'` at compile
+ // time (asserted by @ts-expect-error). The runtime guard below additionally
+ // rejects it for untyped (JS) callers that bypass the type.
+ await expect(
+ Sandbox.create(template, {
+ timeoutMs: 3_000,
+ lifecycle: {
+ // @ts-expect-error keepMemory is not allowed with action: 'kill'
+ onTimeout: { action: 'kill', keepMemory: false },
+ },
+ })
+ ).rejects.toThrowError(InvalidArgumentError)
+ }
+)
+
test.skipIf(isDebug)(
'auto-pause without auto-resume requires connect to wake',
async () => {
@@ -31,6 +66,47 @@ test.skipIf(isDebug)(
60_000
)
+test.skipIf(isDebug)(
+ 'filesystem-only auto-pause reboots on connect',
+ async () => {
+ // keepMemory:false makes the timeout auto-pause filesystem-only, so resuming
+ // cold-boots the sandbox from disk.
+ const sandbox = await Sandbox.create(template, {
+ timeoutMs: 3_000,
+ lifecycle: { onTimeout: { action: 'pause', keepMemory: false } },
+ })
+
+ try {
+ const marker = 'auto-pause-fs-only'
+ await sandbox.files.write('/home/user/auto-pause-marker.txt', marker)
+ const bootBefore = (
+ await sandbox.files.read('/proc/sys/kernel/random/boot_id')
+ ).trim()
+
+ await wait(5_000)
+
+ assert.equal((await sandbox.getInfo()).state, 'paused')
+
+ // A filesystem-only snapshot cannot auto-resume on traffic; connect
+ // resumes it by cold-booting.
+ await sandbox.connect()
+
+ const persisted = (
+ await sandbox.files.read('/home/user/auto-pause-marker.txt')
+ ).trim()
+ assert.equal(persisted, marker)
+
+ const bootAfter = (
+ await sandbox.files.read('/proc/sys/kernel/random/boot_id')
+ ).trim()
+ assert.notEqual(bootAfter, bootBefore)
+ } finally {
+ await sandbox.kill().catch(() => {})
+ }
+ },
+ 60_000
+)
+
test.skipIf(isDebug)(
'auto-resume wakes paused sandbox on http request',
async () => {
diff --git a/packages/python-sdk/e2b/__init__.py b/packages/python-sdk/e2b/__init__.py
index ca46170fd..c8b65aa74 100644
--- a/packages/python-sdk/e2b/__init__.py
+++ b/packages/python-sdk/e2b/__init__.py
@@ -79,6 +79,7 @@ from .sandbox.sandbox_api import (
SandboxInfoLifecycle,
SandboxMetrics,
SandboxLifecycle,
+ SandboxOnTimeout,
SandboxNetworkInfo,
SandboxNetworkOpts,
SandboxNetworkRule,
@@ -201,6 +202,7 @@ __all__ = [
"SandboxNetworkTransform",
"SandboxNetworkUpdate",
"SandboxLifecycle",
+ "SandboxOnTimeout",
"ALL_TRAFFIC",
# Snapshot
"SnapshotInfo",
diff --git a/packages/python-sdk/e2b/api/client/models/new_sandbox.py b/packages/python-sdk/e2b/api/client/models/new_sandbox.py
index 8703ef569..d09b636c2 100644
--- a/packages/python-sdk/e2b/api/client/models/new_sandbox.py
+++ b/packages/python-sdk/e2b/api/client/models/new_sandbox.py
@@ -24,6 +24,11 @@ class NewSandbox:
allow_internet_access (Union[Unset, bool]): Allow sandbox to access the internet. When set to false, it behaves
the same as specifying denyOut to 0.0.0.0/0 in the network config.
auto_pause (Union[Unset, bool]): Automatically pauses the sandbox after the timeout Default: False.
+ auto_pause_memory (Union[Unset, bool]): Controls the snapshot kind taken when the sandbox auto-pauses on timeout
+ (only relevant when autoPause is true). When false, the auto-pause drops the in-memory state and persists only
+ the filesystem (a filesystem-only snapshot); resuming it cold-boots (reboots) the sandbox from disk. Such a
+ snapshot cannot be auto-resumed by traffic and must be resumed explicitly, so it cannot be combined with
+ autoResume. Defaults to true (full memory snapshot). Default: True.
auto_resume (Union[Unset, SandboxAutoResumeConfig]): Auto-resume configuration for paused sandboxes.
env_vars (Union[Unset, Any]):
mcp (Union['McpType0', None, Unset]): MCP configuration for the sandbox
@@ -37,6 +42,7 @@ class NewSandbox:
template_id: str
allow_internet_access: Union[Unset, bool] = UNSET
auto_pause: Union[Unset, bool] = False
+ auto_pause_memory: Union[Unset, bool] = True
auto_resume: Union[Unset, "SandboxAutoResumeConfig"] = UNSET
env_vars: Union[Unset, Any] = UNSET
mcp: Union["McpType0", None, Unset] = UNSET
@@ -56,6 +62,8 @@ class NewSandbox:
auto_pause = self.auto_pause
+ auto_pause_memory = self.auto_pause_memory
+
auto_resume: Union[Unset, dict[str, Any]] = UNSET
if not isinstance(self.auto_resume, Unset):
auto_resume = self.auto_resume.to_dict()
@@ -98,6 +106,8 @@ class NewSandbox:
field_dict["allow_internet_access"] = allow_internet_access
if auto_pause is not UNSET:
field_dict["autoPause"] = auto_pause
+ if auto_pause_memory is not UNSET:
+ field_dict["autoPauseMemory"] = auto_pause_memory
if auto_resume is not UNSET:
field_dict["autoResume"] = auto_resume
if env_vars is not UNSET:
@@ -131,6 +141,8 @@ class NewSandbox:
auto_pause = d.pop("autoPause", UNSET)
+ auto_pause_memory = d.pop("autoPauseMemory", UNSET)
+
_auto_resume = d.pop("autoResume", UNSET)
auto_resume: Union[Unset, SandboxAutoResumeConfig]
if isinstance(_auto_resume, Unset):
@@ -181,6 +193,7 @@ class NewSandbox:
template_id=template_id,
allow_internet_access=allow_internet_access,
auto_pause=auto_pause,
+ auto_pause_memory=auto_pause_memory,
auto_resume=auto_resume,
env_vars=env_vars,
mcp=mcp,
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index ec97b0f9e..4799e0df1 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -239,21 +239,72 @@ class SandboxNetworkInfo(TypedDict, total=False):
mask_request_host: str
+class SandboxOnTimeoutPause(TypedDict):
+ """
+ Object form of `on_timeout` that auto-pauses the sandbox when the timeout is
+ reached, optionally controlling the pause snapshot kind via `keep_memory`.
+ """
+
+ action: Literal["pause"]
+ """Auto-pause the sandbox when the timeout is reached."""
+
+ 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.
+
+ 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
+ woke it hits an already-running process. A filesystem-only snapshot has no
+ memory to restore — resuming cold-boots it — so it can't be woken transparently
+ by traffic and must be resumed explicitly via `connect()`.
+ """
+
+
+class SandboxOnTimeoutKill(TypedDict):
+ """
+ Object form of `on_timeout` that kills the sandbox when the timeout is reached.
+ """
+
+ action: Literal["kill"]
+ """Kill the sandbox when the timeout is reached."""
+
+
+SandboxOnTimeout = Union[
+ Literal["pause", "kill"], SandboxOnTimeoutPause, SandboxOnTimeoutKill
+]
+"""
+What should happen to the sandbox when the timeout is reached. Either the bare
+action (`"pause"` / `"kill"`) or the object form. The object form is a
+discriminated union on `action`: `keep_memory` is only accepted alongside
+`action: "pause"`. Passing `keep_memory` with `action: "kill"` is a static type
+error.
+"""
+
+
class SandboxLifecycle(TypedDict):
"""
Sandbox lifecycle configuration; defines post-timeout behavior and auto-resume settings.
Defaults to `on_timeout="kill"` and `auto_resume=False`.
"""
- on_timeout: Literal["pause", "kill"]
+ on_timeout: SandboxOnTimeout
"""
- What should happen to the sandbox when timeout is reached. `"kill"` means the sandbox will be terminated, while `"pause"` means the sandbox will be paused and can be resumed later. Defaults to `"kill"`.
+ 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"`.
"""
auto_resume: NotRequired[bool]
"""
Whether activity should cause the sandbox to resume when paused. Defaults to `False`.
- Can be `True` only when `on_timeout` is `pause`.
+ Can be `True` only when `on_timeout` is `pause`. Not supported when
+ `keep_memory` is `False` (a filesystem-only snapshot must be resumed
+ explicitly via `connect()`).
"""
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 4b688ab2f..28ce5d4f3 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 allow_internet_access: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`.
: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``.
- :param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}``
+ :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 volume_mounts: Dictionary mapping mount paths to AsyncVolume instances or volume names
:return: A Sandbox instance for the new sandbox
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index 66758ba95..7a47ca171 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -202,18 +202,51 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
- on_timeout = lifecycle.get("on_timeout", "kill") if lifecycle else "kill"
+ # 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 the resolved on_timeout is 'pause'."
+ "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()."
)
network_body = build_network_config(network)
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),
metadata=metadata or {},
timeout=timeout,
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index 12c2c5415..eb41bb6d1 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -184,7 +184,7 @@ class Sandbox(SandboxApi):
:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`. If set to `False`, it works the same as setting network `deny_out` to `[0.0.0.0/0]`.
: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``.
- :param lifecycle: Sandbox lifecycle configuration — ``on_timeout``: ``"kill"`` (default) or ``"pause"``; ``auto_resume``: ``False`` (default) or ``True`` (only when ``on_timeout="pause"``). Example: ``{"on_timeout": "pause", "auto_resume": True}``
+ :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 volume_mounts: Dictionary mapping mount paths to Volume instances or volume names
:return: A Sandbox instance for the new sandbox
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index 435f593d4..3ed10c5f6 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -201,18 +201,51 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
- on_timeout = lifecycle.get("on_timeout", "kill") if lifecycle else "kill"
+ # 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 the resolved on_timeout is 'pause'."
+ "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()."
)
network_body = build_network_config(network)
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),
metadata=metadata or {},
timeout=timeout,
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 4b334e129..aa17c2c52 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_create.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_create.py
@@ -1,4 +1,5 @@
import asyncio
+from typing import Any, cast
import httpx
import pytest
@@ -8,6 +9,7 @@ from e2b.api.client.models import (
NewSandbox,
SandboxAutoResumeConfig,
)
+from e2b.exceptions import InvalidArgumentException
@pytest.mark.skip_debug()
@@ -58,6 +60,97 @@ def test_create_payload_deserializes_auto_resume_enabled():
assert body.auto_resume.to_dict() == {"enabled": False}
+async def test_filesystem_only_auto_pause_rejects_auto_resume():
+ # A filesystem-only auto-pause snapshot can only be resumed explicitly, so
+ # combining keep_memory=False with auto_resume is rejected client-side.
+ with pytest.raises(InvalidArgumentException):
+ await AsyncSandbox.create(
+ timeout=3,
+ lifecycle={
+ "on_timeout": {"action": "pause", "keep_memory": False},
+ "auto_resume": True,
+ },
+ )
+
+
+async def test_keep_memory_not_allowed_with_kill():
+ # The discriminated union forbids keep_memory on action="kill" at type-check
+ # time; the runtime guard rejects it for callers that bypass the type
+ # (cast(Any, ...) feeds the deliberately type-invalid input).
+ with pytest.raises(InvalidArgumentException):
+ await AsyncSandbox.create(
+ timeout=3,
+ lifecycle=cast(
+ Any, {"on_timeout": {"action": "kill", "keep_memory": False}}
+ ),
+ )
+
+
+async def test_invalid_on_timeout_type_does_not_crash(async_sandbox_factory):
+ # An untyped/invalid on_timeout (e.g. None) must not crash create; it falls
+ # back to kill semantics like a missing on_timeout (the sandbox just starts).
+ sbx = await async_sandbox_factory(
+ timeout=10, lifecycle=cast(Any, {"on_timeout": None})
+ )
+ assert await sbx.is_running()
+
+
+async def test_keep_memory_none_defaults_to_full_memory(async_sandbox_factory):
+ # An explicit None keep_memory must default to full memory (not filesystem-only):
+ # the timeout auto-pause then resumes the SAME sandbox in place (memory restore),
+ # so the boot id is unchanged. A changed boot id would mean None was wrongly
+ # treated as filesystem-only (cold boot).
+ sbx = await async_sandbox_factory(
+ timeout=60,
+ lifecycle={"on_timeout": {"action": "pause", "keep_memory": None}},
+ )
+ boot_before = (await sbx.files.read("/proc/sys/kernel/random/boot_id")).strip()
+
+ await sbx.set_timeout(0) # force the timeout auto-pause now
+ for _ in range(150):
+ if not await sbx.is_running():
+ break
+ await asyncio.sleep(0.2)
+ assert not await sbx.is_running()
+
+ resumed = await sbx.connect()
+ assert resumed.sandbox_id == sbx.sandbox_id # same sandbox
+ boot_after = (await resumed.files.read("/proc/sys/kernel/random/boot_id")).strip()
+ assert boot_after == boot_before # memory restore in place, not a cold boot
+
+
+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.
+ sandbox = await async_sandbox_factory(
+ timeout=3,
+ lifecycle={"on_timeout": {"action": "pause", "keep_memory": False}},
+ )
+
+ marker = "auto-pause-fs-only"
+ 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
+
+ # A filesystem-only snapshot cannot auto-resume on traffic; connect resumes
+ # it by cold-booting.
+ resumed = await sandbox.connect()
+
+ persisted = (await resumed.files.read("/home/user/auto-pause-marker.txt")).strip()
+ assert persisted == marker
+
+ boot_after = (await resumed.files.read("/proc/sys/kernel/random/boot_id")).strip()
+ assert boot_after != boot_before
+
+
@pytest.mark.skip_debug()
async def test_auto_pause_without_auto_resume_requires_connect(async_sandbox_factory):
sandbox = await async_sandbox_factory(
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 48a8a8346..737e346d1 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,5 @@
from time import sleep
+from typing import Any, cast
import httpx
import pytest
@@ -8,6 +9,7 @@ from e2b.api.client.models import (
NewSandbox,
SandboxAutoResumeConfig,
)
+from e2b.exceptions import InvalidArgumentException
from e2b.sandbox.sandbox_api import SandboxQuery
@@ -59,6 +61,95 @@ def test_create_payload_deserializes_auto_resume_enabled():
assert body.auto_resume.to_dict() == {"enabled": False}
+def test_filesystem_only_auto_pause_rejects_auto_resume():
+ # A filesystem-only auto-pause snapshot can only be resumed explicitly, so
+ # combining keep_memory=False with auto_resume is rejected client-side.
+ with pytest.raises(InvalidArgumentException):
+ Sandbox.create(
+ timeout=3,
+ lifecycle={
+ "on_timeout": {"action": "pause", "keep_memory": False},
+ "auto_resume": True,
+ },
+ )
+
+
+def test_keep_memory_not_allowed_with_kill():
+ # The discriminated union forbids keep_memory on action="kill" at type-check
+ # time; the runtime guard rejects it for callers that bypass the type
+ # (cast(Any, ...) feeds the deliberately type-invalid input).
+ with pytest.raises(InvalidArgumentException):
+ Sandbox.create(
+ timeout=3,
+ lifecycle=cast(
+ Any, {"on_timeout": {"action": "kill", "keep_memory": False}}
+ ),
+ )
+
+
+def test_invalid_on_timeout_type_does_not_crash(sandbox_factory):
+ # An untyped/invalid on_timeout (e.g. None) must not crash create; it falls
+ # back to kill semantics like a missing on_timeout (the sandbox just starts).
+ sbx = sandbox_factory(timeout=10, lifecycle=cast(Any, {"on_timeout": None}))
+ assert sbx.is_running()
+
+
+def test_keep_memory_none_defaults_to_full_memory(sandbox_factory):
+ # An explicit None keep_memory must default to full memory (not filesystem-only):
+ # the timeout auto-pause then resumes the SAME sandbox in place (memory restore),
+ # so the boot id is unchanged. A changed boot id would mean None was wrongly
+ # treated as filesystem-only (cold boot).
+ sbx = sandbox_factory(
+ timeout=60,
+ lifecycle={"on_timeout": {"action": "pause", "keep_memory": None}},
+ )
+ boot_before = sbx.files.read("/proc/sys/kernel/random/boot_id").strip()
+
+ sbx.set_timeout(0) # force the timeout auto-pause now
+ for _ in range(150):
+ if not sbx.is_running():
+ break
+ sleep(0.2)
+ assert not sbx.is_running()
+
+ resumed = sbx.connect()
+ assert resumed.sandbox_id == sbx.sandbox_id # same sandbox
+ boot_after = resumed.files.read("/proc/sys/kernel/random/boot_id").strip()
+ assert boot_after == boot_before # memory restore in place, not a cold boot
+
+
+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.
+ sandbox = sandbox_factory(
+ timeout=3,
+ lifecycle={"on_timeout": {"action": "pause", "keep_memory": False}},
+ )
+
+ marker = "auto-pause-fs-only"
+ 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
+
+ # A filesystem-only snapshot cannot auto-resume on traffic; connect resumes
+ # it by cold-booting.
+ resumed = sandbox.connect()
+
+ persisted = resumed.files.read("/home/user/auto-pause-marker.txt").strip()
+ assert persisted == marker
+
+ boot_after = resumed.files.read("/proc/sys/kernel/random/boot_id").strip()
+ assert boot_after != boot_before
+
+
@pytest.mark.skip_debug()
def test_auto_pause_without_auto_resume_requires_connect(sandbox_factory):
sandbox = sandbox_factory(
diff --git a/spec/openapi.yml b/spec/openapi.yml
index b8c1bb063..0f20f8d70 100644
--- a/spec/openapi.yml
+++ b/spec/openapi.yml
@@ -689,6 +689,17 @@ components:
type: boolean
default: false
description: Automatically pauses the sandbox after the timeout
+ autoPauseMemory:
+ type: boolean
+ default: true
+ description: >-
+ Controls the snapshot kind taken when the sandbox auto-pauses on
+ timeout (only relevant when autoPause is true). When false, the
+ auto-pause drops the in-memory state and persists only the
+ filesystem (a filesystem-only snapshot); resuming it cold-boots
+ (reboots) the sandbox from disk. Such a snapshot cannot be
+ auto-resumed by traffic and must be resumed explicitly, so it cannot
+ be combined with autoResume. Defaults to true (full memory snapshot).
autoResume:
$ref: '#/components/schemas/SandboxAutoResumeConfig'
secure: