# Sandboxes

Create sandboxes and run real commands in them, with stdin, exit codes, tags and a filesystem API, as local processes on the simulator's machine.

To test code that drives Modal sandboxes, create one and run commands in it: each command runs for real as a local process and returns its own output and exit code. Save this as `sandbox.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)
sb = modal.Sandbox.create(app=app, timeout=300)

p = sb.exec("sh", "-c", "echo out; echo err >&2; exit 3")
print(p.stdout.read().strip(), p.stderr.read().strip(), p.wait())

p = sb.exec("python3", "-c", "import sys; print(sys.stdin.read().upper())")
p.stdin.write("hello")
p.stdin.write_eof()
p.stdin.drain()
print(p.stdout.read().strip())

sb.set_tags({"team": "qa"})
print(sb.get_tags())
sb.terminate()
```

Put the `modal` version that [The Python your code runs on](https://www.rystic.ai/docs/simulators/modal/features/python-runtime.md) names in place of `<version>`. Then point the SDK at the simulator on `localhost` or `127.0.0.1` and run the file:

<!-- example: skip network -->
```bash
pip install -q "modal==<version>"
export MODAL_SERVER_URL="$RYSTIC_URL" MODAL_TOKEN_ID=ak-example MODAL_TOKEN_SECRET=as-example
python3 sandbox.py
# -> out err 3
# -> HELLO
# -> {'team': 'qa'}
```

## Run a sandbox's own command

A command given to `Sandbox.create` runs as the sandbox's own: `wait` returns when it ends, and a sandbox still running at its `timeout` raises `SandboxTimeoutError`. Save this as `command.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)

sb = modal.Sandbox.create("sh", "-c", "echo out; echo err >&2; exit 3", app=app, timeout=60)
sb.wait(raise_on_termination=False)
print(sb.returncode, sb.stdout.read().strip(), sb.stderr.read().strip())

slow = modal.Sandbox.create("sleep", "60", app=app, timeout=10)
try:
    slow.wait(raise_on_termination=False)
except modal.exception.SandboxTimeoutError as exc:
    print(type(exc).__name__)
```

<!-- example: skip network -->
```bash
python3 command.py
# -> 3 out err
# -> SandboxTimeoutError
```

## Follow a command's output

To watch a command while it runs, loop over its `stdout` or `stderr`: each line reaches your test when the command writes it. A sandbox's own command is followed the same way. Save this as `follow.py`:

```python
import time

import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)
sb = modal.Sandbox.create(app=app, timeout=300)

began = time.time()
p = sb.exec("sh", "-c", "for step in build test ship; do echo $step; sleep 2; done")
for line in p.stdout:
    print(round(time.time() - began), line.strip())
sb.terminate()

began = time.time()
own = modal.Sandbox.create("sh", "-c", "for step in lint pack; do echo $step >&2; sleep 2; done", app=app, timeout=60)
for line in own.stderr:
    print(round(time.time() - began), line.strip())
```

<!-- example: skip network -->
```bash
python3 follow.py
# -> 0 build
# -> 2 test
# -> 4 ship
# -> 0 lint
# -> 2 pack
```

Each number is the seconds since its command started. The first three lines are the `stdout` of the command `exec` ran, and the last two the `stderr` of the second sandbox's own command.

## Come back to a sandbox

`sb.stdin` writes to the command given to `Sandbox.create`. To come back to a sandbox, keep its id or create it with `name=`: `modal.Sandbox.from_id` and `modal.Sandbox.from_name` return it, and `exec` runs on the object either returns. A name belongs to one running sandbox of an app, and is free again when that sandbox ends. Save this as `named.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)

sb = modal.Sandbox.create("cat", app=app, timeout=60)
sb.stdin.write("to the command\n")
sb.stdin.write_eof()
sb.stdin.drain()
sb.wait()
print(sb.stdout.read().strip())

first = modal.Sandbox.create(app=app, timeout=300, name="worker")
try:
    modal.Sandbox.create(app=app, timeout=300, name="worker")
except modal.exception.AlreadyExistsError as exc:
    print(type(exc).__name__)

by_name = modal.Sandbox.from_name("ci-sandboxes", "worker")
by_id = modal.Sandbox.from_id(first.object_id)
print(by_name.object_id == first.object_id, by_name.exec("echo", "by name").stdout.read().strip())
print(by_id.exec("echo", "by id").stdout.read().strip())

first.terminate()
first.wait(raise_on_termination=False)
try:
    modal.Sandbox.from_name("ci-sandboxes", "worker")
except modal.exception.NotFoundError as exc:
    print(type(exc).__name__)
second = modal.Sandbox.create(app=app, timeout=300, name="worker")
print(second.object_id != first.object_id)
second.terminate()
```

<!-- example: skip network -->
```bash
python3 named.py
# -> to the command
# -> AlreadyExistsError
# -> True by name
# -> by id
# -> NotFoundError
# -> True
```

## Set variables and list sandboxes

`env=` on `Sandbox.create` and on `exec` reaches the command, and `Sandbox.list` returns an app's sandboxes. Save this as `listing.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)
made = [modal.Sandbox.create(app=app, timeout=300, env={"STAGE": "test"}) for _ in range(3)]

p = made[0].exec("sh", "-c", "echo $STAGE $RUN", env={"RUN": "42"})
print(p.stdout.read().strip())

listed = [sb.object_id for sb in modal.Sandbox.list(app_id=app.app_id)]
print(len(listed), sorted(listed) == sorted(sb.object_id for sb in made))
for sb in made:
    sb.terminate()
```

<!-- example: skip network -->
```bash
python3 listing.py
# -> test 42
# -> 3 True
```

`env=` and `secrets=` reach a sandbox created with `gpu=` too. Save this as `gpu_env.py`:

```python
import modal

app = modal.App.lookup("gpu-env", create_if_missing=True)
sb = modal.Sandbox.create(app=app, timeout=60, gpu="T4", env={"STAGE": "test"}, secrets=[modal.Secret.from_dict({"KEY": "k1"})])
p = sb.exec("sh", "-c", "echo $STAGE $KEY")
print(repr(p.stdout.read()))
sb.terminate()
```

<!-- example: skip network -->
```bash
python3 gpu_env.py
# -> 'test k1\n'
```

A variable an image sets with `Image.env` reaches the commands of a sandbox on that image, and `env=` on the sandbox replaces one of the same name. Save this as `image_env.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)
image = modal.Image.debian_slim().env({"STAGE": "test", "REGION": "eu"})
sb = modal.Sandbox.create(app=app, image=image, timeout=300, env={"REGION": "us"})
p = sb.exec("sh", "-c", "echo $STAGE $REGION")
print(p.stdout.read().strip())
sb.terminate()
```

<!-- example: skip network -->
```bash
python3 image_env.py
# -> test us
```

## Read and write a sandbox's files

`sandbox.filesystem` writes, reads and lists files, and raises the SDK's own error for a missing path. A fifo is listed as a file, as `pipe` is here. Save this as `files.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)
sb = modal.Sandbox.create(app=app, timeout=300)
fs = sb.filesystem

fs.write_text("hello\n", "/tmp/hello.txt")
sb.exec("sh", "-c", 'mkfifo "${TMPDIR:-/tmp}/pipe"').wait()
print(fs.read_text("/tmp/hello.txt").strip(), fs.stat("/tmp/hello.txt").size)
print(sorted((entry.name, entry.type.name) for entry in fs.list_files("/tmp")))
try:
    fs.read_text("/tmp/missing.txt")
except modal.exception.SandboxFilesystemNotFoundError as exc:
    print(type(exc).__name__)
sb.terminate()
```

<!-- example: skip network -->
```bash
python3 files.py
# -> hello 6
# -> [('hello.txt', 'FILE'), ('pipe', 'FILE')]
# -> SandboxFilesystemNotFoundError
```

## Start a sandbox from a snapshot

`snapshot_filesystem` returns an image, and a sandbox created from it starts with the first sandbox's files. Save this as `snapshot.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)

first = modal.Sandbox.create(app=app, timeout=300)
first.exec("sh", "-c", "echo kept > /root/marker").wait()
image = first.snapshot_filesystem()
first.terminate()

second = modal.Sandbox.create(app=app, image=image, timeout=300)
p = second.exec("cat", "/root/marker")
print(p.stdout.read().strip(), p.wait())
second.terminate()
```

<!-- example: skip network -->
```bash
python3 snapshot.py
# -> kept 0
```

Run this with isolation on, as a later section explains. Without it every sandbox shares the simulator's files, so the second sandbox reads `/root/marker` whether or not the snapshot has it.

## Mount an image at a path

`snapshot_directory` returns an image of one directory, and `mount_image` puts its files at a path of a running sandbox. Save this as `mounts.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)

first = modal.Sandbox.create(app=app, timeout=300)
first.exec("sh", "-c", 'mkdir -p "$HOME/data" && echo v1 > "$HOME/data/model.txt"').wait()
image = first.snapshot_directory("/root/data")
first.terminate()

second = modal.Sandbox.create(app=app, timeout=300)
second.exec("sh", "-c", 'mkdir -p "$HOME/models"').wait()
second.mount_image("/root/models", image)
print(second.exec("sh", "-c", 'cat "$HOME/models/model.txt"').stdout.read().strip())
second.unmount_image("/root/models")
print(second.exec("sh", "-c", 'cat "$HOME/models/model.txt"').stdout.read().strip())
try:
    second.unmount_image("/root/other")
except modal.exception.InvalidError as exc:
    print(type(exc).__name__)
second.terminate()
```

<!-- example: skip network -->
```bash
python3 mounts.py
# -> v1
# -> v1
# -> InvalidError
```

The commands name their files under `$HOME`, which is `/root` in a sandbox, so the example runs with isolation on or off. Unmounting a path with no mount raises `InvalidError`, as the last line shows.

**Differs from Modal:** after `unmount_image` the image's files stay at the path, as the second line shows. On Modal the path shows what was there before the mount.

## Give each sandbox a filesystem of its own

How far a sandbox is kept apart depends on how the simulator was started. Its compute view says which:

```bash
curl -s "$RYSTIC_URL/_rystic/inspect?view=compute" | jq -c '{isolated, live}'
# -> {"isolated":false,"live":0}
```

| `isolated` | What a command sees |
|---|---|
| `false` | The simulator's own files and network, shared by every sandbox: a file one command writes at `/data/x` is there for all of them, and neither `sandbox.filesystem` nor a snapshot has it |
| `true` | A root and a network of its own for each sandbox, with the network reaching only the simulator. What a command writes there, `sandbox.filesystem` reads and a snapshot has |

[The Python your code runs on](https://www.rystic.ai/docs/simulators/modal/features/python-runtime.md) gives the Docker flags that turn isolation on. A plain `docker run` leaves it off, so tests that depend on one sandbox not seeing another's files need the flags.

## What a sandbox runs on

A command needs Linux, and runs with the programs the simulator's machine has: in the Docker image, a small Debian with Python. The sandbox's image is accepted and not built, so a package the image asks for is not there unless the simulator's Python already has it. Save this as `image.py`:

```python
import modal

app = modal.App.lookup("ci-sandboxes", create_if_missing=True)
image = modal.Image.debian_slim().pip_install("requests")
sb = modal.Sandbox.create(app=app, image=image, timeout=300)

p = sb.exec("python3", "-c", "import requests")
print(p.wait())
sb.terminate()
```

On the simulator's Docker image, whose Python has no `requests`, the import fails:

<!-- example: skip network -->
```bash
python3 image.py
# -> 1
```

**Differs from Modal:** no image is built, and a sandbox created with `gpu=` gets no GPU.

[Limitations](https://www.rystic.ai/docs/simulators/modal.md#limitations) lists what does not work, among them a background process that ends with its command.

---

Source: https://www.rystic.ai/docs/simulators/modal/features/sandboxes · Markdown: https://www.rystic.ai/docs/simulators/modal/features/sandboxes.md
