# Sandbox pools

A SandboxPool keeps warm capacity for untrusted code, such as each agent run
or build, under gVisor or Kata. A container in the pool starts without waiting
for a new machine, and a sandbox in it can sleep while it is idle and wake on
its next request. You can use a pool in two ways:

- Run a Pod in it. Add one annotation to a Pod, or to a Job's Pod template.
  Otherwise, the Pod is an ordinary Pod.
- Create a sandbox in it. A sandbox is a container that you create through
  the pool's `sandboxes` API. A sandbox can stop, and start again from a snapshot
  of its files, or under gVisor of its processes' memory too. A Durable Object
  uses sandboxes through
  [`@kite/containers`](/docs/durable-object-containers/).

## Create a pool

```yaml
apiVersion: kiteplane.dev/v1alpha1
kind: SandboxPool
metadata:
  name: builders
  namespace: ci
spec:
  runtimeClassName: gvisor
  defaultSandboxSize: { cpu: "1", memory: 2Gi }
  capacity:
    max: { cpu: "32", memory: 64Gi }
    minWarmSlots: 2
```

Set `capacity.max` to the total CPU and memory the pool can reserve across
all nodes. Running workloads, unused warm capacity, and RuntimeClass overhead
share that limit. A sleeping sandbox frees its compute capacity.

Kite reuses capacity where a workload fits and requests room for the workload
when it needs more. If your pool reaches either limit, new work waits. Check
`status.capacityLimited` on the pool. A workload too large to fit even in an
empty pool is refused at creation. Lowering the limit leaves running workloads
in place and prevents new reservations until there is room.

Set `minWarmSlots` to the number of default-sized workloads you want capacity
for after an idle period. Running workloads can use that capacity. The default
is zero, so an idle pool can release all its reservations. Starting or restoring
a sandbox still takes time once capacity is ready.

### Fixed reservation sizes

For a pool with fixed-size reservations, use `reservation`, `container` and
`minReservations` in place of `capacity` and `defaultSandboxSize`.

| Field                | What it does                                                                                                                                                       | Default |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- |
| `runtimeClassName`   | The RuntimeClass that each Pod and sandbox in the pool runs under. You cannot change it, add it or remove it: create another pool for another RuntimeClass.        | None    |
| `reservation`        | The CPU and memory that each reservation Pod requests on a node. Pods and sandboxes in the pool run inside reservation Pods.                                       | None    |
| `container`          | Optional. Admission writes its values into each container that requests no CPU or no memory, as a LimitRange default does. A sandbox with `image` books all of it. | None    |
| `minReservations`    | The reservation Pods that the pool keeps running when nothing uses it. It adds more when its Pods and sandboxes need them.                                         | `1`     |
| `serviceAccountName` | Optional. The ServiceAccount that the pool's sandboxes run as. See [Give a sandbox a token](#give-a-sandbox-a-token).                                              | None    |

A pool without `spec.container` runs only the Pods and the sandboxes with a
`spec` that request both CPU and memory.

`kubectl get sandboxpools` shows how many reservations run, how many sandboxes
and Pods use the pool, and how many more sandboxes fit.

### How a Pod books a reservation

When a Pod joins the pool, it books part of one reservation, and the pool sets
that part aside for the Pod. A Pod books its CPU request, the larger of its
memory request and its memory limit, and the RuntimeClass's overhead. Pods of
different sizes can share a reservation.

Each Pod and each sandbox runs in a pod sandbox of its own, under its
reservation Pod, with the pool's RuntimeClass. A sandbox is as isolated as
that RuntimeClass makes it: gVisor and Kata give each one a kernel of its own,
and runc shares the node's kernel.

### Change the reservation size

When you change `spec.reservation`:

- New Pods and sandboxes go only to reservation Pods of the new size.
- The pool deletes each reservation Pod of the old size that nothing runs in,
  and starts one of the new size in its place.
- A Pod or sandbox that is still running keeps its reservation Pod until it
  ends.
- Right after the change, a new Pod or sandbox may wait for a reservation Pod
  of the new size to start.

### Memory cap

Each Pod's or sandbox's memory cap is the memory that it books, plus the
RuntimeClass's overhead. Kite stops a Pod or sandbox that stays above its cap
for 10 seconds, with the reason `OverMemory`. The others in its reservation
keep running.

:::caution
Under Kata, the cap also covers each Pod's or sandbox's VM and the processes on
the node that run the VM. So the API rejects every Pod and sandbox in a pool
whose RuntimeClass uses Kata and sets no `overhead.podFixed.memory`.
[Sandbox a pod](/docs/sandboxed-runtimes/#create-the-runtimeclass) gives the
overhead for Kata.
:::

## Run a Pod or a Job in a pool

Add the annotation `kiteplane.dev/sandbox-pool` with the name of a pool in
the Pod's namespace:

```yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: build
  namespace: ci
spec:
  template:
    metadata:
      annotations:
        kiteplane.dev/sandbox-pool: builders
    spec:
      restartPolicy: Never
      containers:
        - name: build
          image: golang:1.25
          command: ["go", "build", "./..."]
          resources:
            requests: { cpu: "1", memory: 2Gi }
```

The Pod runs in one of the pool's reservations that has room for what the Pod
books. Volumes, init containers, sidecars, environment variables from Secrets,
logs and exec work as they do for any Pod. When no reservation has room, the
Pod stays Pending until the pool adds a reservation.

The API rejects a Pod in a pool when the Pod:

| Rule                                                                                        | Example                                                                                                                                         |
| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| Requests more CPU or memory than fits in one reservation with the RuntimeClass's overhead   | —                                                                                                                                               |
| Requests no CPU or no memory, and the pool has no default for that resource                 | —                                                                                                                                               |
| Sets a RuntimeClass other than the pool's                                                   | —                                                                                                                                               |
| Uses the host's namespaces or files                                                         | `hostNetwork`, `hostPID`, `hostIPC` or a `hostPath` volume                                                                                      |
| Does not meet the baseline Pod Security Standard, unless the RuntimeClass is gVisor or Kata | A privileged container, a capability that is not on the standard's short list of allowed additions, an `Unconfined` seccomp or AppArmor profile |
| Sets where it runs                                                                          | `nodeName` or another `schedulerName`                                                                                                           |

The same rules apply to an ephemeral container that you add to the Pod.

:::note
A Pod that sets no RuntimeClass gets the pool's before mutating admission
policies and webhooks run. So a policy or webhook that only fills in a missing
RuntimeClass leaves a pool Pod alone, and one that sets the RuntimeClass of
every Pod makes the API refuse a pool Pod.
:::

A Pod in a pool differs from a Pod outside a pool:

- A ResourceQuota counts the Pod in `pods`, but does not count its CPU and
  memory, because the pool's reservation Pod already counts them. A quota
  whose scopes leave out the reservation Pods, such as `Terminating`, counts
  the Pod's CPU and memory as it does for any Pod.
- If the Pod's node selector, affinity or tolerations rule out every node
  that runs one of the pool's reservations, the Pod stays Pending. Its
  `FailedScheduling` event says why.
- A resize cannot raise what the Pod books above what it booked when it was
  placed in a reservation.
- If its reservation Pod is deleted, for example when you drain the node, the
  Pod fails with the reason `ReservationDeleted` and the condition
  `DisruptionTarget`. A Job whose `podFailurePolicy` ignores disruptions
  starts a new Pod.
- The Pod has no snapshots and no idle timeout, which only sandboxes have.

## Create a sandbox

Create a sandbox through the pool's `sandboxes` subresource:

```sh
kubectl create --raw \
  /apis/kiteplane.dev/v1alpha1/namespaces/ci/sandboxpools/builders/sandboxes \
  -f - <<'EOF'
{
  "image": "python:3.12-slim",
  "command": ["python", "-m", "http.server", "8080"],
  "idleTimeoutSeconds": 600
}
EOF
```

| Request                    | What it does                                                                     | RBAC                                      |
| -------------------------- | -------------------------------------------------------------------------------- | ----------------------------------------- |
| `POST sandboxes`           | Creates a sandbox                                                                | `create` on `sandboxpools/sandboxes`      |
| `GET sandboxes?id=<id>`    | Returns the sandbox and its phase: Pending, Running, Sleeping, Stopped or Failed | `get` on `sandboxpools/sandboxes`         |
| `GET sandboxes`            | Lists the pool's sandboxes                                                       | `get` on `sandboxpools/sandboxes`         |
| `PATCH sandboxes?id=<id>`  | Changes `idleTimeoutSeconds`. `null` removes it                                  | `patch` on `sandboxpools/sandboxes`       |
| `DELETE sandboxes?id=<id>` | Stops the sandbox and deletes it                                                 | `delete` on `sandboxpools/sandboxes`      |
| `GET log/<id>`             | Returns a container's log, as a Pod's `log` does                                 | `get` on `sandboxpools/log`               |
| `GET exec/<id>`            | Runs a command in a container, as a Pod's `exec` does                            | `create` and `get` on `sandboxpools/exec` |

The body of `POST sandboxes` takes these fields. The response contains the
sandbox's `id`.

| Field                          | What it does                                                                                                                          |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `image`                        | Runs one container from this image. The sandbox books the pool's default CPU and memory. An image sandbox requires both.              |
| `command`, `args`, `env`       | The container gets them exactly as you send them, without the `$(NAME)` expansion that a Pod's spec has.                              |
| `spec`                         | A Pod's `spec`, in place of the four fields above. See [Run a Pod spec in a sandbox](#run-a-pod-spec-in-a-sandbox).                   |
| `snapshot`                     | The id of a snapshot to start from. See [Snapshots](#snapshots).                                                                      |
| `idleTimeoutSeconds`, `onIdle` | When the sandbox stops or sleeps without requests. See [Idle sandboxes](#idle-sandboxes).                                             |
| `egress`                       | The hosts outside the cluster that the sandbox can connect to. See [Limit where a sandbox connects](#limit-where-a-sandbox-connects). |

### Run a Pod spec in a sandbox

A sandbox's `spec` is a Pod's `spec`, with init containers, sidecars, volumes,
and env from Secrets and ConfigMaps. This sandbox's init container writes a file
to an `emptyDir` volume, and its main container reads it, with `TOKEN` from
the Secret `notebook-token`:

```sh
kubectl create --raw \
  /apis/kiteplane.dev/v1alpha1/namespaces/ci/sandboxpools/builders/sandboxes \
  -f - <<'EOF'
{
  "spec": {
    "volumes": [{ "name": "work", "emptyDir": {} }],
    "initContainers": [{
      "name": "setup",
      "image": "busybox:1.37",
      "command": ["sh", "-c", "echo ready > /work/setup"],
      "volumeMounts": [{ "name": "work", "mountPath": "/work" }]
    }],
    "containers": [{
      "name": "notebook",
      "image": "python:3.12-slim",
      "command": ["sh", "-c", "cat /work/setup && exec python -m http.server 8080"],
      "env": [{
        "name": "TOKEN",
        "valueFrom": { "secretKeyRef": { "name": "notebook-token", "key": "token" } }
      }],
      "volumeMounts": [{ "name": "work", "mountPath": "/work" }]
    }]
  },
  "idleTimeoutSeconds": 600
}
EOF
```

A sandbox with a `spec` books what it requests, as a Pod in the pool does. The
pool's default sandbox size fills in each request that the spec leaves out.

`GET sandboxes?id=<id>` returns:

| Field                          | What it contains                                                                                         |
| ------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `spec`                         | The spec, with the requests that the pool filled in                                                      |
| `cpu`, `memory`                | What the sandbox books                                                                                   |
| `containers`, `initContainers` | Each container's `state` (`waiting`, `running` or `terminated`), `reason`, `exitCode` and `restartCount` |
| `phase`                        | One of the phases below                                                                                  |

| Phase      | When                                                                        |
| ---------- | --------------------------------------------------------------------------- |
| `Running`  | One of its app containers runs                                              |
| `Stopped`  | Each of its app containers has exited with code 0                           |
| `Failed`   | One app container has exited with another code, or a container cannot start |
| `Sleeping` | It is idle with `"onIdle": "Sleep"`. See [Idle sandboxes](#idle-sandboxes)  |

A sandbox with a sidecar ends once Kite has stopped the sidecar, after its app
containers exit.

Kite records an Event on the pool when a sandbox ends. Anyone who can read
Events in the namespace can see it for an hour, even after the sandbox and its
log are deleted.

| The sandbox                    | Event                                                                           |
| ------------------------------ | ------------------------------------------------------------------------------- |
| Fails                          | Warning, with its reason, such as `OOMKilled`, its message and its memory limit |
| Stops                          | Normal                                                                          |
| Stops or sleeps for being idle | None                                                                            |

The API refuses a body that:

- has both `spec` and one of `image`, `command`, `args` or `env`
- has a spec that would be refused as a
  [Pod in the pool](#run-a-pod-or-a-job-in-a-pool), or by the namespace's Pod
  Security level, even in a gVisor or Kata pool
- sets a `serviceAccountName` other than the pool's, or asks for a service
  account token in a pool that sets none: see
  [Give a sandbox a token](#give-a-sandbox-a-token)
- sets a `restartPolicy` other than `Never`, or a `restartPolicy` or
  `restartPolicyRules` on an app container
- has a volume other than `emptyDir`, `secret`, `configMap`, or `projected`
  from Secrets, ConfigMaps and service account tokens
- sets a `hostPort`, or has ephemeral containers

The namespace's rules apply to a sandbox as to a Pod:

- You need `get` on each Secret and ConfigMap that the spec refers to.
- The namespace's Pod Security level applies to a sandbox in either form. A
  sandbox of the short form runs one container named `sandbox` that sets no
  security context, so the `restricted` level refuses it: use a `spec` there.
- The namespace's LimitRanges' defaults fill in the containers' resources, and
  their bounds refuse the sandbox.
- Kite does not run the probes of a sandbox's containers.

:::caution
Admission webhooks and admission policies see Pods, not sandboxes. A webhook or a
`ValidatingAdmissionPolicy` that checks or changes each Pod does not check or
change a sandbox. Use RBAC on `sandboxpools/sandboxes` to decide who may create sandboxes.
:::

### Give a sandbox a token

A sandbox can call the Kite API with a ServiceAccount token, as a Pod does. Set
`serviceAccountName` on the pool, and its sandboxes run as that ServiceAccount:

```yaml
apiVersion: kiteplane.dev/v1alpha1
kind: SandboxPool
metadata:
  name: builders
  namespace: ci
spec:
  runtimeClassName: gvisor
  reservation: { cpu: "8", memory: 16Gi }
  container: { cpu: "1", memory: 2Gi }
  serviceAccountName: builder
```

A sandbox gets a token only when its `spec` asks for one. With
`automountServiceAccountToken: true`, Kite mounts the token at
`/var/run/secrets/kubernetes.io/serviceaccount/token`, with `ca.crt` and
`namespace` beside it, as it does for a Pod:

```sh
kubectl create --raw \
  /apis/kiteplane.dev/v1alpha1/namespaces/ci/sandboxpools/builders/sandboxes \
  -f - <<'EOF'
{
  "spec": {
    "automountServiceAccountToken": true,
    "containers": [{
      "name": "hand",
      "image": "python:3.12-slim",
      "command": ["sleep", "infinity"]
    }]
  }
}
EOF
```

The RBAC rules bound to the ServiceAccount decide what the sandbox may do. A
sandbox keeps the ServiceAccount that the pool sets when you create the
sandbox. A sandbox's spec may leave out `serviceAccountName`, or set it to the
pool's.

| Sandbox or Pod                                                             | Token                                                                                                                                        |
| -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| A `spec` with `automountServiceAccountToken: true`                         | At `/var/run/secrets/kubernetes.io/serviceaccount/token`                                                                                     |
| A `spec` with a projected `serviceAccountToken` volume                     | Where the volume mounts it. Set its `audience` to get a token for another service, such as a cloud that exchanges it for its own credentials |
| A `spec` that leaves `automountServiceAccountToken` unset                  | None, unlike a Pod                                                                                                                           |
| A `spec` that sets `serviceAccountName: default`, in a pool that sets none | None                                                                                                                                         |
| A sandbox with `image`                                                     | None. Use a `spec`                                                                                                                           |
| A Pod in the pool                                                          | The token of its own `serviceAccountName`, as any Pod                                                                                        |

The Kite API refuses a token whose audience is not the cluster's issuer.

| When                                           | The API and the token                                                                                              |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| The sandbox runs                               | Accepts it. Kite writes a new token to the file before the old one expires                                         |
| The sandbox stops, sleeps, fails or is deleted | Refuses it                                                                                                         |
| You delete the ServiceAccount                  | Refuses it                                                                                                         |
| The sandbox wakes from sleep                   | The sandbox gets a new token                                                                                       |
| The sandbox starts from a memory snapshot      | The sandbox gets a token of its own, but its processes hold the old sandbox's token until they read the file again |

### Send requests to a sandbox

A request to `sandboxpools/<pool>/proxy/<sandbox>:<port>/<path>` goes to a
Running sandbox's port. A WebSocket upgrade request to that path opens a
WebSocket to the sandbox. You need the verb of the request's method on
`sandboxpools/proxy`. A response from the sandbox has the header
`x-kite-sandbox`, set to the sandbox's id. A response without that header comes
from the API, such as a rejection.

### Logs and exec

`log/<id>` returns a sandbox's log. It takes the query parameters of a Pod's
log, such as `tailLines`, `sinceSeconds` and `previous`, and `?follow=true`
follows it:

```sh
kubectl get --raw \
  "/apis/kiteplane.dev/v1alpha1/namespaces/ci/sandboxpools/builders/log/<id>?follow=true"
```

`exec/<id>` runs a command in a sandbox, with the WebSocket protocol and the
query parameters of `kubectl exec`. `kubectl exec` itself runs commands only in
Pods, so open a WebSocket with the subprotocol `v5.channel.k8s.io`:

```text
path:  /apis/kiteplane.dev/v1alpha1/namespaces/ci/sandboxpools/builders/exec/<id>
query: ?command=ls&command=/&stdout=true&stderr=true
```

A sandbox of the short form has one container, `sandbox`. For a sandbox with a
`spec` and more than one app container, set `container` to the name of one.

After a sandbox ends:

- You can read its log until you delete the sandbox. With `previous=true`, the
  read returns the log of a container's run before its last one. Only a
  sidecar that restarted has such a run.
- You cannot run a command in it, because its node removes its containers.
- Each node keeps the logs of a number of ended sandboxes, given in
  [Limits](#limits), and deletes the oldest first. A read of a deleted log, or
  of a sandbox whose node is deleted, returns 404.
- A sandbox that starts from a snapshot has a log of its own. Read the log of
  the sandbox that you took the snapshot from by that sandbox's id.

With [agent telemetry](/docs/reference/node-agent/#agent-telemetry) on, the node also
sends each line of a sandbox's log to your telemetry endpoint, as it does for a
Pod's, with these fields:

| Field                                 | Value                         |
| ------------------------------------- | ----------------------------- |
| `k8s.pod.name`                        | `<pool>-<id>`                 |
| `k8s.pod.uid`                         | The sandbox's id              |
| The label `kiteplane.dev/sandbox`     | The sandbox                   |
| The label `kiteplane.dev/reservation` | The sandbox's reservation Pod |

### Idle sandboxes

A sandbox is idle when it has no request, no open WebSocket through the proxy
and no open exec. Set `idleTimeoutSeconds`, and `onIdle` says what happens
after that many idle seconds:

| `onIdle`            | The sandbox                                                                                              | Phase      |
| ------------------- | -------------------------------------------------------------------------------------------------------- | ---------- |
| `Stop`, the default | Stops for good, with the reason `Idle`                                                                   | `Stopped`  |
| `Sleep`             | Keeps its id and books no capacity. An exec or a request through the proxy starts it again from its spec | `Sleeping` |
| `SleepWithFiles`    | Sleeps as with `Sleep`, and saves its writable files first. An image-based sandbox only                  | `Sleeping` |

- The API refuses `Sleep` and `SleepWithFiles` without `idleTimeoutSeconds`.
- The idle timer starts again when the node agent restarts.
- A pool with `minReservations: 0` can have no reservation Pods while its
  sandboxes sleep.

An exec or a request through the proxy wakes a sleeping sandbox. A proxy
request needs only the RBAC verb that its method needs on
`sandboxpools/proxy`, and an exec needs the usual permissions on
`sandboxpools/exec`. If the sandbox does not run within 30 seconds, the request
returns a 503. Reading its logs leaves a sleeping sandbox asleep.

The node runs a sandbox that wakes as a new run:

| In the new run                    | Value                          |
| --------------------------------- | ------------------------------ |
| The sandbox's `instance` field    | A new value                    |
| The log                           | The new run's                  |
| The Pod's `metadata.uid`          | The run's `instance`           |
| The label `kiteplane.dev/sandbox` | The sandbox's id, in every run |

So a container that needs its sandbox's id reads the label:

```json
"env": [
  {
    "name": "SANDBOX",
    "valueFrom": {
      "fieldRef": { "fieldPath": "metadata.labels['kiteplane.dev/sandbox']" }
    }
  }
]
```

:::caution
A sandbox with `"onIdle": "Sleep"` wakes without the files of its last run. To
keep them, use `SleepWithFiles`.
:::

#### Keep files across sleep

With `"onIdle": "SleepWithFiles"`, each time the sandbox goes idle, Kite saves
its writable layer to the cluster's snapshot bucket. The next exec or proxy request
starts a new process with the files from the last successful save, even on
another node. A snapshot that you supply at creation sets the files for the
first run. To set up the bucket, see
[Store snapshots of sandboxes](/docs/configure/#store-snapshots-of-sandboxes).

- The save reads the writable layer while your processes run, as a file
  snapshot does. Finish background writes before the sandbox goes idle if
  several files must reflect the same update.
- An open exec, proxy request or WebSocket keeps the sandbox active. If a save
  begins before your request reaches the node, retry the request.
- If the upload fails, the sandbox keeps running and reports `IdleSaveFailed`.

#### When a sandbox's machine goes away

- Evicting a reservation Pod starts a save for each active `SleepWithFiles`
  sandbox on it. The eviction returns HTTP 429 while a sandbox still needs to
  save, so retry it after the save.
- When a managed node pool reaches its termination deadline, it removes the
  machine even if a save is still pending.
- If your managed node pool confirms that the machine is gone, a sandbox with
  a completed save returns to `Sleeping`, and your next exec or proxy request
  restores that save. Its `recovery` field gives the snapshot ID and the
  checkpoint's creation time. Edits made after that checkpoint can be lost.
- A sandbox that loses its machine before its first completed save reports
  `Failed` with reason `MachineLost`.
- A disconnected node can return, so a disconnect alone does not start a
  replacement run.

### Limit where a sandbox connects

A sandbox's `egress` field accepts the `allowedHosts` and `inject` fields of an
[EgressPolicy](/docs/egress-policy/). Outside the cluster, the
sandbox can then connect only to those hosts, and its requests get the injected
headers. You need `get` on each Secret that `inject` refers to. A Pod in a
pool uses an EgressPolicy, as any Pod does.

To add a header to one host's requests and keep every other connection, list
`*`, which allows every host and port:

```json
{
  "egress": {
    "allowedHosts": ["*"],
    "inject": [
      {
        "host": "github.com",
        "basicAuth": { "username": "x-access-token" },
        "secretKeyRef": { "name": "git-token", "key": "token" }
      }
    ]
  }
}
```

A sandbox with `egress` runs only on a node whose agent enforces egress rules,
and its containers start once that node redirects the sandbox's traffic. While
none of the pool's reservation Pods is on such a node, the sandbox stays Pending
with the reason `EgressNotEnforced`.

## Starts and wakes

How long a sandbox or a Pod in the pool takes to start depends on what it
waits for. Each kind has its own name:

| Start                   | What it waits for                                                                 |
| ----------------------- | --------------------------------------------------------------------------------- |
| Sandbox start           | A reservation with room: the node starts the sandbox's runtime and containers     |
| Sandbox scale-up start  | The pool adds a reservation Pod, which the scheduler places and the node starts   |
| Sandbox wake            | A sleeping sandbox's next request: the node starts it from its last file snapshot |
| Sandbox memory wake     | The same, with its processes' memory restored under gVisor                        |
| Pool Pod start          | A reservation with room: the Pod books part of it, and the node starts it         |
| Pool Pod scale-up start | The pool adds a reservation Pod first                                             |
| Node start              | No node has room: a [node pool](/docs/node-pools/) creates a machine first        |

Keep `minWarmSlots` at the number of workloads you start at once after an
idle period, so that their starts are sandbox starts and pool Pod starts
rather than scale-up starts.

## Snapshots

A snapshot contains a sandbox's files. To take one, send a `POST` with
`{"sandbox": "<id>"}` to the pool's `snapshots` subresource. A sandbox created
with `"snapshot": "<id>"` starts with that snapshot's files. If its node cannot
read them, the sandbox fails with the reason `RestoreFailed`. Snapshots need a
bucket: see [Store snapshots of sandboxes](/docs/configure/#store-snapshots-of-sandboxes).

A snapshot of a sandbox with a `spec` contains the files of its first app
container. A sandbox that starts from it gives those files to its own first app
container, which runs the snapshot's image. Its volumes and its other
containers start empty.

- Kite deletes a snapshot 30 days after it was taken, last restored, or left
  with no tag.
- A tag keeps a snapshot until you remove the tag. A tag is a lowercase
  RFC 1123 label, and a snapshot has at most 16.
- A snapshot outlives its pool. Deleting a namespace deletes its snapshots.
- RBAC: `create`, `get`, `patch` and `delete` on `sandboxpools/snapshots`. A
  sandbox created from another pool's snapshot also needs `get` on that pool's
  snapshots, because it reads the snapshot's files.

### Memory snapshots

A memory snapshot also contains the memory of the sandbox's processes, such as
the variables of a notebook's kernel. To take one, add `"memory": true`:

```sh
kubectl create --raw \
  /apis/kiteplane.dev/v1alpha1/namespaces/ci/sandboxpools/builders/snapshots \
  -f - <<'EOF'
{"sandbox": "<id>", "memory": true}
EOF
```

The sandbox keeps running while its node takes the snapshot. The snapshot's
`kind` is `Memory`, and a snapshot of the files alone has the `kind` `Files`.
A sandbox that you create with `"snapshot"` set to a memory snapshot's id starts
with its processes as they were when the snapshot was taken. Its `restored`
field is `Restoring` until its node confirms that runsc restored them, and then
`Memory`. A sandbox with `image` that sets no `command` and no
`args` runs the snapshot's.

To take a memory snapshot, the sandbox needs:

| Needs      | Value                                         |
| ---------- | --------------------------------------------- |
| Runtime    | gVisor, with the RuntimeClass handler `runsc` |
| Node       | amd64                                         |
| Containers | One container and no init containers          |
| Start      | Not from a snapshot's files alone             |

A sandbox from a memory snapshot starts with the snapshot's files alone, and
its `restored` is `Files`, when a need is not met:

| Needs                                   | Falls back to files when                                           |
| --------------------------------------- | ------------------------------------------------------------------ |
| The same release of gVisor              | Its node runs another release than the node that took the snapshot |
| Each CPU feature of the snapshot's node | Its node's CPU lacks one                                           |
| The same container                      | Its container's name, image, command or arguments differ           |
| A restore that works                    | Its node fails to restore the memory                               |

Kite places the sandbox on a node that can restore the memory when one has
room.

A sandbox restored from memory has a new address, so its processes' network
connections break, and clients must connect again.

## Limits

| Limit                                                        | Value      |
| ------------------------------------------------------------ | ---------- |
| Time over the memory cap before `OverMemory`                 | 10 seconds |
| Wait for a sleeping sandbox to run before the proxy's 503    | 30 seconds |
| Ended sandboxes whose logs a node keeps                      | 100        |
| Request body, response and WebSocket message through `proxy` | 4 MiB each |
| Tags per snapshot                                            | 16         |
| Untagged snapshot kept                                       | 30 days    |
