# RL training on kosa8 Cloud

An RL or post-training run needs thousands of sealed copies of one environment, a reward the policy cannot tamper with, no sandboxes left running when the trainer dies, and a way to tell a policy failure from an infrastructure failure. This guide covers the kosa8 Cloud features built for that, and the limits that apply.

**What is live and what comes next**

**Live today:** create, exec, files, `fork` (up to 1,000 copies a call), snapshots, checkpoints and rewind, egress rules (`egress="deny"`), labels, TTLs and the audit log. The [RL rollouts and evals guide](https://docs.kosa8.com/guides/py-rl-eval/) builds a full rollout loop from those calls, and it works now.

Everything below is live on api.kosa8.com and in `kosa8` 0.5.5 (Python), `@kosa8/sdk` 0.5.3 (JS) and the `kosa8` CLI v0.21.0. `https://api.kosa8.com/openapi.json` is the source of truth for fields.

## The shape of a run

1. **Prepare once.** Build the task's repository and dependencies into a template, or set up a sandbox and snapshot it.

2. **Fan out.** Create a batch of sandboxes, or fork the prepared one into a group (one GRPO group per prompt, say). Tag them all with the run's id.

3. **Roll out.** The policy acts by running commands in its own copy.

4. **Grade sealed.** Score the final state in a fork with no network and hidden tests the policy never saw.

5. **Mask, record, release.** Drop infra failures from the batch instead of scoring them 0, record each rollout to the run, and let the lease clean up whatever is left.

**Rather not run the loop yourself?**

[Hosted jobs](https://docs.kosa8.com/guides/cloud-jobs/) take your tasks, a solver command and a grader, and run every rollout on kosa8's side: retries, masking, the sealed grader, a budget, and the results in an RL run.

## Quickstart

With `kosa8` 0.5.5 (`pip install kosa8==0.5.5`) and `KOSA8_API_KEY` set, this runs as it is. `run.map` forks the base sandbox for each rollout, runs your function, grades the copy in a sealed fork with the task's hidden files, records the result to the run and deletes the copy; infra failures are retried and then marked `masked=True` with reward `None` rather than given reward 0. Leaving the `async with AsyncRun` block marks the run finished and drains every sandbox it made, the base too.

```
import asyncio
import random

import kosa8
from kosa8.rl import AsyncRun

# The hidden grader: it stays on your side until grading, then runs in a sealed
# fork with no network. Its last stdout line {"reward": x} is the reward.
GRADER = """
import json, sys
sys.path.insert(0, "/workspace")
try:
    from solution import add
    passed = sum(add(a, b) == a + b for a, b in [(1, 2), (-3, 3), (10, 5), (0, 0)])
except Exception:
    passed = 0
print(json.dumps({"reward": passed / 4, "metrics": {"passed": passed}}))
"""

tasks = [{"id": f"add-{i}", "prompt": "Write add(a, b) in /workspace/solution.py",
          "files": {"/grader/check.py": GRADER}} for i in range(4)]

def policy(prompt):                                # stand-in for your model
    op = random.choice(["+", "+", "-"])
    return f"def add(a, b):\n    return a {op} b\n"

async def solve(sbx, task):                        # the policy acts in its own copy
    await sbx.files.write("/workspace/solution.py", policy(task["prompt"]))

async def main():
    async with kosa8.AsyncCloud() as cloud:        # reads KOSA8_API_KEY
        # The run heartbeats its sandboxes and drains them when the block ends, even on a crash.
        async with AsyncRun(cloud, "grpo-demo", lease_s=600) as run:
            base = await cloud.sandboxes.create(template="python")
            results = await run.map(base, tasks, solve, group_size=2, concurrency=4,
                                    grade_cmd=["python3", "/grader/check.py"])
    print(results.rewards)                         # e.g. [1.0, 0.25, 1.0, 1.0, 0.25, 1.0, 1.0, 1.0]
    print(results.mean_reward, results.by_class)   # masked (infra) rollouts are None, left out of the mean

asyncio.run(main())
```

It prints the 8 rewards (4 tasks, 2 samples each) and their mean, for example `0.90625 {'ok': 8}`, in under 20 seconds. The python template is Python 3.12 on Debian (`python:3.12-slim`) with `bash`, `git`, `curl`, `pip`, `pytest` and `uv` already in it, so a task can clone a repository and grade with pytest with no install step. Anything else your tasks need, install into the base in a [persistent](https://docs.kosa8.com/guides/cloud/#persistent) sandbox (or under `/workspace`) before the map, and the forks inherit it. Your function's return value is a reward only when there is no `grade_cmd`: return a number or `{"reward": x}`, or pass `reward=fn(sandbox, task, output)`. Open [app.kosa8.com](https://app.kosa8.com/), then **RL runs**, to watch it.

## Batch create

`POST /v1/sandboxes/batch` makes up to 1,000 sandboxes in one call. The Cloud paces the creates across hosts itself (16 in flight), so your trainer does not have to back off from 429s and 503s. Every sandbox goes through the same plan, payment and size checks as `POST /v1/sandboxes`.

```
curl -s -X POST https://api.kosa8.com/v1/sandboxes/batch \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"count": 64, "template": "python", "run_id": "run_…", "lease_s": 600,
       "labels": {"step": "12"}, "partial_ok": true}'
# {"sandboxes":[{"id":"sbx_…","state":"running",…}, …],
#  "failed":[{"index":63,"code":"running_limit","message":"…","failure_class":"quota","retryable":false}],
#  "requested":64,"created":63,"run_id":"run_…"}
```

| Field | Meaning |
|---|---|
| `count` | 1 to 1,000. |
| `template`, `image`, `cpus`, `mem_mb`, `region` | As on a single create. |
| `labels` | Put on every sandbox. With `run_id`, `kosa8.run=<run_id>` is added. |
| `ttl_s` | Delete each sandbox this many seconds after it was made. |
| `lease_s` | A lease: deleted unless a [heartbeat] extends it. |
| `partial_ok` | Default `true`: keep what was made and list the rest in `failed`. With `false`, one failure deletes the ones made and the answer is that first error. |

The plan's running limit holds: if `count` is more than the room left, kosa8 makes as many as fit and reports the rest as `running_limit` (class `quota`), or, with `partial_ok: false`, refuses before making any.

## Fork a prepared state

`POST /v1/sandboxes/{id}/fork` is live: it snapshots the sandbox once and restores `n` live copies with memory, processes and disk as they were. It is the cheap reset for an episode and the natural unit for a GRPO group. It takes these options:

```
curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_base/fork \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"n": 16, "run_id": "run_…", "lease_s": 600, "labels": {"group": "prompt-41"}, "partial_ok": true}'
# {"parent":"sbx_base","sandboxes":[{"id":"sbx_…",…},…],"host_ms":…,"requested":16,"created":16,
#  "failed":[],"hosts":1,"run_id":"run_…"}
```

- **Up to 1,000 copies a call**, made 100 at a time on the parent's host.

- **How many fit on one host.** Copies share their parent's memory until they write to it, so for idle or light work one host holds the parent and 999 copies (1,000 sandboxes, the Scale plan's running limit); a fork of 999 took about 68 seconds. Copies that each do heavy work (about 150 MiB of memory written apiece) top out at about 700 to 770 on one host. Past what one host holds, copies go to other hosts when there are any (below); otherwise they come back in `failed`.

- **When the parent's host is full**, the rest of a group go to other hosts: the parent is snapshotted once, the snapshot is copied to a host with room, and the remaining copies are restored there from the parent's exact state. They get the same `labels`, `run_id`, `lease_s` and `parent_id`, and names carry on (`roll-0054` and on). The answer's `hosts` says how many hosts hold the group. Copies on another host take longer to arrive (the parent's memory and disk are copied there first, so the time grows with its memory size and what it has written to disk), and count toward sandbox-hours like any sandbox of that size.

- Every copy, on any host, counts toward the plan's running limit.

- `labels`, `run_id` and `lease_s` are put on every child; `partial_ok` defaults to `true`. Copies that no host has room for are listed in `failed` (class `infra`, retryable). `false` keeps the all-or-nothing behaviour, on the parent's host only.

- Dedicated sandboxes cannot be forked (**409** `dedicated`).

## Leases, heartbeat and drain

A trainer that crashes or is pre-empted should not leave a thousand sandboxes using your sandbox-hours. Give them a lease, and keep it alive while the trainer is alive:

```
# every minute or so, while training runs
curl -s -X POST https://api.kosa8.com/v1/sandboxes/heartbeat \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"run_id": "run_…"}'
# {"extended":63,"at":…}

# at the end, or to stop a run now
curl -s -X POST https://api.kosa8.com/v1/sandboxes/drain \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"run_id": "run_…"}'
# {"deleted":63,"ids":["sbx_…",…],"failed":[],"more":false}
```

- `lease_s` on create, batch or fork sets the sandbox to be deleted that many seconds from now. A heartbeat moves it to now plus `extend_s` (or the original `lease_s`) for every leased sandbox of your organisation that matches.

- Heartbeat and drain select by `run_id`, `labels` or `ids`. Drain needs at least one, so it can never delete everything by accident.

- Lapsed leases are deleted by the same expiry job as TTLs.

In Python, a run does both: inside `with Run(cloud, "name")` (or `async with AsyncRun(cloud, "name")`) every sandbox made is labelled with the run and leased, a background thread heartbeats, and the run is drained when the block ends, the process exits or it gets SIGTERM. For sandboxes outside a run, `with kosa8.rl.lease(cloud, labels={"job": "exp-7"}):` does the same by label.

## Failure classes and masking

A rollout that died because a host was full is not evidence that the policy was wrong. Scoring it 0 teaches the model noise. Every error answer under `/v1/sandboxes`, and every exec, carries `failure_class` and `retryable`, so the trainer can tell the two apart:

| failure_class | When | retryable | What the trainer does |
|---|---|---|---|
| `ok` | Exec finished with exit 0. | — | Score it. |
| `exit_nonzero` | Exec finished with a non-zero exit. | — | Score it: this is the policy's result. |
| `timeout` | `exec_timeout` and other time limits. | no | Usually the policy's fault (a hang); decide per task. Raise `timeout_s` if it is the task's. |
| `oom` | Exit 137 and the guest kernel killed for memory (its `oom_kill` count rose). A grade gets no reward. | no | Decide per task: give the sandbox more memory (`mem_mb` or a larger size) if the task needs it; mask it to keep it out of the batch. |
| `infra` | Host failed, sandbox not ready, 5xx, no capacity, host gone. | yes | **Mask**: leave it out of the advantage, retry it. |
| `quota` | Running or plan limits, **402** payment, **429** rate limit. | only 429 | Mask and slow down; a plan limit needs the person to act. |
| `client` | **400** `invalid_*`, **404**, **409**. | no | A bug in the caller: fix the request. |

```
r = await sbx.exec(["sh", "-c", cmd])
if r.failure_class in ("infra", "quota"):
    rollout.masked = True          # not reward 0: dropped from this step's batch
elif r.failure_class == "timeout":
    rollout.reward = 0.0
```

A 503 `no_capacity` is `infra`, not a plan limit: wait the seconds in `Retry-After` and retry.

## The sealed grader

Reward hacking starts with a policy that can see or edit the tests, or reach the internet for an answer. `POST /v1/sandboxes/{id}/grade` forks one child from the solved sandbox, denies the child all egress, writes your hidden files into it, runs the grader, and deletes the child. The solver sandbox never sees the hidden files.

```
curl -s -X POST https://api.kosa8.com/v1/sandboxes/sbx_…/grade \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H 'Content-Type: application/json' \
  -d '{"cmd": ["python3", "/grader/test_hidden.py"],
       "files": {"/grader/test_hidden.py": "'"$(base64 < test_hidden.py | tr -d '\n')"'"},
       "timeout_s": 90, "run_id": "run_…", "rollout": {"step": 12, "group": "prompt-41", "index": 3}}'
# {"reward":1,"metrics":null,"reward_from":"exit","exit":0,"stdout":"passed\n","stderr":"",
#  "failure_class":"ok","retryable":false,"ms":1037,"grader_id":"sbx_…","kept":false,"sandbox_id":"sbx_…",
#  "grader_fingerprint":"sha256:…","run_id":"run_…","recorded":true}
```

Here `test_hidden.py` is a plain script that exits non-zero when the solution is wrong:

```
import sys
sys.path.insert(0, "/workspace")
from solution import add
assert add(2, 3) == 5 and add(-1, 1) == 0
print("passed")
```

The grader runs in a copy of the solved sandbox, with no network, so it can only use what that sandbox already has. The python template has pytest, so a grader can also be a test file run with `{"cmd": ["python3", "-m", "pytest", "-q", "/grader"]}`: exit 0 (every test passed) is reward 1.0.

- **Reward:** the last line of stdout that is JSON with a numeric `reward` (and an optional `metrics` object), for example `{"reward": 0.75, "metrics": {"passed": 3}}`. With no such line, exit 0 is 1.0 and any other exit is 0.0.

- `timeout_s` is 1 to 90 seconds; a longer grader is refused with **400**.

- `stdout` and `stderr` come back as their last 64 KiB.

- `keep: true` keeps the graded child for inspection.

- With `run_id`, the result is recorded as a rollout of that run.

## RL runs

A run groups the sandboxes and rollouts of one training job, so you can see it and export it.

| Call | Does |
|---|---|
| `POST /v1/rl/runs` | Start a run: `{name, project?, config?}`. |
| `GET /v1/rl/runs` | List runs (`?project=`, `?status=`) with summary counts. |
| `GET /v1/rl/runs/{id}` | The run, its summary (rollouts, by failure class, reward mean, p50, min and max overall and per step, live sandboxes against the plan limit, sandbox-hours and cost so far, rollouts a minute) and its [recommended actions]. |
| `PATCH /v1/rl/runs/{id}` | Rename, or set `status` to `finished` or `failed`. |
| `POST /v1/rl/runs/{id}/rollouts` | Record up to 500 rollouts a call: step, group, index, sandbox, reward, failure class, exit, duration, tokens, cost, meta. |
| `GET /v1/rl/runs/{id}/rollouts` | Page through them, filtered by `step`, `failure_class` or `min_reward`. |
| `GET /v1/rl/runs/{id}/export?format=jsonl` | Every rollout, streamed as JSON lines. |

Reading needs the `sandboxes:read` scope; changing needs `sandboxes:write`.

### The dashboard page

In [app.kosa8.com](https://app.kosa8.com/), **RL runs** lists every run with its status, rollouts, success rate, mean reward, infra failure rate, live sandboxes and cost. A run's page shows:

- Tiles for rollouts, mean reward, success rate, infra failures, live sandboxes against your limit, cost so far, cost per step and rollouts a minute.

- Reward by step (mean, with the min-max band) and failures by class for each step.

- A rollout table you can filter by step, failure class and reward. Click a row for its reward, metrics, exit, duration, stdout tail and meta, and, while its sandbox still exists, a terminal and a **Fork this state** button.

- **Export JSONL**, **Drain run sandboxes** (asks first) and **Mark finished**. A running run refreshes every 5 seconds.

### Recommended actions

The top of the run page lists what to fix, worked out from the run's own numbers. Each shows only when the data supports it:

| When | It suggests |
|---|---|
| Infra failures are over 5% of the last 500 rollouts. | Mask infra failures and retry (see [failure classes]). |
| Timeouts are over 10%. | Raise `timeout_s` or split the task; it shows the current p95 duration. |
| Live run sandboxes are at 90% or more of the plan's running limit. | You are at your concurrency limit: a pack of +10 running at once, or a bigger plan. |
| Sandbox-hours used are at 80% or more of the plan's allowance. | Add sandbox-hours: a pack of +100 a month. |
| The run is finished but its sandboxes are alive, or nothing was recorded for 15 minutes. | Drain the idle sandboxes. |
| Run sandboxes have no lease. | Use `lease()` so a crashed trainer does not leak sandboxes. |
| Reward has not changed over the last 50 steps. | Check the grader, with a sample rollout to open. |
| Rollouts were scored outside `/grade`. | Grade in a sealed fork to stop reward hacking. |

## Adapters

The `kosa8.rl` module plugs kosa8 sandboxes into the common RL frameworks. Each adapter imports its framework only when you use it, so `kosa8` does not depend on any of them.

| Module | For | What it gives you |
|---|---|---|
| `kosa8.rl.gym` | Gymnasium | An `Env` whose `reset()` makes or forks a sandbox and whose `step(action)` runs a shell action in it. |
| `kosa8.rl.openenv` | OpenEnv | An OpenEnv-compatible environment with `reset`, `step` and `state`. |
| `kosa8.rl.verifiers` | Prime Intellect `verifiers` | A `SandboxEnv`-style provider backed by kosa8 Cloud. |
| `kosa8.rl.trl` | TRL `GRPOTrainer` | An `environment_factory` helper. |
| `kosa8.rl.nemo_gym` | NeMo Gym | A sandbox provider (`Kosa8Provider`), found through the `nemo_gym.sandbox_providers` entry point. |
| `kosa8.rl.swebench` | SWE-bench | Create from an instance's image, apply the model's patch, grade with the hidden tests through the sealed grader. |

Worked examples (`quickstart.py`, `async_rollouts.py`, `grpo_trl.py`, `swebench_grade.py`, `verifiers_env.py`) are in the SDK's [`examples/rl/`](https://github.com/kosa8ai/kosa8-py/tree/main/examples/rl) folder.

## Run health signals

A run's page in the web app and the desktop app checks the run for four problems as it goes. Each shows with a severity and a link back here. `GET /v1/rl/runs/{id}` returns them in `recommendations`, with ids `reward_hacking`, `grader_changed`, `timeouts_rising` and `group_no_signal`.

### Reward hacking

Mean reward rose while rollouts got much shorter or produced much less output. A policy that scores more by doing less is often gaming the grader: it deletes the failing tests, prints what the checker looks for, or exits early. Read a few of the newest high-reward rollouts in the rollout drawer before you trust the curve. A sealed grader with hidden tests ([above]) closes most of these holes.

### Grader fingerprints

Every rollout scored by the sealed grader records a fingerprint of the grader command and its hidden files. Hosted [jobs](https://docs.kosa8.com/guides/cloud-jobs/) do too. When you grade yourself, send `grader_fingerprint` on the rollout (any id up to 128 characters, such as a commit hash of your tests). When a run has more than one fingerprint, the grader changed mid-run, so rewards before and after are not the same measure. Compare runs within one grader, or start a new run.

### Timeouts

The share of rollouts with failure class `timeout` is rising step by step. A policy that learns to run longer, or an environment that got slower, pushes rollouts past `timeout_s`. Read the newest timed-out rollouts, then cap the episode length or raise `timeout_s`. Timed-out rollouts carry no reward, and you can mask them.

### GRPO groups with no signal

In most recent groups, every rollout got the same reward. GRPO learns from the differences within a group, so a group of all 0s or all 1s adds nothing. Give partial credit, pick tasks of the right difficulty for the current policy, or sample more rollouts per group.

### Alerts

Rules at `/v1/rl/alerts`, also on a run's page, fire when infrastructure failures pass a rate, out-of-memory kills spike, cost passes a budget, or a run stops producing rollouts. They are checked every minute, at most once an hour per rule. Each one is sent as the `rl.alert` webhook, so subscribe an endpoint to that event.

## Limits

From the plans in [pricing](https://kosa8.com/pricing/#compare). Limits are hard: past one, new work is refused with **402** `plan_limit`. The limits apply from December 2026. Plan prices are on [the pricing page](https://kosa8.com/pricing/).

|  | Solo | Pro | Team | Scale |
|---|---|---|---|---|
| Sandboxes running at once | 2 | 10 | 25 | up to 1,000 |
| Cloud sandbox-hours a month | 100 | 500 | 500 a person, pooled | 1,000 a person, pooled |
| Largest sandbox | 2 vCPU, 4 GB | 4 vCPU, 8 GB | 8 vCPU, 16 GB | 16 vCPU, 32 GB |
| Snapshots kept | 5 | 50 | 250 | 1,000 |

- **Packs**, monthly, on any plan, stackable: +100 sandbox-hours, or +10 sandboxes running at once (prices on [the pricing page](https://kosa8.com/pricing/)).

- A sandbox-hour is an hour of a 2 vCPU / 4 GB sandbox; bigger sizes count by vCPU, so a 4 vCPU sandbox uses 2 an hour.

- Fork makes at most 1,000 copies a call, 100 at a time, on the parent's host and then on others. One host holds about 1,000 light copies, or about 700 to 770 that each write about 150 MiB of memory ([fork]).

- An exec answered as one JSON object runs at most 90 seconds; stream longer commands (`"stream": true`) or run them in the background.

- Region: `us-ash1` (Ashburn, Virginia, US) is the only live region. Overflow capacity reports region `cf-auto`.

- kosa8 Cloud has no GPUs. Run the policy and trainer on your own GPUs and the environments on kosa8 Cloud.

## What a run costs

Arithmetic only, from the plan limits above; for the dollar figures, see [the pricing page](https://kosa8.com/pricing/). 10,000 rollouts of 3 minutes each on the standard 2 vCPU sandbox:

```
10,000 rollouts x 3 min = 30,000 sandbox-minutes = 500 sandbox-hours
```

- **Pro:** 500 sandbox-hours are included, so this run uses the month's allowance. A second run of the same size takes 5 packs of +100. At 10 running at once it takes 10,000 / 10 x 3 min = 50 hours of wall-clock time.

- **Scale:** 1,000 sandbox-hours a person are included, room for two such runs. At 1,000 running at once it takes 10 rounds of 3 minutes, 30 minutes of wall-clock time, plus the time to make the sandboxes (a fork of 999 takes about a minute).

- On 4 vCPU sandboxes the same run is 1,000 sandbox-hours.

The figures leave out create and grading time, retries and anything else the plan is used for; the run page shows the real sandbox-hours and cost as the run goes.

## See also

- [RL rollouts and evals in Python](https://docs.kosa8.com/guides/py-rl-eval/): the loop with calls that are live today.

- [Hosted jobs](https://docs.kosa8.com/guides/cloud-jobs/): kosa8 runs the rollouts for you.

- [Benchmarks](https://docs.kosa8.com/guides/benchmarks/): SWE-bench Verified and Terminal-Bench, ready-made.

- [kosa8 Cloud](https://docs.kosa8.com/guides/cloud/): keys, limits, errors and regions.

- [Snapshots, background commands and env](https://docs.kosa8.com/guides/cloud-snapshots-background/).

- [Egress controls](https://docs.kosa8.com/guides/cloud-egress/).

- [The best sandbox for reinforcement learning](https://kosa8.com/best/reinforcement-learning/).

---
Source: https://docs.kosa8.com/guides/rl-training/
