# Hosted jobs

Send a list of tasks, the command that solves one and the command that grades it. kosa8 Cloud runs every rollout on its side: a sandbox per task, the solver for as long as it needs, the sealed grader, retries for infrastructure failures, and a record of each rollout in an [RL run](https://docs.kosa8.com/guides/rl-training/#runs). Nothing has to stay running on your machine.

## What a job does with each task

1. **A sandbox.** Made from the job's `template`, `image` or `snapshot` (and `size`), labelled with the job's run, and leased: if kosa8's driver ever stopped, the sandbox would go by itself after `lease_s`.

2. **The task's input.** `input` (any JSON, up to 32 KiB) is written to `/workspace/.kosa8-task/input.json` and given to the solver as `KOSA8_TASK_INPUT`; the task's `files` are written where they say.

3. **The solver.** `solver.cmd` runs as a background command, polled until it exits, so it can run for hours (`timeout_s` up to 24 hours). It also gets `KOSA8_TASK_ID`, `KOSA8_TASK_INPUT_FILE`, `KOSA8_JOB_ID`, `KOSA8_RUN_ID` and `KOSA8_ATTEMPT`.

4. **The sealed grader.** A copy of the solved sandbox with no network gets the hidden `grader.files`, which the solver never sees, and runs `grader.cmd` (up to 90 s). The reward is the last stdout line that is JSON with a numeric `reward` (`{"reward": 0.75, "metrics": {...}}`), else 1 for exit 0 and 0 otherwise. See [the sealed grader](https://docs.kosa8.com/guides/rl-training/#grader).

5. **The rollout.** Recorded to the job's run with step 0, group = the task's id, the reward and the failure class. The sandbox is deleted.

## Failures

| What happened | What the job does |
|---|---|
| Infrastructure: a host failed, the sandbox was lost, the grader could not run | Deletes that try's sandbox and tries the task again, up to `retries_on_infra` more times (default 2). After that the rollout is recorded with `failure_class: "infra"`, no reward and `meta.masked: true`, never as reward 0. |
| The solver was killed for memory | Recorded as `oom`, no reward. Use a larger `size`. |
| The solver ran past `timeout_s` | Recorded as `timeout`, no reward. |
| The solver exited non-zero | Still graded: the grader decides the reward. |
| The org is at its running limit, or no host has room | The task waits in the queue; no try is used. |
| A refusal every task would meet: no payment method, an unknown template, a host that cannot seal the grader | The job stops with status `failed` and the reason in `error`. |

## Submit a job

A job that runs as it is: each task asks for the sum of two numbers, the solver writes its answer to `/workspace/answer.txt`, and a hidden grader checks it. The `python` template is Python 3.12 on Debian with `bash`, `git`, `pip`, `pytest` and `uv`; both commands here need only `python3`. The grader, `tests/test.py`:

```
import json
task = json.load(open("/workspace/.kosa8-task/input.json"))
got = open("/workspace/answer.txt").read().strip()
print(json.dumps({"reward": 1.0 if got == str(task["a"] + task["b"]) else 0.0}))
```

Write the body to a file (the heredoc fills in the grader as base64), then submit it:

```
cat > job.json <<EOF
{"name": "sum-eval-1", "project": "demo", "template": "python",
 "tasks": [{"id": "sum-1", "input": {"a": 2, "b": 3}}, {"id": "sum-2", "input": {"a": 10, "b": -4}}],
 "solver": {"cmd": "python3 -c \"import json, os; t = json.loads(os.environ['KOSA8_TASK_INPUT']); open('/workspace/answer.txt', 'w').write(str(t['a'] + t['b']))\"",
            "timeout_s": 120},
 "grader": {"cmd": "python3 /hidden/test.py", "timeout_s": 60,
            "files": {"/hidden/test.py": "$(base64 < tests/test.py | tr -d '\n')"}},
 "concurrency": 4, "retries_on_infra": 2, "budget_usd": 1}
EOF
curl -s https://api.kosa8.com/v1/jobs \
  -H "Authorization: Bearer $KOSA8_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" -d @job.json
# 202 {"job_id": "job_…", "run_id": "run_…", "job": {"status": "queued", …}}
# a few seconds later, GET /v1/jobs/job_… says "status": "done", and both rollouts have reward 1
```

A real job puts your agent in the solver (`"cmd": "python /opt/agent/solve.py"` in a [template](https://docs.kosa8.com/guides/templates/) or snapshot that has it) and your hidden tests in the grader. The grader's `timeout_s` is at most 90, and it runs with no network, so it can use only what the sandbox already has. The `python` template has pytest, so `"cmd": "python3 -m pytest -q /hidden"` works as a grader there (exit 0 is reward 1); anything else the grader needs goes in the template or snapshot. The solver's `files` field is used only by [benchmark](https://docs.kosa8.com/guides/benchmarks/) jobs; for your own jobs, put the solver in the template, or in each task's `files`.

- `tasks`: 1 to 10,000, each `{id, input?, files?}` (files up to 256 KiB a task). `tasks_url` is reserved for a JSONL file in organization storage and answers 501 until that exists.

- `concurrency`: tasks in flight at once (default 16). At most your plan's running limit less one: one place is kept for a grader's sealed copy, so a full organization still grades what it solved.

- `lease_s`: each task sandbox's lease, 120 s to 24 hours (default 900).

- `budget_usd`: the job stops with status `budget_reached` once its list cost reaches this, and drains its sandboxes.

- An `Idempotency-Key` header makes a retried submit return the first job instead of starting a second.

## Watch, list and cancel

| Call | Does |
|---|---|
| `GET /v1/jobs/{id}` | Status (`queued`, `running`, `done`, `failed`, `cancelled`, `budget_reached`), counts by state (queued, running, done, masked, cancelled), counts by failure class, progress, mean reward, cost so far, sandbox-hours and an ETA. |
| `GET /v1/jobs` | The organization's jobs, newest first (`?status=`, `?project=`, `?cursor=`). |
| `POST /v1/jobs/{id}/cancel` | No new rollouts; every sandbox of the job is drained. Rollouts already recorded stay in the run. |
| `GET /v1/rl/runs/{run_id}/rollouts` | The rollouts themselves; `…/export?format=jsonl` streams them all. |

The job's RL run is a normal run: its page in [app.kosa8.com](https://app.kosa8.com/) shows reward, failures and cost as the job goes.

## Estimate first

`POST /v1/jobs/estimate` takes the same body (or `task_count` instead of `tasks`) and answers a range:

```
{"tasks": 1000, "basis": "timeout",
 "per_task_s": {"low": 480, "high": 1890},
 "sandbox_hours": {"low": 133.333, "high": 525}, "usd_list": {"low": …, "high": …},
 "size": "2x4", "vcpus": 2, "mem_mb": 4096, "included_hours_left": 812.5, "note": "From the solver's timeout: …"}
```

- **From the timeout** (the default): each task takes from 30 s plus a quarter of the solver's `timeout_s`, to 30 s plus the solver's and the grader's full `timeout_s`.

- **From a sample:** send `sample: n` (1 to 50) to start a pilot job of the first `n` tasks (answered 202 with its `sample.job_id`). Once it has finished, estimate again with `sample_job_id`: the range is then tasks × the pilot's measured p50 to p90.

- Sandbox-hours are counted by vCPU, as the plan counts them (a 4 vCPU size uses 2 an hour), and dollars are at list rates. On a plan, usage is included up to its sandbox-hours; `included_hours_left` is what this month has left (`null` while the plan's limits do not apply yet: they apply from December 2026, or to an account with no plan limits).

- Retries are not in the estimate.

## Python

The same job from Python, with the tasks in `tasks.jsonl` (one a line, for example `{"id": "sum-1", "input": {"a": 2, "b": 3}}`) and the grader above in `tests/test.py`:

```
from pathlib import Path
from kosa8 import Kosa8Cloud

SOLVER = {"cmd": "python3 -c \"import json, os; t = json.loads(os.environ['KOSA8_TASK_INPUT']); "
                 "open('/workspace/answer.txt', 'w').write(str(t['a'] + t['b']))\"",
          "timeout_s": 120}
GRADER = {"cmd": "python3 /hidden/test.py", "files": {"/hidden/test.py": Path("tests/test.py")}}

cloud = Kosa8Cloud()
est = cloud.jobs.estimate(name="sum-eval-1", template="python", tasks="tasks.jsonl", solver=SOLVER, grader=GRADER)
print(est["usd_list"])                                             # {'low': 0, 'high': 0.01}
job = cloud.jobs.submit(name="sum-eval-1", template="python", tasks="tasks.jsonl", solver=SOLVER, grader=GRADER,
                        concurrency=4, budget_usd=1)
final = cloud.jobs.wait(job["id"], progress=lambda j: print(j["progress"]["done"], "/", j["tasks"]))
print(final["status"])                                             # done

from kosa8.rl import Run
page = Run.attach(cloud, final["run_id"]).rollouts()               # {"rollouts": [...], "next_cursor": ...}
print([r["reward"] for r in page["rollouts"]])                     # [1, 1]
```

`rollouts()` returns one page, `{"rollouts": [...], "next_cursor": ...}`; `rollouts(as_="pandas")` returns a DataFrame and needs pandas (`pip install pandas`).

## CLI

**An API key is enough**

`kosa8 job` run on kosa8 Cloud, so they use your organization's plan through your API key: `KOSA8_API_KEY`, `kosa8 cloud login` or the browser sign-in, `kosa8 login`. This needs CLI v0.21.0 or later. Older versions asked for a plan on this machine even on a paid plan; there, use the HTTP API or the Python SDK above, which work with the key.

```
kosa8 job submit tasks.jsonl --template python \
  --solver "python /opt/agent/solve.py" --solver-timeout 30m \
  --grader "python3 /hidden/test.py" --grader-file tests/test.py:/hidden/test.py \
  --concurrency 64 --budget 20 --estimate      # prints the range, submits nothing
kosa8 job submit tasks.jsonl … --watch          # submit, then a live progress line
kosa8 job ls
kosa8 job get job_…
kosa8 job watch job_…                           # running  done 120/1000 (12%)  running 64  masked 3  reward 0.42  $1.23  eta 4m10s
kosa8 job cancel job_…
```

`tasks.jsonl` has one task a line: `{"id": "…", "input": {…}, "files": {"/path": "<base64>"}}`. The CLI's `--solver` and `--grader` run with `sh -c`.

## How it runs

kosa8's minute tick drives every active job, and a submit starts its job at once. Every step is kept in the control plane's database before it is taken, so a restart of kosa8's side resumes the job where it was, and each try of a task is recorded at most once. Each task's sandbox counts toward your running limit and is billed like any other sandbox; the job's cost is what its run's sandboxes used.

## See also

- [Benchmarks](https://docs.kosa8.com/guides/benchmarks/): a job of SWE-bench Verified or Terminal-Bench, with its official grader.

- [RL training](https://docs.kosa8.com/guides/rl-training/): runs, failure classes, the sealed grader.

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

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

---
Source: https://docs.kosa8.com/guides/cloud-jobs/
