databricks-sandbox
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDatabricks Sandbox
Databricks Sandbox
Databricks Sandbox is a serverless, isolated compute environment for humans and agents to run untrusted code. Drive it from code with the Databricks SDK, available in Python, Java, Go, and JavaScript. Lifecycle, file operations, and synchronous are available in all four SDKs; streaming is currently Python-only. The examples in this skill use the Python SDK.
execute_command_syncexecute_commandSDK reference (Python): https://databricks-sdk-py.readthedocs.io/en/latest/workspace/sandbox/sandbox.html
Product docs: https://docs.databricks.com/compute/serverless/sandbox
SDK user guide: https://docs.databricks.com/compute/serverless/sandbox-usage-guide
REST API reference: https://docs.databricks.com/api/sandbox/v1/sandbox
For the full per-method signature table, see references/sdk-reference.md.
Databricks Sandbox 是一个无服务器的隔离计算环境,供人类和 Agent 运行不受信任的代码。您可以通过 Databricks SDK 以编程方式驱动该环境;SDK 提供 Python、Java、Go 和 JavaScript 版本。所有四种 SDK 均支持生命周期管理、文件操作和同步 ;流式 目前仅支持 Python。本 skill 中的示例使用 Python SDK。
execute_command_syncexecute_commandSDK 参考(Python): https://databricks-sdk-py.readthedocs.io/en/latest/workspace/sandbox/sandbox.html
产品文档: https://docs.databricks.com/compute/serverless/sandbox
SDK 用户指南: https://docs.databricks.com/compute/serverless/sandbox-usage-guide
REST API 参考: https://docs.databricks.com/api/sandbox/v1/sandbox
有关完整的方法级签名表,请参阅 references/sdk-reference.md。
Environment Setup
环境设置
- Install the SDK with the sandbox extra: . The
uv pip install "databricks-sdk[sandbox]>=0.154.0"extra supplies the gRPC dependencies that streamingsandboxneeds (the plainexecute_commandpackage omits them); lifecycle, file operations, and unarydatabricks-sdkwork without the extra. 0.154.0 is the first release with the file-operation methods used below.execute_command_sync - Authentication, profiles, and are covered by the
~/.databrickscfgskill. The sandbox client authenticates like any otherdatabricks-core.WorkspaceClient - Your workspace must be in a supported region (see Features with limited regional availability) and have the Databricks Sandbox preview enabled on the workspace Previews page.
- 使用 sandbox extra 安装 SDK:。
uv pip install "databricks-sdk[sandbox]>=0.154.0"extra 提供流式sandbox所需的 gRPC 依赖项(普通execute_command包不包含这些依赖项);无需该 extra 即可使用生命周期管理、文件操作和一元databricks-sdk。0.154.0 是首个包含下文所用文件操作方法的版本。execute_command_sync - 身份验证、profiles 和 由
~/.databrickscfgskill 介绍。sandbox 客户端采用与任何其他databricks-core相同的身份验证方式。WorkspaceClient - 您的 workspace 必须位于受支持的区域(请参阅具有区域可用性限制的功能),并且 workspace 的 Previews 页面已启用 Databricks Sandbox 预览功能。
Resource Naming
资源命名
A sandbox's resource is . takes the bare ; every other call takes the full .
namesandboxes/<sandbox_id>create_sandboxsandbox_idnamesandbox 的资源 为 。 接受不含前缀的 ;其他所有调用均接受完整的 。
namesandboxes/<sandbox_id>create_sandboxsandbox_idnameLifecycle
生命周期
Lifecycle calls return before the transition finishes ( returns while , while ), so poll and wait for the target state before depending on it.
create_sandboxPENDINGstop_sandboxSTOPPINGget_sandbox(name).status.statepython
import time
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.sandbox import ComputeSpec, Sandbox, SandboxSpec, SandboxState
from google.protobuf.duration_pb2 import Duration
w = WorkspaceClient()
def wait_for_state(name: str, state: SandboxState, timeout: float = 300) -> Sandbox:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
sandbox = w.sandbox.get_sandbox(name=name)
if sandbox.status and sandbox.status.state == state:
return sandbox
time.sleep(2)
raise TimeoutError(f"{name} did not reach {state}")生命周期调用会在状态转换完成之前返回( 在 时返回, 在 时返回),因此应轮询 ,并等待达到目标状态后再继续使用该 sandbox。
create_sandboxPENDINGstop_sandboxSTOPPINGget_sandbox(name).status.statepython
import time
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.sandbox import ComputeSpec, Sandbox, SandboxSpec, SandboxState
from google.protobuf.duration_pb2 import Duration
w = WorkspaceClient()
def wait_for_state(name: str, state: SandboxState, timeout: float = 300) -> Sandbox:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
sandbox = w.sandbox.get_sandbox(name=name)
if sandbox.status and sandbox.status.state == state:
return sandbox
time.sleep(2)
raise TimeoutError(f"{name} did not reach {state}")Create returns while the sandbox is still PENDING; wait for RUNNING before use.
Create returns while the sandbox is still PENDING; wait for RUNNING before use.
A sandbox bills hourly while running; set inactivity_timeout so it auto-stops when
A sandbox bills hourly while running; set inactivity_timeout so it auto-stops when
idle.
idle.
Sandboxes can be updated with update_sandbox. The only accepted update paths
Sandboxes can be updated with update_sandbox. The only accepted update paths
are display_name and spec.compute.inactivity_timeout.
are display_name and spec.compute.inactivity_timeout.
created = w.sandbox.create_sandbox(
sandbox=Sandbox(spec=SandboxSpec(compute=ComputeSpec(inactivity_timeout=Duration(seconds=3600)))),
sandbox_id="my-sandbox",
)
name = created.name # "sandboxes/my-sandbox"
wait_for_state(name, SandboxState.SANDBOX_STATE_RUNNING)
created = w.sandbox.create_sandbox(
sandbox=Sandbox(spec=SandboxSpec(compute=ComputeSpec(inactivity_timeout=Duration(seconds=3600)))),
sandbox_id="my-sandbox",
)
name = created.name # "sandboxes/my-sandbox"
wait_for_state(name, SandboxState.SANDBOX_STATE_RUNNING)
Inspect
Inspect
sandbox = w.sandbox.get_sandbox(name=name)
for s in w.sandbox.list_sandboxes():
print(s.name)
sandbox = w.sandbox.get_sandbox(name=name)
for s in w.sandbox.list_sandboxes():
print(s.name)
Stop keeps the home directory; it returns while STOPPING, so wait for STOPPED
Stop keeps the home directory; it returns while STOPPING, so wait for STOPPED
before starting again.
before starting again.
w.sandbox.stop_sandbox(name=name)
wait_for_state(name, SandboxState.SANDBOX_STATE_STOPPED)
w.sandbox.start_sandbox(name=name)
wait_for_state(name, SandboxState.SANDBOX_STATE_RUNNING)
w.sandbox.stop_sandbox(name=name)
wait_for_state(name, SandboxState.SANDBOX_STATE_STOPPED)
w.sandbox.start_sandbox(name=name)
wait_for_state(name, SandboxState.SANDBOX_STATE_RUNNING)
Delete is terminal.
Delete is terminal.
w.sandbox.delete_sandbox(name=name)
Stopping preserves only the home directory (`/home/sandbox-agent`, which holds up to 100 GB); data written elsewhere does not survive a stop (up to 10 GB of non-home storage, cleared on stop). Deleting a sandbox is terminal.
A stopped sandbox (previously by `stop_sandbox()`) can be restarted by explicit `start_sandbox()` or by running `execute_command` / `execute_command_sync` against the sandbox. For sandbox creation or restart through `create_sandbox()` and `start_sandbox()`, wait for the sandbox status to reach Running before using it; `execute_command` / `execute_command_sync` auto-starts a stopped sandbox and wait for it to reach Running, and no sandbox status polling is required.w.sandbox.delete_sandbox(name=name)
停止 sandbox 时只会保留主目录(`/home/sandbox-agent`,最多可容纳 100 GB);写入其他位置的数据在停止后不会保留(非主目录存储最多 10 GB,并会在停止时清除)。删除 sandbox 是终态操作。
已通过 `stop_sandbox()` 停止的 sandbox 既可通过显式调用 `start_sandbox()` 重启,也可通过针对该 sandbox 运行 `execute_command` / `execute_command_sync` 重启。对于通过 `create_sandbox()` 和 `start_sandbox()` 创建或重启 sandbox,请等待 sandbox 状态达到 Running 后再使用;`execute_command` / `execute_command_sync` 会自动启动已停止的 sandbox 并等待其达到 Running,因此无需轮询 sandbox 状态。Running Commands
运行命令
Pick the mode by workload:
| Mode | Method | Use for |
|---|---|---|
| Synchronous | | Short commands where you only need the final stdout/stderr/exit code |
| Streaming | | Long-running or interactive commands where you consume output as it is produced |
Streaming (the handle) is currently available only in the Python SDK; is available in all SDKs.
execute_commandCommandProcessexecute_command_synccmd/bin/bash -c "..."args根据工作负载选择模式:
| 模式 | 方法 | 适用场景 |
|---|---|---|
| 同步 | | 只需最终 stdout/stderr/exit code 的短命令 |
| 流式 | | 长时间运行或交互式命令,需要在生成输出时实时获取输出 |
流式 ( 句柄)目前仅适用于 Python SDK; 适用于所有 SDK。
execute_commandCommandProcessexecute_command_synccmdargs/bin/bash -c "..."Synchronous
同步
python
from google.protobuf.duration_pb2 import Duration
resp = w.sandbox.execute_command_sync(
"sandboxes/my-sandbox",
"/bin/bash",
args=["-c", "echo hello && whoami"],
execution_timeout=Duration(seconds=30),
)
print(resp.status, resp.exit_code, resp.truncated, resp.stdout, resp.stderr)python
from google.protobuf.duration_pb2 import Duration
resp = w.sandbox.execute_command_sync(
"sandboxes/my-sandbox",
"/bin/bash",
args=["-c", "echo hello && whoami"],
execution_timeout=Duration(seconds=30),
)
print(resp.status, resp.exit_code, resp.truncated, resp.stdout, resp.stderr)Check resp.status for the terminal status: exit_code is unset when the command is
Check resp.status for the terminal status: exit_code is unset when the command is
killed (e.g. timed out) or fails to start. resp.truncated is True when the output
killed (e.g. timed out) or fails to start. resp.truncated is True when the output
hit the sync size cap - use execute_command (streaming) for large output.
hit the sync size cap - use execute_command (streaming) for large output.
undefinedundefinedStreaming
流式
execute_commandCommandProcessstdoutstderrwait()withproc.pidw.sandbox.execute_command_sync(name, "/bin/kill", args=[str(proc.pid)])python
with w.sandbox.execute_command(
"sandboxes/my-sandbox",
"/bin/bash",
args=["-c", "for i in 1 2 3; do echo line $i; sleep 1; done"],
) as proc:
for line in proc.stdout:
print(line, end="")
exit_code = proc.wait() # also available as proc.exit_code once finishedstdoutstderrStreamMode.PIPEStreamMode.DEVNULLStreamMode.STDOUTstderrtext=Falsebytesstrconnect_command(name, command_id)list_commands(parent="sandboxes/my-sandbox")在命令启动后, 会返回一个 句柄。迭代 / 以获取实时输出,并调用 获取退出码;将其用作上下文管理器,可在退出时释放客户端侧的流和读取线程。关闭句柄(或离开 代码块)只会关闭客户端侧资源——命令仍会继续在 sandbox 中运行。目前没有针对单个命令的取消 API;若要真正停止命令,请从 读取服务器端 PID,再使用单独的命令将其终止,例如 。
execute_commandCommandProcessstdoutstderrwait()withproc.pidw.sandbox.execute_command_sync(name, "/bin/kill", args=[str(proc.pid)])python
with w.sandbox.execute_command(
"sandboxes/my-sandbox",
"/bin/bash",
args=["-c", "for i in 1 2 3; do echo line $i; sleep 1; done"],
) as proc:
for line in proc.stdout:
print(line, end="")
exit_code = proc.wait() # also available as proc.exit_code once finishedstdoutstderrStreamMode.PIPEStreamMode.DEVNULLstderrStreamMode.STDOUTtext=Falsebytesstrconnect_command(name, command_id)list_commands(parent="sandboxes/my-sandbox")Files
文件
Manage the sandbox filesystem without a shell. All methods take (the sandbox ) plus a . Write under the sandbox user's home directory, (the only persisted, writable tree; itself is root-owned, and paths outside the home directory are cleared on stop).
parentnamepath/home/sandbox-agent/homepython
w.sandbox.create_directory(parent="sandboxes/my-sandbox", path="/home/sandbox-agent/data", parents=True)
for entry in w.sandbox.list_directory_contents(parent="sandboxes/my-sandbox", path="/home/sandbox-agent/data"):
print(entry.path)
w.sandbox.get_metadata(parent="sandboxes/my-sandbox", path="/home/sandbox-agent/data")
w.sandbox.rename_path(parent="sandboxes/my-sandbox", source="/home/sandbox-agent/a", destination="/home/sandbox-agent/b")
w.sandbox.delete_path(parent="sandboxes/my-sandbox", path="/home/sandbox-agent/b", recursive=True)Use the sandbox APIs to move data in and out; native API/SDK support for uploading and downloading file contents (local <-> sandbox) is not yet available.
execute_command无需 shell 即可管理 sandbox 文件系统。所有方法都接受 (sandbox 的 )和 。请在 sandbox 用户的主目录 下写入(这是唯一可持久化且可写的目录树; 本身归 root 用户所有,主目录之外的路径会在停止时清除)。
parentnamepath/home/sandbox-agent/homepython
w.sandbox.create_directory(parent="sandboxes/my-sandbox", path="/home/sandbox-agent/data", parents=True)
for entry in w.sandbox.list_directory_contents(parent="sandboxes/my-sandbox", path="/home/sandbox-agent/data"):
print(entry.path)
w.sandbox.get_metadata(parent="sandboxes/my-sandbox", path="/home/sandbox-agent/data")
w.sandbox.rename_path(parent="sandboxes/my-sandbox", source="/home/sandbox-agent/a", destination="/home/sandbox-agent/b")
w.sandbox.delete_path(parent="sandboxes/my-sandbox", path="/home/sandbox-agent/b", recursive=True)使用 sandbox 的 API 移入和移出数据;目前尚无原生 API/SDK 支持在本地与 sandbox 之间上传和下载文件内容。
execute_commandWhen to Use
使用场景
- Agent / untrusted code execution - run model-generated code off the host, in isolation.
- Ephemeral build/test environments - create, use, delete.
- Agent / 不受信任代码执行——在主机之外以隔离方式运行模型生成的代码。
- 临时构建/测试环境——创建、使用和删除环境。