Guide · Reinforcement learning
How do I build an RL environment rollout loop on sandboxes?
Updated
Prepare the environment once in a kosa8 template and a base sandbox with the network closed. Then wrap it in a small environment class: reset() forks the base into a fresh live copy, step() runs the policy's shell command in that copy with a time limit, and reward() copies in a grader the policy never saw and scores the exit code. Run many episodes at once from a thread pool and delete each copy when its episode ends.
01Steps
Install kosa8 and the Python SDK. Forks need a plan; your plan sets how many copies run at once.
Put the task in a template. Bake the repository and its dependencies into the image so episodes need no network.
FROM python:3.12-slim RUN apt-get update && apt-get install -y --no-install-recommends git && rm -rf /var/lib/apt/lists/* RUN git clone https://github.com/pallets/click /repo && pip install --no-cache-dir -e /repo pytest
Create the base with the network closed. Forks inherit the base's network policy, so with
--egress denyno episode can download an answer.Write the hidden grader. Keep
hidden_tests.pyon your side. It is written into each copy only after the episode, so the policy cannot read or edit it.Wrap it in an environment and run rollouts.
resetforks,stepruns one command with a 120-second limit,rewardruns the grader. Replacescripted_policywith a call to your model.from concurrent.futures import ThreadPoolExecutor from kosa8 import Kosa8Client client = Kosa8Client() BASE = "env-base" GRADER = open("hidden_tests.py").read() # stays on your side until the episode ends class SandboxEnv: """One episode = one fork of the prepared base.""" def __init__(self, tag): self.tag, self.sid = tag, None def reset(self): self.close() self.sid = client.fork(BASE, 1, prefix=f"{self.tag}-")["forks"][0]["id"] return client.shell(self.sid, "cd /repo && git status --short && ls").stdout def step(self, command): r = client.shell(self.sid, command, timeout_s=120) return (r.stdout + r.stderr)[-8000:], r.exit_code, r.timed_out def reward(self): client.write_file(self.sid, "/workspace/.grader/test_hidden.py", GRADER) r = client.shell(self.sid, "cd /repo && python -m pytest -q /workspace/.grader", timeout_s=300) return 1.0 if r.ok else 0.0 def close(self): if self.sid: client.delete_sandbox(self.sid) self.sid = None def rollout(tag, policy, max_steps=20): env = SandboxEnv(tag) try: obs, trajectory = env.reset(), [] for _ in range(max_steps): command = policy(obs, trajectory) # your model: next shell command, or None to stop if command is None: break obs, exit_code, timed_out = env.step(command) trajectory.append((command, exit_code, timed_out)) return trajectory, env.reward() finally: env.close() def scripted_policy(obs, trajectory): # replace with your model plan = ["cd /repo && python -m pytest -q -x 2>&1 | tail -5"] return plan[len(trajectory)] if len(trajectory) < len(plan) else None with ThreadPoolExecutor(8) as pool: results = list(pool.map(lambda i: rollout(f"ep{i}", scripted_policy), range(8))) print("mean reward", sum(r for _, r in results) / len(results))
Branch inside an episode when the policy searches. To try a risky action and undo it, checkpoint the episode's copy first and rewind if it fails. The rest of the episode is unaffected.
client.checkpoint(env.sid, label="before migration") out, exit_code, _ = env.step("cd /repo && ./migrate.sh") if exit_code != 0: client.rewind(env.sid) # disk and memory back to the checkpoint
02Design notes
- Reset is a fork. Forking snapshots the base once and restores a copy with memory, processes and disk intact, so the shell, the installed packages and any warm server are already there.
- Observations are text. The tail of stdout and stderr is a simple observation; return structured data from your own commands if your policy needs it.
- Time limits keep the batch moving. A command past
timeout_sreturns withtimed_out=Truerather than blocking. - Partial rewards. Have the grader print JSON and parse
r.stdoutinstead of using the exit code. - Reward hacking. Every command a policy ran is in kosa8's audit log, which is the first place to look when a reward looks too good.
03How far it scales
Each episode is a microVM with its own memory, so one machine runs as many at once as its RAM allows and your plan's limit on copies permits. kosa8 has not published rollout throughput benchmarks; measure on your hardware. For thousands of concurrent episodes, a hosted fleet may fit better; see the best sandbox for RL for the trade-offs.
04FAQ
Why fork instead of rewinding one sandbox between episodes?
Forks run in parallel and each episode gets its own machine. Rewind fits search within one episode, where the policy backs out of a step.
Can the policy see the grader?
No. The grader stays on your side and is written into the copy with write_file only after the episode's last step.
Does this work with Gymnasium?
The class follows the same reset and step shape, so it can sit behind a Gymnasium-style interface; the observations and actions here are text.
How do I avoid leaving copies behind?
rollout() deletes its copy in a finally block. As a backstop, create sandboxes with ephemeral=True or a ttl_min from the Python SDK.
05Get started
Install kosa8 on a Mac, Linux or Windows (WSL2) machine, or make an account and run the same sandboxes on kosa8 Cloud.
06Sources
- kosa8 docs: RL rollouts and evals (Python)
- kosa8 docs: Checkpoints and rewind
- kosa8 docs: Python quickstart
- Gymnasium documentation
- kosa8 command reference
Related
- The best sandbox for reinforcement learning environments
- How do I run SWE-bench-style evals in parallel sandbox forks?
- The best sandbox for running AI agents in parallel
- How do I try several AI agent approaches in parallel?
- How do I undo what an AI coding agent did?
Updated 2026-11-14