# Benchmark
<subtitle>Run sandbox operations repeatedly at a given concurrency and measure per-phase latency, failure rate, and throughput.</subtitle>

`benchmark` (alias `bench`) runs a set of sandbox operations a given number of times at a given concurrency. Each step is timed separately, and the result reports the latency distribution, failure count, and failure reasons for every phase.

| Command | Purpose |
| --- | --- |
| `bench create` | Measure sandbox creation latency only |
| `bench lifecycle` | Measure the full lifecycle latency: create, first command execution, and kill |
| `bench snapshot` | Measure latency of creating a snapshot, restoring from a snapshot, forking, and deleting the snapshot, and verify the data in the copies |

> ⚠️Note: Benchmarks create real sandboxes, and `bench snapshot` also creates snapshots. All of these resources are billed under the normal rules. For billing details, see [Billing](/docs/agent-sandbox/product/fee.md). High concurrency may also hit quota limits; see [Quotas](/docs/agent-sandbox/product/ratelimit.md).

## Quick start

```bash
# Run 100 lifecycle iterations at concurrency 10
ucloud-sandbox-cli bench lifecycle -n 100 -c 10

# Measure sandbox creation latency only
ucloud-sandbox-cli bench create -n 50 -c 10

# Measure snapshot, restore-from-snapshot, fork, and snapshot deletion latency
ucloud-sandbox-cli bench snapshot -n 3
```

Benchmarks use the API Key and region configured for the CLI. For configuration, see the [CLI Guide](/docs/agent-sandbox/product/cli.md).

## Common options

All `bench` subcommands support the following options:

| Option | Description | Default |
| --- | --- | --- |
| `-t, --template` | Template ID or alias used to create sandboxes | `system/base` |
| `-n, --count` | Total number of iterations | 10 for `create` and `lifecycle`, 3 for `snapshot` |
| `-c, --concurrency` | Concurrency | 1 |
| `--timeout` | Lifetime of each sandbox in seconds, as a fallback when it is not cleaned up normally | 300 |
| `-f, --format` | Output format, `pretty` or `json` | `pretty` |
| `-o, --output` | Additionally write the JSON result to the given file, independent of `--format` | No file |
| `--breakdown` | Expand each phase's duration into connection setup time and service time | Off |

One iteration corresponds to one sandbox: create the sandbox, run each step of the command against it in order, and finally kill it. Each step is called a phase and is timed separately.

`-o` is meant for the "read the table in the terminal and keep a JSON copy" case. A single run produces both outputs, so there is no need to run twice:

```bash
ucloud-sandbox-cli bench lifecycle -n 200 -c 50 -o result.json
```

## During a run

When a run starts, the CLI first prints basic information about the benchmark:

```text
Running lifecycle benchmark 20261125-225910-b2bbf0
  Template:     system/base
  Iterations:   100 (concurrency 10)
  Sandbox tag:  benchmark=20261125-225910-b2bbf0
  Cleanup:      ucloud-sandbox-cli sandbox kill --all -m benchmark=20261125-225910-b2bbf0
```

- Each run gets a run ID made up of the start time and a random suffix.
- Every sandbox created in the run carries the metadata `benchmark=<run ID>` and is marked as created by `sandbox-bench`. The command on the `Cleanup` line only deletes sandboxes from this run and does not affect any other sandboxes.
- When running in a terminal, progress and success/failure counts are shown in real time.

Press `Ctrl+C` once and the CLI stops starting new iterations, waits for in-flight iterations to finish and clean up their sandboxes, then prints the results for the completed part. Press `Ctrl+C` again to exit immediately; this may leave sandboxes behind, which you can delete with the `Cleanup` command shown at the start.

If any iteration fails or the run is interrupted, the command exits with a non-zero exit code, so scripts and CI can detect the result.

## Reading the results

When the run finishes, the CLI prints a summary and a statistics table per phase (values are for illustration only):

```text
Benchmark 20261125-225910-b2bbf0 completed: template system/base, concurrency 10
Iterations: 100/100 started, 98 succeeded, 2 failed
Elapsed: 42.5s, rate: 2.31 sandbox/s

Service time per phase, excluding connection setup (DNS, dial, TLS); --breakdown shows the full latency:
+--------+-----------+--------+-------+-------+-------+-------+-------+-------+
| Phase  | Succeeded | Failed | Avg   | Min   | P50   | P95   | P99   | Max   |
+--------+-----------+--------+-------+-------+-------+-------+-------+-------+
| create | 100       | 0      | 1.21s | 862ms | 1.15s | 1.68s | 2.03s | 2.11s |
| exec   | 98        | 2      | 156ms | 98ms  | 142ms | 245ms | 301ms | 312ms |
| kill   | 100       | 0      | 85ms  | 61ms  | 80ms  | 121ms | 150ms | 156ms |
| total  | 98        | 2      | 1.47s | 1.08s | 1.39s | 1.98s | 2.35s | 2.41s |
+--------+-----------+--------+-------+-------+-------+-------+-------+-------+
```

- `Elapsed` is the duration of the whole run, and `rate` is the number of iterations completed successfully per second.
- The line above the table states which duration is shown: service time (excluding connection setup) by default, or the full latency with `--breakdown`.
- Each phase has one row. `Succeeded` and `Failed` are the number of successes and failures for that phase; latency statistics only include successful attempts.
- Percentiles (`P50`, `P95`, `P99`) are taken from actually observed durations.
- `total` is the end-to-end duration of an iteration from create to kill, and only counts iterations in which every phase succeeded. It is not shown when there is only one phase (such as `bench create`).

### Connection setup time and service time

The duration of each request consists of two parts:

- **connect**: the time to establish the HTTP connection, i.e. DNS resolution, TCP connect, and TLS handshake. It is close to 0 when a connection is reused. This part mainly depends on the network between the client and the server.
- **service**: everything other than connection setup, i.e. the time for the server to process the request and respond.

By default the table only shows service time, which makes it easier to observe server-side performance. With `--breakdown`, each phase first shows the full latency including connection setup, followed by separate connect and service rows:

```text
| create    | 100 | 0 | 1.29s | 901ms | 1.22s | 1.80s | 2.15s | 2.20s |
|   connect | -   | - | 80ms  | 0s    | 45ms  | 210ms | 260ms | 270ms |
|   service | -   | - | 1.21s | 862ms | 1.15s | 1.68s | 2.03s | 2.11s |
```

connect and service are computed independently, so their percentiles do not add up to the percentiles of the full latency.

### Errors

When there are failures, a summary grouped by "phase + error message" is shown below the statistics table, sorted by count in descending order. Failures with the same cause are merged into one row: sandbox IDs in error messages are replaced with a placeholder, and long request URLs are stripped so that only the cause remains:

```text
Errors:
+-------+-------+--------------------------------------------+
| Count | Phase | Message                                    |
+-------+-------+--------------------------------------------+
| 8     | exec  | net/http: TLS handshake timeout            |
| 3     | exec  | dial tcp: lookup ...: no such host         |
| 2     | kill  | context deadline exceeded                  |
+-------+-------+--------------------------------------------+
```

> Benchmarks disable the SDK's automatic retry on rate-limit responses (HTTP 429). When rate limiting is triggered, the request is recorded as a failure and appears in the error table, instead of inflating latency with retry wait time.

## bench create

Measures sandbox creation latency only. Each iteration makes a single create call; it does not run commands or kill the sandbox:

```bash
ucloud-sandbox-cli bench create -n 50 -c 10
```

The created sandboxes keep running until the lifetime set by `--timeout` (5 minutes by default) expires and they are reclaimed, so the number of live sandboxes grows with the number of iterations during the run. The end of the output shows how many sandboxes were left running. To delete them earlier, run the `Cleanup` command shown at the start.

> If `-n` is large, later creations may fail after hitting the quota limit. These failures appear in the error table.

## bench lifecycle

Measures the full sandbox lifecycle. Each iteration runs the following in order:

| Phase | Description |
| --- | --- |
| create | Create a sandbox |
| exec | Run a command in the sandbox, measuring the time from creation until the sandbox is actually usable |
| kill | Kill the sandbox |

```bash
ucloud-sandbox-cli bench lifecycle -n 100 -c 10

# Specify the command and user
ucloud-sandbox-cli bench lifecycle --cmd "python3 --version" -u root

# Measure create and kill only
ucloud-sandbox-cli bench lifecycle --skip-exec
```

| Option | Description | Default |
| --- | --- | --- |
| `--cmd` | Command run in the exec phase; a non-zero exit code counts as a failure | `echo ok` |
| `-u, --user` | User that runs the command | Sandbox default user |
| `--skip-exec` | Skip the exec phase | Off |

If the exec phase fails, the sandbox is still killed.

## bench snapshot

Measures the latency of snapshot-related operations and verifies that sandboxes restored from the snapshot and forked from the source sandbox retain the source sandbox's data. For snapshots themselves, see [Sandbox Snapshots](/docs/agent-sandbox/sandbox/snapshots.md).

```bash
ucloud-sandbox-cli bench snapshot -n 3
```

Each iteration runs the following in order:

| Phase | Description |
| --- | --- |
| create | Create the source sandbox |
| write | Write a file with random content to the user's home directory in the source sandbox |
| snapshot | Create a snapshot of the source sandbox |
| restore | Create a new sandbox from the snapshot |
| restore-verify | Read the file in the restored sandbox and verify that the content matches |
| fork | Fork a sandbox from the source sandbox |
| fork-verify | Read the file in the forked sandbox and verify that the content matches |
| snapshot-delete | Delete the snapshot |
| kill | Kill the source sandbox |

Notes:

- When a phase fails, the phases that depend on it are recorded as failed with the error message `not attempted: ...`. For example, if snapshot creation fails, neither restore nor snapshot-delete runs. Such failures, where no request was sent, are not counted toward the "the server may have created a sandbox" hint.
- The restored and forked sandboxes are killed after verification and before the snapshot is deleted; this step is not timed. If killing fails, a `cleanup` row appears in the error table and the iteration is recorded as failed.
- Snapshots are named `bench-<run ID>-<source sandbox ID>` and deleted by name.

> ⚠️Note: Unlike sandboxes, snapshots are not reclaimed automatically on expiry. Undeleted snapshots keep occupying storage and are billed. If the results report snapshots that could not be deleted, delete them with the command shown.

## Common symptoms under high concurrency

As concurrency increases, failures usually concentrate on the "establish a new connection" step, which you can see in the connect row of `--breakdown` or in the error table:

| Symptom | Usually indicates |
| --- | --- |
| `net/http: TLS handshake timeout`, `dial tcp ...: connect: operation timed out` | The client failed to open a new connection to the gateway; this is unrelated to execution inside the sandbox. Connections to the same API address are reused, so usually only phases like exec, which use a new address per sandbox, are affected |
| `dial tcp: lookup <sandbox domain>: no such host` | Client-side DNS resolution failed, possibly due to resolver rate limiting or network jitter |
| Outbound internet access from inside the sandbox fails, e.g. `command exited with code 28` | curl timed out inside the sandbox; this is outbound egress congestion and unrelated to the client |
| `context deadline exceeded` | The request timed out as a whole, usually as a result of one of the issues above |

Troubleshooting tips:

- Use `--breakdown` to separate connect from service: a significant increase in connect means the bottleneck is the network or connection count between the client and the gateway; only an increase in service means server-side processing has slowed down.
- Increase concurrency step by step from a low level (e.g. 10, 20, 50) to find the level at which failures start to appear.
- Use `-o` to save the JSON of each run for comparison across time and versions.

## Cleaning up leftover resources

Normally, sandboxes and snapshots created by a benchmark are cleaned up automatically (except sandboxes from `bench create`, which are reclaimed when their lifetime expires). Resources may be left behind in the following cases:

- Killing a sandbox or deleting a snapshot failed.
- Creating a sandbox, restoring from a snapshot, forking, or creating a snapshot timed out on the client side, but completed on the server.
- The run was force-exited by pressing `Ctrl+C` twice.

In the first two cases, the end of the output lists the affected resources and cleanup commands. Forked sandboxes and sandboxes restored from snapshots inherit the source sandbox's `benchmark=<run ID>` metadata, so the first command below deletes all sandboxes from the run:

```bash
# Delete all sandboxes created by a run
ucloud-sandbox-cli sandbox kill --all -m benchmark=<run-id>

# Delete specific sandboxes by ID
ucloud-sandbox-cli sandbox kill <sandbox-id...>

# Delete snapshots by name, in the form bench-<run-id>-<sandbox-id>
ucloud-sandbox-cli snapshot list
ucloud-sandbox-cli snapshot delete <snapshot-name...>
```

> `sandbox kill --all` asks for confirmation in a terminal; add `-y` when using it in scripts. Snapshot IDs and names shown by `snapshot list` include a team prefix (such as `<team>/bench-...`) and a tag (such as `:default`). When deleting, use only the name part in the middle, i.e. `bench-...`.

## JSON output

With `-f json`, results are written to standard output as JSON, while run information and progress still go to standard error, so the output can be piped directly:

```bash
ucloud-sandbox-cli bench lifecycle -n 20 -f json > result.json
```

Or use `-o` to write a file while keeping the table output:

```bash
ucloud-sandbox-cli bench lifecycle -n 200 -c 50 -o result.json
```

The file is written whether or not any iteration fails, to help with troubleshooting; when there are failures the command still exits with a non-zero exit code.

Main fields:

| Field | Description |
| --- | --- |
| `run_id` | Run ID |
| `template`, `concurrency`, `sandbox_timeout_sec` | Template, concurrency, and sandbox lifetime of the run |
| `requested`, `started` | Planned and actually started iteration counts |
| `succeeded`, `failed` | Succeeded and failed iteration counts |
| `interrupted` | Whether the run was interrupted |
| `elapsed_ms`, `rate_per_sec` | Duration of the whole run (milliseconds) and iterations completed successfully per second |
| `phases` | Per-phase statistics, see below |
| `errors` | Failure counts grouped by phase and error message |
| `iterations` | Raw samples of each iteration, see below |
| `leaked` | IDs of sandboxes that could not be killed |
| `leaked_snapshots` | Names of snapshots that could not be deleted |
| `left_running` | Number of sandboxes left running by `bench create` |

Each item in `phases` contains `phase`, `succeeded`, `failed`, and the full latency including connection setup: `avg_ms`, `min_ms`, `p50_ms`, `p95_ms`, `p99_ms`, `max_ms`. The `connect` and `service` objects give the same set of statistics for connection setup time and service time respectively. Note that latency in the JSON is the full latency, unlike the service time shown in the default table.

`iterations` keeps a sample for every iteration, ordered by start time, for analyzing how latency changes over time and locating individual slow requests:

| Field | Description |
| --- | --- |
| `seq` | Iteration sequence number, starting from 1 |
| `sandbox_id` | Sandbox ID of the iteration; empty if creation failed |
| `start_offset_ms` | Offset of the iteration's start relative to the start of the run |
| `succeeded` | Whether all phases succeeded |
| `phases` | Phase results in execution order: successful phases include `duration_ms` and `connect_ms`, failed phases include `error`, and phases that were not reached are omitted |
| `leaked` | Sandbox IDs from this iteration that could not be killed |

`message` in `errors` is a condensed summary; to see the full error of a specific iteration, check the corresponding `iterations[].phases[].error`.
