# Sandboxes

> Create a sandbox, run commands and stream their output, copy files in and out, read logs, and terminate it keeping the files you need.

Source: https://docs.compute.dev.ddcdragon.com/guides/sandboxes/

Guides show how to do one task at a time, with the `cere` CLI and the Python SDK side by side. For why sandboxes
work the way they do, read [Sandboxes](https://docs.compute.dev.ddcdragon.com/concepts/sandboxes/) in Concepts.

A sandbox is a gVisor container on a node of the cluster. You create it from an image, run commands in it, move
files in and out, and terminate it. The examples assume you are signed in ([Signing in](https://docs.compute.dev.ddcdragon.com/guides/signing-in/)).

## Create a sandbox

`cere sandbox create` starts a sandbox from an image and waits until it runs; `Sandbox.create` does the same.

**CLI**

```sh
cere sandbox create --image python:3.12-slim --timeout 300
```

```
sb-01m89qnegv0g7cq352t9ck4qvm placed on node d4007f488e29; starting python:3.12-slim ...
running on node d4007f488e29 (started in 173 ms)
sb-01m89qnegv0g7cq352t9ck4qvm
```

The ID goes to standard output and the progress lines to standard error. In a script, `-q` prints only the ID:

```sh
ID=$(cere sandbox create --image python:3.12-slim --timeout 300 -q)
```

The rest of this page uses `$ID`. End the first sandbox with `cere sandbox terminate <id>`
([below](#terminate-a-sandbox-and-keep-files)), or let its timeout end it.

**Python**

```python
import cere

sb = cere.Sandbox.create(image="python:3.12-slim", timeout=300)
print(sb.object_id, sb.status)
```

```
sb-01m89qq2ep7kdfw72dvzxs1mkm running
```

`Sandbox.create` waits until the sandbox runs (`wait=False` returns while it is still `starting`).

The sandbox runs `sleep infinity` until its timeout or until you terminate it, and its bucket pays for it while
it runs. The image comes from a public registry (`docker.io`, `ghcr.io`, `quay.io` or `public.ecr.aws`) and needs
`sh` and `sleep`: the default command is `sleep infinity`, and file copies run through `sh`.

## Set options at create

Size, timeouts, environment, working directory and labels are set when the sandbox is created.

**CLI**

```sh
APP=$(cere sandbox create --image python:3.12-slim \
  --cpu 0.5 --memory 512 --timeout 300 --idle-timeout 120 \
  --env MODE=demo --workdir /workspace/app --label app=docs -q)
cere sandbox exec $APP -- sh -c 'echo "$MODE in $(pwd)"'
```

```
demo in /workspace/app
```

**Python**

```python
app = cere.Sandbox.create(
    image="python:3.12-slim",
    cpu=0.5, memory=512,            # vCPU; MiB
    timeout=300, idle_timeout=120,  # seconds
    env={"MODE": "demo"},
    workdir="/workspace/app",
    labels={"app": "docs"},
)
print(app.exec("sh", "-c", 'echo "$MODE in $(pwd)"').stdout.read(), end="")
```

```
demo in /workspace/app
```

| CLI flag | Python | Default | What it sets |
|---|---|---|---|
| `--image` | `image=` | required | The image, from a public registry |
| `--cpu` | `cpu=` | 1 | vCPUs reserved; also the CPU quota |
| `--memory` | `memory=` | 1024 | MiB reserved, at least 128; also the memory limit |
| `--pids` | `pids=` | 2048 | Process limit |
| `--timeout` | `timeout=` | 600 | Seconds (CLI: or a duration, `10m`) until the sandbox is terminated |
| `--idle-timeout` | `idle_timeout=` | off | Terminate after this long with no exec or file call |
| `--env K=V` | `env={}` | none | Environment variables. Not secret: see [Egress and secrets](https://docs.compute.dev.ddcdragon.com/guides/egress-and-secrets/) for credentials |
| `--workdir` | `workdir=` | `/workspace` | Working directory of the main process and of exec |
| `--label k=v` | `labels={}` | none | Labels to find the sandbox by; the `cere.` prefix is reserved |
| `--allow RULE` | `egress=[cere.Allow(...)]` | none | Hosts the sandbox may reach ([Egress and secrets](https://docs.compute.dev.ddcdragon.com/guides/egress-and-secrets/)) |
| `-- command...` | positional arguments | `sleep infinity` | The main process |
| `--wait-timeout` | `wait_timeout=` | 10m; 600 s | How long to wait for the sandbox to start, image pull included |

On devnet nodes that already run requests and limits, the quota and the memory limit can be higher than the
reservation; see [Resources and billing](https://docs.compute.dev.ddcdragon.com/concepts/resources-and-billing/).

Limits on size and time are in [Resources and billing](https://docs.compute.dev.ddcdragon.com/guides/resources-and-billing/).

## Give the sandbox a main command

A command after `--` (CLI) or positional arguments (Python) replace `sleep infinity`. The sandbox ends when that
process exits.

**CLI**

```sh
TICK=$(cere sandbox create --image busybox:1.36 --timeout 120 -q \
  -- sh -c 'for i in 1 2 3; do echo "tick $i"; sleep 2; done')
cere sandbox logs $TICK
```

```
tick 1
tick 2
tick 3
```

**Python**

```python
tick = cere.Sandbox.create("sh", "-c", 'for i in 1 2 3; do echo "tick $i"; sleep 2; done',
                           image="busybox:1.36", timeout=120)
for stream, text in tick.logs():
    print(stream, text, end="")
```

```
stdout tick 1
stdout tick 2
stdout tick 3
```

## List and find sandboxes

List the bucket's sandboxes, newest first, filtered by status and labels; get one by its ID.

**CLI**

```sh
cere sandbox list --label app=docs --status running
cere sandbox get $APP
```

```
ID                             STATUS   IMAGE             NODE          CREATED  CPU-S  EXIT  LABELS
sb-01m89qnh4w9k76n9mxmzf9e2t6  running  python:3.12-slim  9f97fd7fc247  7s ago   0.00   -     app=docs
id         sb-01m89qnh4w9k76n9mxmzf9e2t6
status     running
bucket     <bucket-id>
node       9f97fd7fc247038ffa7944d5fa8fbd23e85c9002360a1bfcda58683faffec8cc
image      python:3.12-slim
command    sleep infinity
resources  cpu 0.5, memory 512 MiB, pids 2048
timeout    300s (idle 120s)
egress     -
env keys   MODE
labels     app=docs
created    2026-11-25T16:12:22Z
started    2026-11-25T16:12:22Z
startup    192 ms
ended      -
exit       -
retained   -
billed     0.5 vCPU × 8.1 s = 4.1 CPU-s (measured 0.1), 0.5 GiB × 8.1 s = 4.1 GiB-s (measured 0.1)
usage      wall 8.1s, cpu 0.10s, memory peak 24 MiB, 0.08 GiB-s, net out 0 B in 628 B, disk peak 0.0 MiB
```

`--label` repeats (all must match); `--status` is `starting`, `running`, `terminated`, `failed` or `unknown`;
`--limit N` (default 100) or `--all`.

**Python**

```python
for s in cere.Sandbox.list(label="app=docs", status="running"):
    print(s.object_id, s.status, s.data["labels"])

found = cere.Sandbox.from_id("sb-...")  # an ID from the list
print(found.status, found.data["resources"], found.data["workdir"])
```

```
sb-01m89qq3p4kjjwtbpxxzghc595 running {'app': 'docs'}
running {'cpu': 0.5, 'memory_mib': 512, 'pids': 2048, 'disk_mib': 0, 'gpu': None} /workspace/app
```

`label` takes `"k=v"`, a list of them or a dict (all must match); `limit` defaults to 100 (`None` for all).
`found.data` is the sandbox as the API last reported it; `found.refresh()` reads it again.

## Run a command

`exec` runs a command in a running sandbox and returns its output and exit code.

**CLI**

```sh
cere sandbox exec $ID -- python -c "print(6 * 7)"
cere sandbox exec $ID -- sh -c 'echo "to stderr" >&2; exit 3'; echo "exit code: $?"
echo 'print("from stdin")' | cere sandbox exec $ID --stdin -- python -
cere sandbox exec $ID --workdir /tmp --env GREETING=hello -- sh -c 'echo "$GREETING from $(pwd)"'
```

```
42
to stderr
exit code: 3
from stdin
hello from /tmp
```

`cere sandbox exec` writes the command's stdout and stderr to its own and exits with the command's exit code.

**Python**

```python
p = sb.exec("python", "-c", "print(6 * 7)")
print(p.stdout.read(), end="")

p = sb.exec("sh", "-c", 'echo "to stderr" >&2; exit 3')
print(p.wait(), repr(p.stderr.read()))

p = sb.exec("python", "-", stdin='print("from stdin")')
print(p.stdout.read(), end="")

p = sb.exec("sh", "-c", 'echo "$GREETING from $(pwd)"', workdir="/tmp", env={"GREETING": "hello"})
print(p.stdout.read(), end="")
```

```
42
3 'to stderr\n'
from stdin
hello from /tmp
```

`p.stdout.read()` and `p.stderr.read()` return everything once the command has ended; `p.wait()` returns the
exit code, also kept in `p.returncode`.

Each exec has a timeout: 600 seconds by default, at most 3600. When it passes, the call returns with exit code 124:

**CLI**

```sh
cere sandbox exec $ID --timeout 2 -- sleep 10; echo "exit code: $?"
```

```
cere: the command did not finish within 2 s and was stopped
exit code: 124
```

**Python**

```python
p = sb.exec("sleep", "10", timeout=2)
print(p.wait(), p.timed_out)
```

```
124 True
```

:::caution
The call returns, but the command itself keeps running in the sandbox until the sandbox ends: after the example
above, `sleep 10` is still in the sandbox's process list. Give long commands a timeout of their own (for example
`timeout 60 <command>` in the image's shell), or terminate the sandbox.
:::

:::note
A sandbox takes at most 8 exec, file and log calls at once. One more is refused with `429 too_many_requests`
("already has 8 exec, file and log calls in flight"); retry it when one ends.
:::

## Stream output

Output arrives while the command runs. The CLI prints it as it comes; in Python, iterate over `p.stdout` for
lines as they arrive.

**CLI**

```sh
cere sandbox exec $ID -- python -u -c "import time
for i in range(3):
    print('step', i); time.sleep(1)" | while read -r line; do echo "$(date +%T) $line"; done
```

```
19:12:35 step 0
19:12:36 step 1
19:12:37 step 2
```

**Python**

```python
import time

p = sb.exec("python", "-u", "-c", "import time\nfor i in range(3):\n    print('step', i); time.sleep(1)")
for line in p.stdout:
    print(time.strftime("%H:%M:%S"), line, end="")
print("exit code", p.wait(), "in", p.duration_ms, "ms")
```

```
19:13:27 step 0
19:13:28 step 1
19:13:29 step 2
exit code 0 in 3037 ms
```

`p.iter_output()` yields `("stdout" | "stderr", text)` chunks in the order they arrive, for both streams:

```python
p = sb.exec("sh", "-c", "echo out; echo err >&2; echo out again")
for stream, chunk in p.iter_output():
    print(stream, repr(chunk))
```

```
stdout 'out\n'
stdout 'out again\n'
stderr 'err\n'
```

:::tip
Python buffers its output when it does not write to a terminal, so a Python program in a sandbox prints in one
burst at the end unless you run it with `python -u` (or set `PYTHONUNBUFFERED=1`, or `flush=True`).
:::

## Copy files in and out

`put` writes a local file into the sandbox (parent directories are created) and `get-file` reads one out.

**CLI**

```sh
printf 'name,score\nada,3\nbob,5\n' > data.csv
cere sandbox put $ID data.csv /workspace/in/data.csv
cere sandbox exec $ID -- sh -c 'wc -l < /workspace/in/data.csv > /workspace/out.txt'
cere sandbox get-file $ID /workspace/out.txt
cere sandbox get-file $ID /workspace/out.txt out.txt
echo "hello" | cere sandbox put $ID - /workspace/hello.txt
```

```
wrote data.csv (23 B) to sb-01m89qng3kr30x9ba5xj2j80en:/workspace/in/data.csv
3
wrote sb-01m89qng3kr30x9ba5xj2j80en:/workspace/out.txt (2 B) to out.txt
wrote - (6 B) to sb-01m89qng3kr30x9ba5xj2j80en:/workspace/hello.txt
```

Without a local path `get-file` writes to standard output; `put` with `-` reads standard input.

**Python**

```python
sb.write_file("/workspace/in/data.csv", "name,score\nada,3\nbob,5\n")   # str or bytes
sb.exec("sh", "-c", "wc -l < /workspace/in/data.csv > /workspace/out.txt").wait()
print(sb.read_file("/workspace/out.txt"))                                 # bytes

with sb.open("/workspace/notes.txt", "w") as f:                          # text, written on close
    f.write("written with open()\n")
print(sb.read_file("/workspace/notes.txt"))
```

```
b'3\n'
b'written with open()\n'
```

A file is at most 16 MiB each way. A larger one, or a missing one, is refused:

**CLI**

```sh
head -c 17000000 /dev/zero > big.bin
cere sandbox put $ID big.bin /workspace/big.bin
cere sandbox get-file $ID /workspace/missing.txt
```

```
error: 413 too_large: file is larger than the limit
error: 404 file_not_found: no file /workspace/missing.txt in sandbox sb-01m89qng3kr30x9ba5xj2j80en
```

**Python**

```python
try:
    sb.read_file("/workspace/missing.txt")
except cere.CereError as e:
    print(e.status, e.code)
```

```
404 file_not_found
```

`write_file` does not check the size first: a write over 16 MiB is cut off by the API and fails with a connection
error (`urllib.error.URLError`), not a `CereError`. Check `len(data)` before you write.

## Read the main process's logs

`logs` streams the stdout and stderr of the sandbox's main process (the command it was created with) until it
ends. The example in [Give the sandbox a main command](#give-the-sandbox-a-main-command) reads them. Exec output is
not in the logs: it goes to the caller of `exec`.

Logs stay readable for 10 minutes after the sandbox ends. To keep output longer, write it to a file and retain
it ([below](#terminate-a-sandbox-and-keep-files)).

## Terminate a sandbox and keep files

Terminate a sandbox when you are done; billing stops when it stops. `--retain` (`retain=`) keeps files readable
after the end, and `--reason` (`reason=`) is recorded in its exit reason.

**CLI**

```sh
cere sandbox exec $ID -- sh -c 'echo "{\"answer\": 42}" > /workspace/result.json'
cere sandbox terminate $ID --retain /workspace/result.json,/workspace/out.txt --reason "docs example done"
```

```
sb-01m89qng3kr30x9ba5xj2j80en terminated: terminated by API: docs example done
billed 1.0 vCPU × 25.5 s = 25.5 CPU-s (measured 0.5), 1.0 GiB × 25.5 s = 25.5 GiB-s (measured 0.3)
usage: wall 25.5s, cpu 0.54s, memory peak 18 MiB, 0.32 GiB-s, net out 210 B in 1.0 KiB, disk peak 0.0 MiB
retained: /workspace/out.txt, /workspace/result.json
```

**Python**

```python
sb.exec("sh", "-c", 'echo "{\\"answer\\": 42}" > /workspace/result.json').wait()
sb.terminate(retain=["/workspace/result.json"], reason="docs example done")
print(sb.status, sb.exit_reason, sb.data["retained"])
```

```
terminated terminated by API: docs example done ['/workspace/result.json']
```

Read a retained file after the end the same way as before it, from any machine signed in to the bucket:

**CLI**

```sh
cere sandbox get-file $ID /workspace/result.json
cere sandbox get-file $ID /workspace/in/data.csv
```

```
{"answer": 42}
error: 410 file_gone: sandbox sb-01m89qng3kr30x9ba5xj2j80en has ended and /workspace/in/data.csv was not retained
```

**Python**

```python
sb = cere.Sandbox.from_id("sb-...")
print(sb.read_file("/workspace/result.json"))
try:
    sb.read_file("/workspace/in/data.csv")
except cere.CereError as e:
    print(e.status, e.code)
```

```
b'{"answer": 42}\n'
410 file_gone
```

| Retained files | |
|---|---|
| Size | Each file up to 16 MiB; one terminate keeps its files together within 64 MiB per bucket on the node, or keeps none |
| How long | 24 hours after the sandbox ends |
| A path that is missing or too large | Skipped; the terminate still succeeds, and `retained` lists what was kept |
| A file that was not retained | `410 file_gone`, with the reason when the budget was the cause; a sandbox that kept no files answers `404 not_found` once its logs are gone |

Terminating a sandbox that has already ended returns it unchanged.

## Wait for a sandbox to end

In Python, `sb.wait()` blocks until the sandbox ends (its main command exits, it times out or is terminated) and
returns its exit code; `sb.poll()` returns `None` while it runs. From the CLI, read its state with
`cere sandbox get`.

**CLI**

```sh
JOB=$(cere sandbox create --image busybox:1.36 --timeout 120 -q -- sh -c 'sleep 5; exit 7')
cere sandbox get $JOB | grep -E '^(status|exit)'
sleep 10
cere sandbox get $JOB | grep -E '^(status|exit)'
```

```
status     running
exit       -
status     terminated
exit       exited with code 7 (exit code 7)
```

**Python**

```python
job = cere.Sandbox.create("sh", "-c", "sleep 5; exit 7", image="busybox:1.36", timeout=120)
print(job.poll())
print(job.wait(), job.status, job.exit_reason)
```

```
None
7 terminated exited with code 7
```

## States and exit reasons

`cere sandbox get` shows a sandbox's `status` (`starting`, `running`, `terminated`, `failed`, `unknown`) and, once it
has ended, its exit reason, such as `exited with code 7`, `timeout (30s)` or `terminated by API: <reason>`. Every
status and exit reason is listed in [Sandboxes: lifecycle](https://docs.compute.dev.ddcdragon.com/concepts/sandboxes/#lifecycle).

## Related

- [Next: Resources and billing](https://docs.compute.dev.ddcdragon.com/guides/resources-and-billing/)
- [Sandboxes](https://docs.compute.dev.ddcdragon.com/concepts/sandboxes/): lifecycle, isolation, images, limits
- [CLI](https://docs.compute.dev.ddcdragon.com/reference/cli/): every `cere sandbox` flag
- [Python SDK](https://docs.compute.dev.ddcdragon.com/reference/python-sdk/): `cere.Sandbox` and `cere.Process`
