Skip to content

armgit / E2B

Public Imported from GitHub
0

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

fix(sdks): make lifecycle.on_timeout and auto_pause precedence consistent (#1343)

Tomas Valentad21b936bf77d
diff --git a/.changeset/little-webs-drive.md b/.changeset/little-webs-drive.md
new file mode 100644
index 000000000..4168c7d2f
--- /dev/null
+++ b/.changeset/little-webs-drive.md
@@ -0,0 +1,8 @@
+---
+'@e2b/python-sdk': minor
+'e2b': minor
+---
+
+- Fix lifecycle and autopause precedence
+- Deprecate `auto_pause`/`autoPause`; use `lifecycle={"on_timeout": "pause"}` instead. A `DeprecationWarning` (Python) / `console.warn` (JS) is now emitted when the flag is set
+- **Breaking validation change**: passing `auto_resume=true` while the resolved `on_timeout` is `"kill"` now raises `InvalidArgumentException` (Python) / `InvalidArgumentError` (JS)
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 0ab54ab7e..32b37ecff 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -5,7 +5,11 @@ import {
DEFAULT_SANDBOX_TIMEOUT_MS,
} from '../connectionConfig'
import { compareVersions } from 'compare-versions'
-import { SandboxNotFoundError, TemplateError } from '../errors'
+import {
+ InvalidArgumentError,
+ SandboxNotFoundError,
+ TemplateError,
+} from '../errors'
import { timeoutToSeconds } from '../utils'
import type { Volume } from '../volume'
import type { McpServer as BaseMcpServer } from './mcp'
@@ -419,23 +423,27 @@ export interface SandboxMetrics {
diskTotal: number
}
-function getLifecycle(
+export function getLifecycle(
opts?: Pick<SandboxBetaCreateOpts, 'lifecycle' | 'autoPause'>
): SandboxLifecycle {
- if (opts?.lifecycle) {
- return opts.lifecycle
+ if (opts?.autoPause !== undefined) {
+ console.warn(
+ "`autoPause` is deprecated; use `lifecycle: { onTimeout: 'pause' }` instead."
+ )
}
- if (opts?.autoPause) {
- return {
- onTimeout: 'pause',
- autoResume: false,
- }
+ const onTimeout =
+ opts?.lifecycle?.onTimeout ?? (opts?.autoPause ? 'pause' : 'kill')
+
+ if (opts?.lifecycle?.autoResume === true && onTimeout !== 'pause') {
+ throw new InvalidArgumentError(
+ "autoResume can only be true when the resolved onTimeout is 'pause'."
+ )
}
return {
- onTimeout: 'kill',
- autoResume: false,
+ onTimeout,
+ autoResume: opts?.lifecycle?.autoResume,
}
}
@@ -795,12 +803,8 @@ export class SandboxApi {
) {
const config = new ConnectionConfig(opts)
const client = new ApiClient(config)
- const lifecycle = getLifecycle(opts)
- const autoPause = lifecycle.onTimeout === 'pause'
- const autoResumeEnabled =
- lifecycle.onTimeout === 'pause'
- ? (lifecycle.autoResume ?? false)
- : undefined
+ const { onTimeout, autoResume } = getLifecycle(opts)
+ const autoPause = onTimeout === 'pause'
const body: components['schemas']['NewSandbox'] = {
templateID: template,
@@ -811,9 +815,9 @@ export class SandboxApi {
secure: opts?.secure ?? true,
allow_internet_access: opts?.allowInternetAccess ?? true,
network: opts?.network,
- ...(autoPause !== undefined ? { autoPause } : {}),
- ...(autoResumeEnabled !== undefined
- ? { autoResume: { enabled: autoResumeEnabled } }
+ autoPause,
+ ...(autoResume !== undefined
+ ? { autoResume: { enabled: autoResume } }
: {}),
}
diff --git a/packages/js-sdk/tests/sandbox/getLifecycle.test.ts b/packages/js-sdk/tests/sandbox/getLifecycle.test.ts
new file mode 100644
index 000000000..475ee3260
--- /dev/null
+++ b/packages/js-sdk/tests/sandbox/getLifecycle.test.ts
@@ -0,0 +1,126 @@
+import { assert, describe, test } from 'vitest'
+
+import { InvalidArgumentError } from '../../src'
+import { getLifecycle } from '../../src/sandbox/sandboxApi'
+
+describe('getLifecycle', () => {
+ test('returns defaults when no opts are provided', () => {
+ assert.deepEqual(getLifecycle(), {
+ onTimeout: 'kill',
+ autoResume: undefined,
+ })
+ })
+
+ test('returns defaults when opts is empty', () => {
+ assert.deepEqual(getLifecycle({}), {
+ onTimeout: 'kill',
+ autoResume: undefined,
+ })
+ })
+
+ test('lifecycle.onTimeout takes precedence over autoPause=true', () => {
+ assert.deepEqual(
+ getLifecycle({ lifecycle: { onTimeout: 'kill' }, autoPause: true }),
+ {
+ onTimeout: 'kill',
+ autoResume: undefined,
+ }
+ )
+ })
+
+ test('lifecycle.onTimeout=pause takes precedence over autoPause=false', () => {
+ assert.deepEqual(
+ getLifecycle({ lifecycle: { onTimeout: 'pause' }, autoPause: false }),
+ {
+ onTimeout: 'pause',
+ autoResume: undefined,
+ }
+ )
+ })
+
+ test('falls back to autoPause when lifecycle.onTimeout is missing', () => {
+ // partial lifecycle without onTimeout (possible at runtime despite TS typing)
+ const lifecycle = { autoResume: true } as unknown as {
+ onTimeout: 'pause' | 'kill'
+ autoResume?: boolean
+ }
+ assert.deepEqual(getLifecycle({ lifecycle, autoPause: true }), {
+ onTimeout: 'pause',
+ autoResume: true,
+ })
+ })
+
+ test('autoPause=true with no lifecycle maps to onTimeout=pause', () => {
+ assert.deepEqual(getLifecycle({ autoPause: true }), {
+ onTimeout: 'pause',
+ autoResume: undefined,
+ })
+ })
+
+ test('autoPause=false with no lifecycle maps to onTimeout=kill', () => {
+ assert.deepEqual(getLifecycle({ autoPause: false }), {
+ onTimeout: 'kill',
+ autoResume: undefined,
+ })
+ })
+
+ test('preserves autoResume from lifecycle', () => {
+ assert.deepEqual(
+ getLifecycle({ lifecycle: { onTimeout: 'pause', autoResume: true } }),
+ {
+ onTimeout: 'pause',
+ autoResume: true,
+ }
+ )
+ assert.deepEqual(
+ getLifecycle({ lifecycle: { onTimeout: 'pause', autoResume: false } }),
+ {
+ onTimeout: 'pause',
+ autoResume: false,
+ }
+ )
+ })
+
+ test('autoResume is undefined when omitted from lifecycle', () => {
+ assert.deepEqual(getLifecycle({ lifecycle: { onTimeout: 'pause' } }), {
+ onTimeout: 'pause',
+ autoResume: undefined,
+ })
+ })
+
+ test('autoResume is undefined when only autoPause is provided', () => {
+ assert.equal(getLifecycle({ autoPause: true }).autoResume, undefined)
+ assert.equal(getLifecycle({ autoPause: false }).autoResume, undefined)
+ })
+
+ test('throws when autoResume=true and onTimeout=kill', () => {
+ assert.throws(
+ () =>
+ getLifecycle({
+ lifecycle: { onTimeout: 'kill', autoResume: true },
+ }),
+ InvalidArgumentError
+ )
+ })
+
+ test('throws when autoResume=true and effective onTimeout resolves to kill', () => {
+ // partial lifecycle with autoResume=true; no onTimeout; autoPause falsy.
+ const lifecycle = { autoResume: true } as unknown as {
+ onTimeout: 'pause' | 'kill'
+ autoResume?: boolean
+ }
+ assert.throws(() => getLifecycle({ lifecycle }), InvalidArgumentError)
+ assert.throws(
+ () => getLifecycle({ lifecycle, autoPause: false }),
+ InvalidArgumentError
+ )
+ })
+
+ test('does not throw when autoResume=true and autoPause=true (no explicit onTimeout)', () => {
+ const lifecycle = { autoResume: true } as unknown as {
+ onTimeout: 'pause' | 'kill'
+ autoResume?: boolean
+ }
+ assert.doesNotThrow(() => getLifecycle({ lifecycle, autoPause: true }))
+ })
+})
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index fc8b47868..519b8fcfb 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -7,12 +7,17 @@ from typing_extensions import NotRequired, Unpack
from e2b.api.client.models import (
ListedSandbox,
SandboxDetail,
+ SandboxState,
+)
+from e2b.api.client.models import (
SandboxLifecycle as ClientSandboxLifecycle,
+)
+from e2b.api.client.models import (
SandboxNetworkConfig as ClientSandboxNetworkConfig,
- SandboxState,
)
from e2b.api.client.types import Unset
from e2b.connection_config import ApiParams
+from e2b.exceptions import InvalidArgumentException
from e2b.sandbox.mcp import McpServer as BaseMcpServer
@@ -116,11 +121,29 @@ class SandboxInfoLifecycle(TypedDict):
"""
-def get_auto_resume_enabled(lifecycle: Optional[SandboxLifecycle]) -> Optional[bool]:
- if lifecycle is None or lifecycle.get("on_timeout") != "pause":
- return None
+def get_lifecycle(
+ lifecycle: Optional[SandboxLifecycle],
+ auto_pause: Optional[bool],
+) -> SandboxLifecycle:
+ auto_resume = lifecycle.get("auto_resume") if lifecycle is not None else None
+
+ explicit_on_timeout = lifecycle.get("on_timeout") if lifecycle is not None else None
+ on_timeout: Literal["pause", "kill"] = (
+ explicit_on_timeout
+ if explicit_on_timeout is not None
+ else ("pause" if auto_pause else "kill")
+ )
+
+ if auto_resume and on_timeout != "pause":
+ raise InvalidArgumentException(
+ "auto_resume can only be True when the resolved on_timeout is 'pause'."
+ )
+
+ resolved = SandboxLifecycle(on_timeout=on_timeout)
+ if auto_resume is not None:
+ resolved["auto_resume"] = auto_resume
- return lifecycle.get("auto_resume", False)
+ return resolved
def from_client_network_config(
diff --git a/packages/python-sdk/e2b/sandbox_async/main.py b/packages/python-sdk/e2b/sandbox_async/main.py
index 83e691f71..5f8a32b0c 100644
--- a/packages/python-sdk/e2b/sandbox_async/main.py
+++ b/packages/python-sdk/e2b/sandbox_async/main.py
@@ -3,6 +3,7 @@ import json
import logging
import shlex
import uuid
+import warnings
from typing import Dict, List, Optional, Union, overload
import httpx
@@ -551,13 +552,14 @@ class AsyncSandbox(SandboxApi):
cls,
template: Optional[str] = None,
timeout: Optional[int] = None,
- auto_pause: bool = False,
+ auto_pause: Optional[bool] = None,
metadata: Optional[Dict[str, str]] = None,
envs: Optional[Dict[str, str]] = None,
secure: bool = True,
allow_internet_access: bool = True,
mcp: Optional[McpServer] = None,
volume_mounts: Optional[SandboxAsyncVolumeMount] = None,
+ lifecycle: Optional[SandboxLifecycle] = None,
**opts: Unpack[ApiParams],
) -> Self:
"""
@@ -569,18 +571,27 @@ class AsyncSandbox(SandboxApi):
:param template: Sandbox template name or ID
:param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
- :param auto_pause: Automatically pause the sandbox after the timeout expires. Defaults to `False`.
+ :param auto_pause: **Deprecated**: use ``lifecycle={"on_timeout": "pause"}`` instead.
+ Automatically pause the sandbox after the timeout expires. Defaults to ``False``.
:param metadata: Custom metadata for the sandbox
:param envs: Custom environment variables for the sandbox
:param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.
:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.
:param mcp: MCP server to enable in the sandbox
:param volume_mounts: Dictionary mapping mount paths to AsyncVolume instances or volume names
+ :param lifecycle: Sandbox lifecycle configuration; controls timeout behavior and auto-resume.
:return: A Sandbox instance for the new sandbox
Use this method instead of using the constructor to create a new sandbox.
"""
+ if auto_pause is not None:
+ warnings.warn(
+ "`auto_pause` is deprecated; use `lifecycle={'on_timeout': 'pause'}` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
if not template and mcp is not None:
template = cls.default_mcp_template
elif not template:
@@ -605,9 +616,7 @@ class AsyncSandbox(SandboxApi):
secure=secure,
allow_internet_access=allow_internet_access,
mcp=mcp,
- lifecycle=(
- {"on_timeout": "pause", "auto_resume": False} if auto_pause else None
- ),
+ lifecycle=lifecycle,
volume_mounts=transformed_mounts,
**opts,
)
diff --git a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
index 2bd1f73e5..69688fca7 100644
--- a/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_async/sandbox_api.py
@@ -37,14 +37,14 @@ from e2b.exceptions import (
)
from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
- SandboxLifecycle,
- get_auto_resume_enabled,
McpServer,
SandboxInfo,
+ SandboxLifecycle,
SandboxMetrics,
SandboxNetworkOpts,
SandboxQuery,
SnapshotInfo,
+ get_lifecycle,
)
from e2b.sandbox_async.paginator import AsyncSandboxPaginator
@@ -177,13 +177,10 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
- should_auto_pause = (
- lifecycle["on_timeout"] == "pause" if lifecycle is not None else auto_pause
- )
- auto_resume_enabled = get_auto_resume_enabled(lifecycle)
+ lifecycle = get_lifecycle(lifecycle, auto_pause)
body = NewSandbox(
template_id=template,
- auto_pause=(should_auto_pause if should_auto_pause is not None else UNSET),
+ auto_pause=lifecycle["on_timeout"] == "pause",
metadata=metadata or {},
timeout=timeout,
env_vars=env_vars or {},
@@ -193,8 +190,8 @@ class SandboxApi(SandboxBase):
network=SandboxNetworkConfig(**network) if network else UNSET,
volume_mounts=volume_mounts if volume_mounts else UNSET,
)
- if auto_resume_enabled is not None:
- body.auto_resume = SandboxAutoResumeConfig(enabled=auto_resume_enabled)
+ if "auto_resume" in lifecycle:
+ body.auto_resume = SandboxAutoResumeConfig(enabled=lifecycle["auto_resume"])
api_client = get_api_client(config)
res = await post_sandboxes.asyncio_detailed(
diff --git a/packages/python-sdk/e2b/sandbox_sync/main.py b/packages/python-sdk/e2b/sandbox_sync/main.py
index bb818b9e2..c2f184c28 100644
--- a/packages/python-sdk/e2b/sandbox_sync/main.py
+++ b/packages/python-sdk/e2b/sandbox_sync/main.py
@@ -3,6 +3,7 @@ import json
import logging
import shlex
import uuid
+import warnings
from typing import Dict, List, Optional, Union, overload
import httpx
@@ -552,13 +553,14 @@ class Sandbox(SandboxApi):
cls,
template: Optional[str] = None,
timeout: Optional[int] = None,
- auto_pause: bool = False,
+ auto_pause: Optional[bool] = None,
metadata: Optional[Dict[str, str]] = None,
envs: Optional[Dict[str, str]] = None,
secure: bool = True,
allow_internet_access: bool = True,
mcp: Optional[McpServer] = None,
volume_mounts: Optional[SandboxVolumeMount] = None,
+ lifecycle: Optional[SandboxLifecycle] = None,
**opts: Unpack[ApiParams],
) -> Self:
"""
@@ -570,18 +572,27 @@ class Sandbox(SandboxApi):
:param template: Sandbox template name or ID
:param timeout: Timeout for the sandbox in **seconds**, default to 300 seconds. The maximum time a sandbox can be kept alive is 24 hours (86_400 seconds) for Pro users and 1 hour (3_600 seconds) for Hobby users.
- :param auto_pause: Automatically pause the sandbox after the timeout expires. Defaults to `False`.
+ :param auto_pause: **Deprecated**: use ``lifecycle={"on_timeout": "pause"}`` instead.
+ Automatically pause the sandbox after the timeout expires. Defaults to ``False``.
:param metadata: Custom metadata for the sandbox
:param envs: Custom environment variables for the sandbox
:param secure: Envd is secured with access token and cannot be used without it, defaults to `True`.
:param allow_internet_access: Allow sandbox to access the internet, defaults to `True`.
:param mcp: MCP server to enable in the sandbox
:param volume_mounts: Dictionary mapping mount paths to Volume instances or volume names
+ :param lifecycle: Sandbox lifecycle configuration; controls timeout behavior and auto-resume.
:return: A Sandbox instance for the new sandbox
Use this method instead of using the constructor to create a new sandbox.
"""
+ if auto_pause is not None:
+ warnings.warn(
+ "`auto_pause` is deprecated; use `lifecycle={'on_timeout': 'pause'}` instead.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+
if not template and mcp is not None:
template = cls.default_mcp_template
elif not template:
@@ -606,9 +617,7 @@ class Sandbox(SandboxApi):
secure=secure,
allow_internet_access=allow_internet_access,
mcp=mcp,
- lifecycle=(
- {"on_timeout": "pause", "auto_resume": False} if auto_pause else None
- ),
+ lifecycle=lifecycle,
volume_mounts=transformed_mounts,
**opts,
)
diff --git a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
index 648c1b414..782db6baf 100644
--- a/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox_sync/sandbox_api.py
@@ -37,7 +37,7 @@ from e2b.exceptions import (
from e2b.sandbox.main import SandboxBase
from e2b.sandbox.sandbox_api import (
SandboxLifecycle,
- get_auto_resume_enabled,
+ get_lifecycle,
McpServer,
SandboxInfo,
SandboxMetrics,
@@ -176,13 +176,10 @@ class SandboxApi(SandboxBase):
) -> SandboxCreateResponse:
config = ConnectionConfig(**opts)
- should_auto_pause = (
- lifecycle["on_timeout"] == "pause" if lifecycle is not None else auto_pause
- )
- auto_resume_enabled = get_auto_resume_enabled(lifecycle)
+ lifecycle = get_lifecycle(lifecycle, auto_pause)
body = NewSandbox(
template_id=template,
- auto_pause=(should_auto_pause if should_auto_pause is not None else UNSET),
+ auto_pause=lifecycle["on_timeout"] == "pause",
metadata=metadata or {},
timeout=timeout,
env_vars=env_vars or {},
@@ -192,8 +189,8 @@ class SandboxApi(SandboxBase):
network=SandboxNetworkConfig(**network) if network else UNSET,
volume_mounts=volume_mounts if volume_mounts else UNSET,
)
- if auto_resume_enabled is not None:
- body.auto_resume = SandboxAutoResumeConfig(enabled=auto_resume_enabled)
+ if "auto_resume" in lifecycle:
+ body.auto_resume = SandboxAutoResumeConfig(enabled=lifecycle["auto_resume"])
api_client = get_api_client(config)
res = post_sandboxes.sync_detailed(
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 e5d002945..4b334e129 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_create.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_create.py
@@ -8,7 +8,6 @@ from e2b.api.client.models import (
NewSandbox,
SandboxAutoResumeConfig,
)
-from e2b.sandbox.sandbox_api import get_auto_resume_enabled
@pytest.mark.skip_debug()
@@ -35,17 +34,6 @@ async def test_metadata(async_sandbox_factory):
assert False, "Sandbox not found"
-def test_lifecycle_auto_resume_enabled_mapping():
- assert get_auto_resume_enabled({"on_timeout": "pause", "auto_resume": True}) is True
- assert (
- get_auto_resume_enabled({"on_timeout": "pause", "auto_resume": False}) is False
- )
- assert get_auto_resume_enabled({"on_timeout": "pause"}) is False
- assert get_auto_resume_enabled({"on_timeout": "kill", "auto_resume": False}) is None
- assert get_auto_resume_enabled({"on_timeout": "kill"}) is None
- assert get_auto_resume_enabled(None) is None
-
-
def test_create_payload_serializes_auto_resume_enabled():
body = NewSandbox(
template_id="template-id",
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 40622447f..48a8a8346 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
@@ -8,7 +8,7 @@ from e2b.api.client.models import (
NewSandbox,
SandboxAutoResumeConfig,
)
-from e2b.sandbox.sandbox_api import SandboxQuery, get_auto_resume_enabled
+from e2b.sandbox.sandbox_api import SandboxQuery
@pytest.mark.skip_debug()
@@ -35,17 +35,6 @@ def test_metadata(sandbox_factory):
assert False, "Sandbox not found"
-def test_lifecycle_auto_resume_enabled_mapping():
- assert get_auto_resume_enabled({"on_timeout": "pause", "auto_resume": True}) is True
- assert (
- get_auto_resume_enabled({"on_timeout": "pause", "auto_resume": False}) is False
- )
- assert get_auto_resume_enabled({"on_timeout": "pause"}) is False
- assert get_auto_resume_enabled({"on_timeout": "kill", "auto_resume": False}) is None
- assert get_auto_resume_enabled({"on_timeout": "kill"}) is None
- assert get_auto_resume_enabled(None) is None
-
-
def test_create_payload_serializes_auto_resume_enabled():
body = NewSandbox(
template_id="template-id",
diff --git a/packages/python-sdk/tests/test_sandbox_api.py b/packages/python-sdk/tests/test_sandbox_api.py
new file mode 100644
index 000000000..faf7b20e9
--- /dev/null
+++ b/packages/python-sdk/tests/test_sandbox_api.py
@@ -0,0 +1,70 @@
+import pytest
+
+from e2b.exceptions import InvalidArgumentException
+from e2b.sandbox.sandbox_api import get_lifecycle
+
+
+def test_get_lifecycle_returns_defaults_when_nothing_provided():
+ assert get_lifecycle(None, None) == {"on_timeout": "kill"}
+
+
+def test_get_lifecycle_on_timeout_takes_precedence_over_auto_pause():
+ assert get_lifecycle({"on_timeout": "kill"}, True) == {"on_timeout": "kill"}
+ assert get_lifecycle({"on_timeout": "pause"}, False) == {"on_timeout": "pause"}
+
+
+def test_get_lifecycle_falls_back_to_auto_pause_when_on_timeout_missing():
+ # partial lifecycle without on_timeout (possible at runtime despite typing).
+ assert get_lifecycle({"auto_resume": True}, True) == { # type: ignore[typeddict-item]
+ "on_timeout": "pause",
+ "auto_resume": True,
+ }
+
+
+def test_get_lifecycle_auto_pause_only_maps_to_on_timeout():
+ assert get_lifecycle(None, True) == {"on_timeout": "pause"}
+ assert get_lifecycle(None, False) == {"on_timeout": "kill"}
+
+
+def test_get_lifecycle_preserves_auto_resume_from_lifecycle():
+ assert get_lifecycle({"on_timeout": "pause", "auto_resume": True}, None) == {
+ "on_timeout": "pause",
+ "auto_resume": True,
+ }
+ assert get_lifecycle({"on_timeout": "pause", "auto_resume": False}, None) == {
+ "on_timeout": "pause",
+ "auto_resume": False,
+ }
+
+
+def test_get_lifecycle_omits_auto_resume_when_not_set_in_lifecycle():
+ # Lifecycle present but auto_resume not specified -> key omitted in result.
+ assert "auto_resume" not in get_lifecycle({"on_timeout": "pause"}, None)
+
+
+def test_get_lifecycle_omits_auto_resume_when_only_auto_pause_provided():
+ # auto_resume is preserved verbatim from lifecycle input; bare auto_pause
+ # does not introduce one.
+ assert "auto_resume" not in get_lifecycle(None, True)
+ assert "auto_resume" not in get_lifecycle(None, False)
+
+
+def test_get_lifecycle_raises_when_auto_resume_true_with_kill():
+ with pytest.raises(InvalidArgumentException):
+ get_lifecycle({"on_timeout": "kill", "auto_resume": True}, None)
+
+
+def test_get_lifecycle_raises_when_auto_resume_true_and_effective_is_kill():
+ # No on_timeout, auto_pause falsy -> effective kill -> error.
+ with pytest.raises(InvalidArgumentException):
+ get_lifecycle({"auto_resume": True}, None) # type: ignore[typeddict-item]
+ with pytest.raises(InvalidArgumentException):
+ get_lifecycle({"auto_resume": True}, False) # type: ignore[typeddict-item]
+
+
+def test_get_lifecycle_does_not_raise_when_auto_resume_true_with_auto_pause():
+ # Partial lifecycle with auto_resume=True and auto_pause=True is valid.
+ assert get_lifecycle(
+ {"auto_resume": True}, # type: ignore[typeddict-item]
+ True,
+ ) == {"on_timeout": "pause", "auto_resume": True}