> ## Documentation Index
> Fetch the complete documentation index at: https://docs.styne.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Evals and RL fan-out

> Prepare one sandbox, then start every eval, test or rollout task from it in parallel, each in a sandbox of its own.

There are two ways to start from a prepared sandbox:

| Start from | When | Call |
| - | - | - |
| a [snapshot](https://docs.styne.ai/snapshots.md) | the same start for many runs over time; the prepared state outlives the sandbox | `POST /sandboxes` with `snapshot` |
| a [fork](https://docs.styne.ai/fork.md) | many copies of a running sandbox right now, with its memory | `POST /sandboxes/{id}/fork` with `count` |

Both begin each task exactly where the prepared sandbox was, with its files and memory, in about the time of a create.

**1. Prepare one sandbox and save it**

```bash theme={"theme":"css-variables"}
curl -sS https://api.styne.ai/sandboxes/$SANDBOX_ID/commands \
  -H "Authorization: Bearer $STYNE_API_KEY" -H "content-type: application/json" \
  -d '{"cmd": "sh", "args": ["-c", "mkdir -p /root/task && echo prepared > /root/task/state.txt && sync"]}'

curl -sS https://api.styne.ai/sandboxes/$SANDBOX_ID/snapshots \
  -H "Authorization: Bearer $STYNE_API_KEY" -H "content-type: application/json" \
  -d '{"name": "fanout-demo"}'
```

Install your dependencies and check out your repository in the first command; every task then starts with them in place. The
snapshot outlives the sandbox it was taken from, so kill the prepared sandbox now: it would otherwise count against your
concurrency limit while the tasks run.

```bash theme={"theme":"css-variables"}
curl -sS -X DELETE https://api.styne.ai/sandboxes/$SANDBOX_ID \
  -H "Authorization: Bearer $STYNE_API_KEY"
```

**2. Start the tasks in parallel**

The Python version runs three tasks with at most two sandboxes alive at a time (inside the trial's limit of 3 VMs at once; raise `MAX_PARALLEL` on a plan that allows more). Each task creates a sandbox from the snapshot, runs one
command, collects the result, and kills the sandbox even when it fails. A `429` or `503` is retried after `Retry-After`.

Starting many sandboxes at once from Node: each sandbox is reached at a host name of its own (`49983-<id>.<domain>`), and Node
resolves each new name on libuv's four DNS threads, so the first command of a hundred sandboxes started together waits in a queue
of lookups. Measured on 2026-11-17 with the E2B JavaScript SDK, 100 sandboxes created at once from a server in the same region:
the median first command took 750 ms; with `UV_THREADPOOL_SIZE=128` in the process environment it took 255 ms.

```python Python theme={"theme":"css-variables"}
import asyncio
import os

import httpx

API = "https://api.styne.ai"
HEADERS = {"Authorization": f"Bearer {os.environ['STYNE_API_KEY']}"}
MAX_PARALLEL = 2
TASKS = ["alpha", "beta", "gamma"]

async def call(client, method, path, **kw):
    for attempt in range(8):
        r = await client.request(method, API + path, **kw)
        if r.status_code in (429, 503, 504):
            await asyncio.sleep(float(r.headers.get("Retry-After", 1)) * (attempt + 1))
            continue
        r.raise_for_status()
        return r
    raise RuntimeError(f"{method} {path}: still busy after retries")

async def run_task(client, gate, name):
    async with gate:
        sandbox = (await call(client, "POST", "/sandboxes", json={"snapshot": "fanout-demo", "timeout": 300})).json()
        sid = sandbox["sandboxID"]
        try:
            body = {"cmd": "sh", "args": ["-c", f"cat /root/task/state.txt && echo task={name}"]}
            out = (await call(client, "POST", f"/sandboxes/{sid}/commands", json=body)).json()
            return name, out["stdout"].split()
        finally:
            await client.delete(f"{API}/sandboxes/{sid}")

async def main():
    gate = asyncio.Semaphore(MAX_PARALLEL)
    async with httpx.AsyncClient(headers=HEADERS, timeout=120) as client:
        for name, lines in await asyncio.gather(*(run_task(client, gate, t) for t in TASKS)):
            print(name, lines)

asyncio.run(main())
```

```typescript TypeScript theme={"theme":"css-variables"}
const API = 'https://api.styne.ai'
const headers = { Authorization: `Bearer ${process.env.STYNE_API_KEY}`, 'content-type': 'application/json' }
const TASKS = ['alpha', 'beta']

async function call(method: string, path: string, body?: unknown): Promise<any> {
  for (let attempt = 1; attempt <= 8; attempt++) {
    const r = await fetch(API + path, { method, headers, body: body ? JSON.stringify(body) : undefined })
    if ([429, 503, 504].includes(r.status)) {
      await new Promise((ok) => setTimeout(ok, Number(r.headers.get('retry-after') ?? 1) * 1000 * attempt))
      continue
    }
    if (!r.ok) throw new Error(`${method} ${path}: ${r.status} ${await r.text()}`)
    return r.status === 204 ? null : r.json()
  }
  throw new Error(`${method} ${path}: still busy after retries`)
}

async function runTask(name: string): Promise<[string, string[]]> {
  const { sandboxID } = await call('POST', '/sandboxes', { snapshot: 'fanout-demo', timeout: 300 })
  try {
    const out = await call('POST', `/sandboxes/${sandboxID}/commands`, {
      cmd: 'sh',
      args: ['-c', `cat /root/task/state.txt && echo task=${name}`],
    })
    return [name, out.stdout.split(/\s+/).filter(Boolean)]
  } finally {
    await fetch(`${API}/sandboxes/${sandboxID}`, { method: 'DELETE', headers })
  }
}

for (const [name, lines] of await Promise.all(TASKS.map(runTask))) console.log(name, lines)
```

The Python version prints:

```text theme={"theme":"css-variables"}
alpha ['prepared', 'task=alpha']
beta ['prepared', 'task=beta']
gamma ['prepared', 'task=gamma']
```

The TypeScript version prints the same lines for its two tasks. `Promise.all` starts every task at once, so keep the list within your concurrency (two tasks here, inside every plan's limit); for
more tasks than that, take them from a queue with a fixed number of workers instead of mapping over the whole list.

## Fork instead: copies of a running sandbox

Use a fork when the tasks need the live state of one sandbox (a warmed interpreter, a loaded model, a running server).

```bash theme={"theme":"css-variables"}
curl -sS https://api.styne.ai/sandboxes/$SANDBOX_ID/fork \
  -H "Authorization: Bearer $STYNE_API_KEY" -H "content-type: application/json" \
  -d '{"count": 2, "timeout": 300}'
```

The answer lists the children, each with its own `sandboxID`; kill them when the tasks end. The parent counts too, so on the trial
(three VMs at once) fork with at most `"count": 2`.

## Concurrency limits

| Account | Sandboxes alive at once | Over the limit |
| - | - | - |
| Trial | 3 VMs at once | `429 limit_concurrent` with `Retry-After` |
| Starter plan | 200 VMs at once | `429 limit_concurrent` with `Retry-After` |
| Pro plan | 1,000 VMs at once | `429 limit_concurrent` with `Retry-After` |
| Any plan | capacity above the `target` of your entitlement is added in steps | `429 capacity_provisioning` with `Retry-After` while a step is pending, `429 quota_exceeded` above the target |

Size your parallelism to the limit of your account, read in `GET /v1/run/usage` (`concurrent_sandboxes`, `caps`), and
keep the retry on `429 capacity_provisioning` and `503 capacity` as the examples do. The API applies no per-key request
rate limit. See
[limits](https://docs.styne.ai/limits.md) and [errors](https://docs.styne.ai/errors.md#retrying).

## Keep it clean

* A refused create holds nothing, so retrying it is safe. Kill what you create in a `finally`: a sandbox you forget runs
  and bills until its `timeout`.
* Give each task its own `timeout` shorter than the job; the sandbox ends by itself if your harness dies.
* Tag sandboxes with `metadata` (a run id) and list them with `GET /sandboxes` to clean up after a crash.
* To tell a failed task from a failed platform in a harness, branch on the error's `origin`: see
  [errors](https://docs.styne.ai/errors.md#origin).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.