# Fan out from one snapshot

Install once, copy many times. Set up a sandbox the slow way a single time, save it, then start as many identical copies as the job needs: one shard of a test suite each, or one rollout each. Every copy starts with the installs done and the files in place.

Everything on this page works on kosa8 Cloud today with the `kosa8` Python SDK 0.5.5 (`Kosa8Cloud`) or plain HTTP. For RL runs, batch create, leases and a sealed grader build on this pattern; see [RL training](https://docs.kosa8.com/guides/rl-training/).

## Two ways to copy

|  | `fork` | Create from a snapshot |
|---|---|---|
| Call | `POST /v1/sandboxes/{id}/fork {"n": N}` | `POST /v1/sandboxes {"snapshot": "snap_…"}`, once per copy |
| Copies a call | 1 to 1,000; by default the copies that fit are kept and the rest listed in `failed` (`"partial_ok": false` for all or nothing) | One |
| The source | A running sandbox, as it is now | A saved snapshot, which outlives its sandbox |
| Best for | One job, right now | The same starting point reused across jobs and days |

Both keep memory, processes and disk. Both start the copies on the host that holds the source (a fork that does not fit there goes on to other hosts, when there are any; see [fork](https://docs.kosa8.com/guides/rl-training/#fork)), and every copy counts toward your plan's sandboxes running at once (2, 10, 25 or up to 1,000; see [pricing](https://kosa8.com/pricing/#compare)).

## 1. Set up once and snapshot

```
from kosa8 import Kosa8Cloud

cloud = Kosa8Cloud()                                   # reads KOSA8_API_KEY
base = cloud.sandboxes.create(template="python", name="suite-base", ttl_s=3600)   # has git, bash and pytest
base.exec("cd /workspace && git clone -q https://github.com/pallets/click repo")
base.exec("cd /workspace/repo && pip install -q -e . pytest")
snap = base.snapshot(name="click-deps")                # {"id": "snap_…", "state": "ready", …}
```

Or with curl:

```
curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/snapshots \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' -d '{"name":"click-deps"}'
# 201 {"snapshot":{"id":"snap_…","state":"ready",…}}
```

Each `exec` answers with an `exit_code`: check it in your own script, since a failed step does not raise. An exec answered as one JSON object stops after 90 seconds. Run a long install in the background (see [background commands](https://docs.kosa8.com/guides/cloud-snapshots-background/)) and snapshot when it has finished.

## 2. Fan out

With `fork`, from the running base:

```
N = 8
shards = base.fork(N)                                  # N running copies
```

```
curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/fork \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' -d '{"n":8}'
# {"parent":"sbx_…","sandboxes":[{"id":"sbx_…","state":"running",…}, …],"requested":8,"created":8,"failed":[],…}
```

Or from the snapshot, which still works after the base is gone:

```
from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(N) as pool:
    shards = list(pool.map(lambda _: cloud.sandboxes.create(snapshot=snap["id"], ttl_s=3600), range(N)))
```

```
curl -s -X POST https://api.kosa8.com/v1/sandboxes \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' -d '{"snapshot":"snap_…","ttl_s":3600}'
```

For more than 1,000 copies, fork again or create from the snapshot in more threads. Keep the thread count at or under your running limit: past it a create answers **402** `plan_limit`.

## 3. Shard the work

Give each copy its slice. For a test suite, list the tests once and split them by index. Each argument of a command is at most 8,192 characters, so write a shard's test ids to a file and hand pytest the file (`@file`) rather than putting them on the command line:

```
from concurrent.futures import ThreadPoolExecutor

out = base.exec("cd /workspace/repo && python -m pytest --collect-only -q").stdout
ids = [t for t in out.splitlines() if "::" in t]       # 2,653 tests for click

def run_shard(i, sbx):
    sbx.files.write("/workspace/shard.txt", "\n".join(ids[i::N]))   # every Nth test, starting at i
    r = sbx.exec("cd /workspace/repo && python -m pytest -q @/workspace/shard.txt")
    return {"shard": i, "id": sbx.id, "exit": r.exit_code, "tail": r.stdout[-2000:]}

with ThreadPoolExecutor(N) as pool:
    results = list(pool.map(run_shard, range(N), shards))
```

For rollouts, the slice is one task (or one sample of a group) per copy:

```
def rollout(task, sbx):
    r = sbx.exec(["bash", "-c", task["command"]])      # your policy's action
    return {"task": task["id"], "exit": r.exit_code, "stdout": r.stdout[-4000:]}

with ThreadPoolExecutor(N) as pool:
    results = list(pool.map(rollout, tasks[:N], shards))
```

## 4. Collect and clean up

```
failed = [r for r in results if r["exit"] != 0]
print(f"{N - len(failed)}/{N} shards passed")
for r in failed:
    print(r["shard"], r["tail"])

for sbx in shards:
    sbx.delete()
base.delete()                                          # the snapshot stays until you delete it
cloud.snapshots.delete(snap["id"])                     # when you no longer need the starting point
```

The `ttl_s` on every sandbox is the safety net: if the script dies before this step, each copy is deleted when its TTL runs out, so it does not keep using your sandbox-hours.

## Things to watch

- **One host first.** Copies start on the host that holds the source. A fork that does not fit there goes on to other hosts when there are any; copies no host has room for come back in `failed`. If the host is full, a create from a snapshot answers **503** `no_capacity` with `Retry-After`: wait and retry; it is not a plan limit.

- **Snapshots count.** They count toward your plan's snapshot limit (5, 50, 250 or 1,000) until you delete them (see [snapshots](https://docs.kosa8.com/guides/cloud-snapshots-background/)). Delete the ones you are done with.

- **Network.** A sandbox made from a snapshot gets your organisation's egress policy, not the source's. If the copies run untrusted code, set the policy on each copy, or on the organisation, before they run it.

- **Not copyable.** A sandbox with brokered secrets or dedicated cores cannot be snapshotted (**409**), and a dedicated sandbox cannot be forked.

See also: [snapshots, background commands and env](https://docs.kosa8.com/guides/cloud-snapshots-background/), [RL training](https://docs.kosa8.com/guides/rl-training/) and [RL rollouts and evals](https://docs.kosa8.com/guides/py-rl-eval/).

---
Source: https://docs.kosa8.com/guides/cloud-fan-out/
