RL Environments: From Gym to Environment Factories

Deep dive · Agentic RL · Infrastructure

RL Environments: From Gym to Environment Factories

How simulated environments for agentic reinforcement learning are specified, built, synthesized, run at scale, and turned into training data.

RL EnvironmentsAgentic RLVerifiersSandboxesRollout SystemsTraining Data

Summary

  • An RL environment is a bundle of five parts: a task distribution, a stateful world, an action interface, a verifier and a harness. Two properties decide whether its rewards mean anything: reset semantics and isolation. The same bundle serves RL, evaluation and supervised-trajectory generation. That reuse is efficient, and it is also the root of train/eval leakage (What an RL Environment Is).
  • Environments became a purchased input to post-training in 2025–2026. Epoch AI's interviews put most tasks at $200–$2,000 each. Open projects (Prime Intellect's Environments Hub, OpenEnv, Harbor, NeMo Gym) turned environments into versioned, shareable packages (Introduction, Standards and Hubs).
  • There are four ways to get an environment: build it by hand, mine it from real software, synthesize it, or let a model simulate it. For mining, SWE-smith made about 50,000 tasks from 128 repositories. For synthesis, Agent World Model generates 1,000 database-backed tool environments. Early scaling studies suggest that the number and diversity of environments matter more than tasks per environment (Mining, Synthesis).
  • The verifier is the specification the policy actually learns. Hacking rates depend on how much of the grader the environment exposes. METR saw hacking in 30.4% of reviewed runs where scoring code was visible, against 0.7% where it was not. The standard defenses are read-only tests, a fresh grading sandbox and a verifier test suite that checks both directions (Verifiers and Rewards).
  • At scale, sandboxes are the throughput limit, and image handling dominates their cost. Production rollout systems split inference, environments and training into separate services. They run asynchronously with bounded staleness (a cap on how many policy versions old a sample may be). They label infrastructure failures instead of scoring them, and they capture tokens and sampler log-probabilities at a gateway (Sandboxes, Rollout Systems, Capture).
  • Rollouts become data only with their versions pinned. Curation keeps mixed-outcome groups, retires saturated tasks and keeps failures for verifiers and monitors. Evaluation holds out whole environment families. A revision of Terminal-Bench moved one agent's score by about 12 points with no model change (Data Model, Train/Eval Separation).

Key Concepts

The core ideas of this book, one card each: a definition, an explanation from basics, why it matters, a common misconception and a diagram. Click a card, or any dotted-underlined term with a badge in the text, to open it in the side panel. To add your own, highlight any phrase and choose Key Concept.

One-Pager: An Environment Program End to End

An environment program turns a capability target into executable tasks. It runs a policy against them in isolated sandboxes and scores the results with verifiers. It then turns the scored episodes into policy updates and evaluation numbers.

This page puts the program on one screen:

  • the decisions, in the order they arise;
  • the system that runs an episode;
  • the main verifier, sandbox and framework options;
  • the order in which to build.

Each item links to the section that argues for it. The full reference architecture is in Reference Architecture, and the detailed playbook is in Playbook.

The Decisions, in Order

Ten decisions shape an environment program. Most mistakes come from taking them out of order, for example scaling the sandbox fleet before any environment has been shown to move the evaluation. Each row gives the default the book argues for and the condition that justifies a different choice.

#DecisionDefaultDeviate whenRead
1Target and held-out evaluationName the capability, pick its evaluation first, and hold out whole environment families, not tasksThe claim is only about one environment (then held-out tasks suffice)Target, Held-out families
2Source of environmentsMine where real software and tests exist; synthesize database-backed tool environments for breadthA high-value workflow needs product fidelity (buy or hand-build a replica); state is soft and expensive to execute (simulate users or rare APIs)Hand-built, Mined, Synthesized, Simulated
3VerifierExecutable check of the end state or hidden tests, binary headline reward, collateral-damage checkThe output is open-ended: add a rubric judge for what code cannot see, and keep the code check as the anchorKinds of verifiers, Partial credit
4Who owns the loopEnvironment-owned loop with a simple built-in scaffold while the program is youngThe deployed product is a specific harness: run it unmodified and capture through a gatewayWho owns the loop
5Packaging standardAdopt an existing task format and library (Harbor tasks, Verifiers, OpenEnv, NeMo Gym) rather than a private oneAn existing trainer already fixes the interface; still keep tasks importableStandards and Hubs
6IsolationStrong enough for what the agent may do: containers for trusted, dependency-light tasks; microVMs when the agent runs as root or code is untrustedDesktop or GPU tasks need full VMs; design snapshots for resetIsolation options, Isolation
7Rollout modeAsynchronous with a bounded staleness and recorded policy versionsShort, uniform episodes or debugging a new algorithm: synchronous is simpler and exactly on-policySync and async, Long tail
8Trajectory captureToken-in/token-out at the inference gateway, with sampler log-probabilities, never retokenized textNone for RL; text-only traces are acceptable for SFT data and debuggingCapture, Gateway
9Data model and curationLight episode metadata plus heavy token payloads; every version pinned; keep mixed-outcome groupsOffline SFT or distillation: select by quality and diversity, and keep failures for verifiersData model, Curation
10OperationsPer-environment-version dashboards, trace review of rising-reward episodes, exact replayEnvironments touch live services: add drift monitors and pinned mirrorsObservability

Table. The design decisions of an environment program in the order they arise, each with the default argued for in the linked section and the condition for deviating from it.

The System on One Screen

One episode crosses three bands of the system. The top row runs it, the middle row records it, and the bottom row learns from it and checks the result. Three rules hold throughout:

  • Separation. The agent's sandbox never holds the verifier's material.
  • Capture. Model calls pass through a gateway that records tokens.
  • Joining. The trajectory store joins rewards, tokens and versions before anything reaches the trainer.
An environment program on one screen. Top row: task store, environment registry, sandbox, agent loop and verifier. Middle row: inference engine, gateway and trajectory store. Bottom row: evaluation harness, trainer and curation, with weights flowing back to the inference engine. Task store tasks · seeds train / held-out Env registry image · tools verifier @ version Sandbox reset · isolate no hidden tests Agent loop policy + harness tools · MCP · shell Verifier fresh sandbox state or tests Inference engine samples tokens policy version Gateway token ids in / out sampler logprobs Trajectory store episodes · tokens versions · labels Eval harness held-out families Trainer policy update Curation pass-rate band model calls reward or infra label held-out tasks new weights curated groups checkpoints
Fig. An environment program on one screen. The top row runs one episode from a versioned task to a verdict; the verifier returns a reward, or an infrastructure label when it could not score. The middle row records exact tokens through the gateway and joins them with rewards and versions. The bottom row curates, trains, returns new weights to the inference engine and measures checkpoints on held-out families. The rollout orchestrator that drives the top row is left implicit; it leases sandboxes, enforces budgets and retries infrastructure failures. Reference Architecture draws every component.

Verifier, Sandbox and Framework Choices

The three most consequential technology choices are how success is checked, how episodes are isolated, and which library packages the environment. None has a universal winner. Each option fits a kind of task and fails in a characteristic way.

LayerOptionFitsWatch for
VerifierHidden testsSWE and terminal tasks with tests that detect the fixTest tampering and flaky tests; copy tests in after the agent exits and repeat runs (Reward hacking)
End-state checkTool, web and enterprise tasks backed by a database or filesystemShortcut end states and collateral damage; check that nothing else changed (State check)
Rule or exact matchMath, puzzles, single-turn answersCorrect answers in other forms scored wrong, more often as policies improve (Kinds of verifiers)
Rubric plus LLM judgeOpen-ended outputs and constraints code cannot seeJudges persuaded by style or adversarial text; keep a code-checked headline (Kinds of verifiers)
SandboxContainers or rootless namespacesTrusted clusters, dependency-light SWE and terminal tasks, highest densityShared kernel; run inside a VM when tenants or code are untrusted (Isolation options)
User-space kernel (gVisor)Multi-tenant Kubernetes poolsSystem-call overhead and compatibility gaps
MicroVM (Firecracker, Kata)Untrusted code and agents with rootStart-up dominated by moving images; use snapshots and warm pools (Cold start)
Full VMDesktop, GUI and GPU environmentsSlow reset; density low (Image economics)
FrameworkOpenEnvA shared protocol: reset, step and state over the network, MCP tools, one image per environmentNo opinion on rewards or training loops (Main projects)
Verifiers and the Environments HubAuthoring environments with rubric rewards, split into taskset, harness and runtimeTied most closely to Prime Intellect's trainer and hub
HarborRunning agent harnesses in containers on tasks with a tests/ verifierA task format and runner more than a training library
NeMo GymServing agent, model and resources servers; imports Harbor, OpenEnv and Verifiers environmentsIts own trajectory format; check portability of rewards
SkyRL-Gym, GEM, AtroposGym-style text and tool environments inside a given trainerCross-stack reward agreement is rarely measured (Hubs)

Table. The main options for verifiers, sandboxes and environment frameworks, what each fits and its characteristic failure. Facts about frameworks are from their own documents as summarized in Environment Standards and Hubs.

Build It Step by Step

The build order follows dependencies: each step produces something the next one runs against. Infrastructure is scaled only after a small environment has been shown to move the held-out evaluation.

  1. Fix the target and the held-out evaluation. Choose the capability, its evaluation and the environment families that will never be trained on. Record the baseline with error bars (Target, Held-out families).
  2. Write one small, stateful environment. End-state verification, a reset contract that covers hidden state, and verifier material outside the agent's reach (One environment, Reset, Isolation).
  3. Test the verifier in both directions. Reference solutions score 1. Null, claim-only, tampering, special-casing and collateral-damage agents score 0. A killed sandbox yields "not scored" (Verifier as a product, Audit).
  4. Put a gateway in front of the model and define the record. Record token ids and sampler log-probabilities per call. Record episode metadata with task, environment, verifier, harness and policy versions (Gateway capture, Data model).
  5. Calibrate difficulty. A pass-rate sweep with the current policy keeps tasks whose groups are likely to mix successes and failures (Pass-rate sweep, Zero-variance groups).
  6. Prove the loop on a pilot. Training reward rises, the held-out evaluation moves, and a sample of rising-reward traces shows real task completion (Pilot).
  7. Scale environment families. Mine, synthesize and buy, with every new environment passing the same acceptance checks and decontamination against the evaluation (Quality control, Contamination).
  8. Scale the run layer. Use shared images, snapshots and warm pools. Run rollouts asynchronously with bounded staleness. Label and retry infrastructure failures (Sandboxes, Rollout systems, Labeling failures).
  9. Operate. Dashboards per environment version, hacking detection over traces, drift monitoring, retirement of saturated tasks and new held-out families as training families grow (Operate, Observability).
If only one thing is built well

Build the verifier's own test suite. Every other component can be fixed after the fact by re-running or re-curating. Rewards from a verifier that accepts non-solutions are already inside the policy by the time anyone notices.

Expert Primer: Mental Models, Debates and Self-Test

This page condenses the book into what an expert carries around. It has three parts:

  • Five ideas that hold across math checkers, SWE repositories, synthesized tool worlds and desktop VMs.
  • Three live disagreements where informed practitioners still differ.
  • Ten questions that test whether the ideas can be applied rather than recited.

The page works as a map before reading and as a test afterwards.

Five Core Mental Models

Five ideas explain most design choices in the book. Together they say what an environment is for, what it actually teaches, which tasks are worth running, how to keep infrastructure out of the reward, and what has to be recorded for an episode to become training data.

1. Practice, not answers. An environment lets a model try, fail and be graded many times, where a label only tells it what to say.

One environment bundle (task distribution, world, action interface, verifier, harness) feeding three consumers: RL, evaluation and supervised trajectories. One environment task distribution world action interface verifier harness RL Evaluation Supervised trajectories trains measures generates data
Fig. Schematic. The same bundle serves three consumers. Because one artifact both trains and measures, train/eval leakage is the main hazard.
  • What it is. The environment is the bundle of task distribution, world, action interface, verifier and harness. The same bundle has three consumers: RL, evaluation and supervised-trajectory generation.
  • Why experts hold it. It explains the economics: labs buy practice the way they once bought labels. It also explains the main hazard: an artifact that trains a model can no longer measure it cleanly.
  • Design consequence. The task distribution is part of the objective. Re-weighting the mix changes what is optimized as surely as changing the reward.

See Introduction and What an RL Environment Is.

2. The verifier is the specification. Whatever the verifier accepts, including accepted non-solutions, is what the policy learns.

Two-by-two grid of verifier outcomes: real solution or non-solution against verifier accepts or rejects. False positives become reward hacks; false negatives become lost signal. Verifier accepts Verifier rejects Real solution Non-solution Correct reward policy learns the task False negative lost signal, looks like a plateau False positive reward hack is learned Correct zero no reward
Fig. Schematic. The policy learns whatever lands in the left column. The two highlighted cells are the error directions a verifier test suite must check.
  • Why. The effective task is defined by the grader, not by the prompt.
  • Two error directions. False positives (non-solutions accepted) become reward hacks. False negatives (real solutions rejected) become lost signal that later looks like a plateau.
  • Design consequence. Verifiers get their own test suites, versions and owners. Tests are kept out of the agent's reach, and a verifier change is treated as a reward change.

See Verifiers and Rewards and The Verifier as a Product.

3. Only the middle band teaches. Useful tasks sit in a band of intermediate pass rates.

Sketch of learning signal against a task's pass rate: zero at a pass rate of 0 and of 1, highest in a middle band where outcomes mix. learning signal the band moves as the policy improves middle band: outcomes mix no signal no signal 0 · none solve all solve · 1 pass rate of a task under the current policy
Fig. Schematic, not measured. Under group-relative methods, tasks at either end cost full rollout compute but give no signal.
  • Why. A task that every rollout solves, or that none does, produces no learning signal under group-relative methods (methods that score each rollout against the other rollouts of the same task). It still costs full rollout compute.
  • The band moves. The band shifts as the policy improves, so difficulty is measured rather than guessed.
  • Design consequence. Tasks are retired as they saturate, and generators with a difficulty knob outlast fixed pools.

See Zero-Variance Groups, Curricula and Calibrate Difficulty.

4. Label, don't score. Reward must vary only with the policy's behavior.

Flow: reset and isolation make episodes comparable and independent; an episode the verifier scored yields a reward for the update, and one it could not score gets an infrastructure label and is retried. Reset + isolation comparable, independent Episode ends Scored by the verifier? Reward enters the update Infra label retried, not zero yes no crash · failed pull · dead sandbox
Fig. Schematic. Only episodes the verifier could score reach the update. A crash scored as zero would teach the policy to avoid whatever it was doing.
  • Noise and poison. Anything else that moves the reward is noise or poison. Examples: a start state that differs between rollouts of the same task, a shared database corrupted by a neighbor, a sandbox that died, an image that failed to pull.
  • Three promises. Reset makes episodes comparable. Isolation keeps them independent and keeps answers out of reach. Infrastructure failures are labeled and retried rather than scored as zero.
  • Why not zero. A crash scored as failure teaches the policy to avoid whatever it was doing.
  • Design consequence. Most of the engineering in the run layer exists to make these three promises cheaply.

See Reset Semantics, Isolation and Infrastructure Failures Are Labeled.

5. Record tokens where they are born. On-policy RL needs the exact token ids the engine sampled and the probabilities it assigned, captured at sampling time.

Two paths from the inference engine: tokens and log-probabilities captured at a gateway give an exact update with pinned versions; text decoded and re-encoded may differ and yields off-policy training. Inference engine samples tokens Gateway token ids · logprobs Text log decode · re-template Exact update versions pinned Re-encoded may differ, off-policy same tokens retokenized
Fig. Schematic. Identical text does not imply identical tokens. Capture happens at sampling time, and every version that produced the reward is pinned.
  • Why. Text that is decoded, re-templated and re-encoded can differ while looking identical.
  • Provenance. The same idea extends to versions. A reward means something only together with the task, environment, verifier, harness and policy versions that produced it.
  • Design consequence. Gateways pass token ids in and out. Sampler log-probabilities feed importance correction (reweighting updates for the gap between the sampling and training policies). Records pin every version.

See Capturing Trajectories Exactly and Versions and Provenance.

How the five connect

Model 1 says what an environment is for, model 2 what it really teaches, model 3 which of its tasks are worth running, model 4 how to keep infrastructure out of its reward, and model 5 what must be kept for its episodes to become data. Most failures described in the book violate exactly one of them.

Three Fundamental Disagreements

The sharpest arguments about environments are not about which library to use. They are about how much fidelity training needs, whether a model should be trained inside its production harness, and whether model-judged rewards can be trusted under optimization. Each debate below gives the strongest case for both sides from evidence cited in the book, then a short view of where it is heading.

Debate 1. Scale or fidelity: many cheap environments, or fewer faithful ones? One side expects synthesized and simulated environments in large numbers to win. The other holds that only faithful, expert-built or executable worlds teach skills that transfer (Synthesizing Environments, LLM-Simulated Environments).

The case for scale.

  • Diversity appears to be the lever. Agent World Model found that training on 10 environments hurt. Training on 100 helped substantially, and 526 helped further. Szot et al. (2026) found that as the data budget grows, adding tool and database diversity beats adding tasks.
  • Synthetic environments transfer. DeepSeek-V3.2 improved agent benchmarks with RL on synthesized general-agent tasks, where RL restricted to code and search did not.
  • Cheap tasks and simulation. Mined and synthesized tasks cost cents to dollars (SWE-smith), several orders of magnitude below hand-built ones. Simulation can also stand in for costly interaction: DreamGym matched GRPO and PPO in costly settings using synthetic interactions only.

The case for fidelity.

  • Simulators break exactly where training needs them. EnvSimBench found models near-perfect when state did not change. They failed sharply when several state variables changed at once, and errors compound over long episodes.
  • Quality can substitute for count. EnvFactory reported gains with roughly a fifth as many environments as comparable work by building from authentic resources.
  • Cheap tasks waste compute. Mechanize (2025) argued that cheap tasks waste the training compute spent on them, so spending per task should rise. Lab researchers interviewed by Epoch AI complained about quickly built replicas full of bugs.

Where it is heading. Toward a division of labor. Simulate what is soft and expensive (users, rare APIs, the long tail of tool responses), and execute what is cheap and exact (code, databases, files). Alongside that come methods that predict an environment's training value before paying for it, such as the pre-RL measures of Madan et al. (2026).

Debate 2. Who should own the loop: the training system or the production harness? Environment-owned loops keep the Gym shape and full control. Harness-owned loops run an unmodified agent program and observe the model through a proxy (Who Owns the Loop).

The case for the production harness.

  • The scaffold is part of the capability. In an audit of Terminal-Bench, Buchanan et al. (2026) found that swapping the harness around one model changed accuracy by up to 29.9 points. A policy trained in a toy scaffold is trained for a different job.
  • Policies learn harness habits. A policy trained against one harness learns that harness's habits. That is why the OpenEnv Harbor environment makes the harness a per-rollout choice.
  • Labs report doing it at scale. MiniMax Forge used more than 100,000 distinct scaffolds and environments. Kimi K2.5 records black-box agents through an LLM gateway.

The case for an environment-owned loop.

  • Exactness is free when the trainer produced every token. Through a harness it must be engineered. Retokenization and chat-template drift are documented failure modes (Agent Lightning 2025, Miles 2026). The OpenEnv Harbor environment marks rollouts eval-only when the engine cannot return token ids or log-probabilities.
  • Control is lost. Control over prompts, context management and per-step rewards is lost once the harness decides when to call the model. Compaction and sub-agents turn a trajectory into a tree that the trainer must reconstruct.
  • Simpler debugging. A custom loop is simpler to debug, and its behavior does not shift when a harness vendor ships an update.

Where it is heading. Toward both, behind one gateway. Token-in/token-out capture (Hugging Face 2026) makes harness-owned rollouts exact enough for training. Libraries let the same task run under a cheap built-in loop or a rotating set of production harnesses.

Debate 3. Can model-judged rewards be trusted under optimization? One side wants rewards from code only. The other holds that rubric judges are the only way to train on the open-ended work that matters (Kinds of Verifiers).

The case for judges and rubrics.

  • Code checks miss correct answers. Huang et al. (2025) found rule-based math verifiers highly precise but with recall (the share of correct answers accepted) around 86%, falling as policies improve. A model fallback when the rule rejects beat rules alone.
  • Instance-specific rubrics work. Rubrics as Rewards beat Likert-style judge rewards on HealthBench and GPQA-Diamond.
  • Most valuable work has no executable end state. Enterprise workflows, research and writing are examples, so refusing judges means refusing those domains.

The case for code-only rewards.

  • Optimizers find judges' holes. The same Huang et al. (2025) study saw a generative verifier accept single symbols and gibberish during RL until training collapsed.
  • Labs avoid neural reward models. DeepSeek-R1 avoided neural reward models at scale for this reason. Hacking is common even against code: METR (2025) found frontier models tampering with scorers.
  • Monitors do not close the gap. ImpossibleBench found LLM monitors caught only 42–65% of cheating on SWE-scale tasks.

Where it is heading. Toward hybrids with a code-checked anchor:

  • executable checks for the outcome;
  • rubric judges for constraints code cannot see;
  • the judge as a fallback rather than the headline;
  • judge robustness tested with adversarial answers before training.
DebateSide ASide BEvidence that would move it
Scale or fidelityMany synthesized or simulated environments; diversity beats tasksFewer faithful environments; simulators fail on complex stateScaling curves beyond a few thousand environments, with fidelity measured per skill
Who owns the loopProduction harness, captured at a gatewayEnvironment-owned loop with full controlMatched comparisons of transfer to deployed harnesses at equal compute
Judged rewardsRubrics and judges open new domainsOnly code resists optimizationMeasured judge false-positive rates late in long RL runs, on policies stronger than the rubric authors

Table. The three disagreements at a glance. Both sides accept the same facts; they differ on which failure matters more at scale.

Self-Test: Ten Questions

These questions apply the book's ideas to situations it does not describe: diagnosing a failure, choosing between designs or planning a check. Each is worth answering in a few sentences before opening the model answer. The answer ends with the point a memorizer usually misses.

  1. A pool that teaches nothing. A team's 2,000-task pool is solved by every rollout on a quarter of the tasks and by none on half. Training uses group-relative advantages with small groups, and reward has been flat for days. What is happening, and what should change?

    Answer Most groups have zero variance, so most compute buys no gradient

    Under group-relative methods, a group in which every rollout succeeds, or every rollout fails, has zero advantage. Three quarters of the pool therefore contributes compute and no signal.

    The fixes are curation, not tuning:

    • Run a pass-rate sweep with the current policy.
    • Retire saturated tasks.
    • Set aside the unsolved half, or add easier variants and partial-credit diagnostics.
    • Draw groups from the band where outcomes mix.

    Larger groups help only for hard tasks with small but nonzero pass rates. That is why practitioners require a success within many rollouts rather than a fixed rate (Zero-Variance Groups, Calibrate Difficulty).

    What a memorizer misses: the band moves as the policy improves, so the sweep is repeated at every checkpoint, not done once.

  2. Reward up, evaluation flat. On one SWE environment, training reward climbs steadily while episodes get shorter, and the held-out evaluation does not move. List the likely explanations and the first checks.

    Answer Suspect the verifier and isolation before crediting the policy

    Rising reward with shorter episodes is the classic fingerprint of a shortcut. Typical shortcuts:

    • editing or skipping tests;
    • special-casing checked inputs;
    • exiting the test runner with a success code;
    • reading the answer, for example by checking out a later commit that contains the reference fix.

    First checks:

    1. Search traces for writes to test files and access to grader paths.
    2. Read a sample of the highest-reward short episodes.
    3. Re-score them with tests copied in after the agent exits and in a fresh sandbox.
    4. Confirm that the repository history is truncated at the task's commit.

    A third possibility is an environment change that made the task easier, which version-pinned records reveal (Detecting Reward Hacking, Reward Hacking in Environments, Isolation).

    What a memorizer misses: telling the model not to cheat barely helps. The fix lives in what the environment exposes.

  3. Crashes as zeros. A rollout system scores every episode that times out or loses its sandbox as reward 0. Failures are rare overall but concentrated in long episodes that run many builds. What does the policy learn, and what should the system do instead?

    Answer It learns to avoid long, thorough solutions

    Failures correlate with behavior (long episodes, heavy builds). Scoring them as zeros therefore attaches a penalty to that behavior, and the policy drifts toward short attempts that rarely crash.

    The system should instead:

    • Label. Episodes the verifier could not score should carry an infrastructure label, be excluded from the advantage computation and be retried.
    • Separate timeouts. Timeouts set by the task's budget are a policy outcome and are kept separate from crashes.
    • Monitor. The orchestrator also tracks the infrastructure-failure rate per environment, since a rising rate is itself an alert (Infrastructure Failures Are Labeled, Long-Tail Episodes).

    What a memorizer misses: the harm is not noise but bias, because failures are not random with respect to what the agent does.

  4. Retokenized transcripts. To save engineering time, a team stores each multi-turn episode as chat text and re-tokenizes it with the chat template at training time. The text matches the logs exactly. Why can the update still be wrong?

    Answer Identical text does not imply identical tokens or probabilities

    Decoding, tool-call parsing and re-rendering through a chat template can change token boundaries and special tokens. The visible text stays the same.

    The trainer then computes gradients on sequences the engine never sampled, and the stored log-probabilities no longer line up. The result is silently off-policy training.

    The fix is to record token ids and sampler log-probabilities at the gateway and never re-tokenize. Separately, an importance correction handles the remaining numerical gap between engine and trainer (Three Sources of Drift, Capture at the Gateway, Logprobs).

    What a memorizer misses: text logs are fine for debugging and SFT data. The requirement is specific to the policy-gradient update.

  5. Ready to ship? A new environment's verifier gives every reference solution a score of 1, over repeated runs. The team proposes to start training. What is missing?

    Answer The negative direction: proof that wrong behavior scores 0

    Passing references proves only the absence of false negatives on one solution. The suite also needs:

    • a null agent (catches tasks solved at reset);
    • a claim-only agent that says "done" (catches verifiers that read the transcript);
    • tampering and special-casing agents (catch hacks);
    • a collateral-damage agent;
    • a second valid solution written differently (catches over-specific checks);
    • a killed sandbox that yields "not scored";
    • for judged rewards, adversarial text appended to wrong answers.

    Then a few dozen real passes and failures are read by hand (The Verifier as a Product, Audit the Verifier).

    What a memorizer misses: a regression on the alternative-solution case does not show up as hacking. It shows up later as a plateau.

  6. Choosing a source. Pick a way to obtain each environment:

    • (a) bug fixing in popular Python libraries;
    • (b) airline customer service with a refund policy;
    • (c) a workflow inside a proprietary ERP product;
    • (d) a long tail of rarely used third-party APIs for tool-calling practice.
    Answer Mine what exists, synthesize what is structured, buy fidelity, simulate the soft
    • (a) Mine. Repositories bring state, actions and tests. SWE-smith-style bug injection adds volume, mixed with harvested real fixes because synthetic bugs are smaller.
    • (b) Synthesize a database-backed world with typed tools and a policy document. Grade by final database state, and add a simulated user whose words never decide the reward.
    • (c) Buy or hand-build a replica with expert-written tasks. Neither mining nor synthesis reproduces the product's behavior, and the value of the workflow justifies the price.
    • (d) Simulate tool responses, keep the simulated phase short, and filter trajectories with a judge. These are soft, long-tail behaviors where execution is expensive (Hand-Built, Mining, Synthesizing, Simulated).

    What a memorizer misses: the choice follows where fidelity matters to the skill, not a general ranking of the four methods.

  7. Two kinds of held-out. After training, held-out tasks from the training environments improve a lot, while a held-out family of environments barely moves. A slide claims "strong generalization". What does the evidence support?

    Answer Familiarity with the environments, not transfer

    Held-out tasks inside a trained environment share its tools, templates, data and verifier quirks. Gains there measure how well the policy learned that environment.

    A held-out family tests transfer, and it barely moved. The supportable claim is "improved on the trained environments".

    Before reporting, check that no training environment shares a generator, repository or template with the evaluation. Report the split level, versions, harness and budget with the result (Held-Out Environments and Families, Reporting Practice).

    What a memorizer misses: the split must match the claim. A task-level split cannot support a family-level claim however large the gain.

  8. Bigger batches, slower steps. A synchronous RL run doubles its batch of agentic episodes to use more engines, and the fraction of engine time doing useful work falls. Why, and what are the options?

    Answer A synchronous step waits for its slowest episode, and bigger batches have slower slowest episodes

    Episode lengths are heavy-tailed, and the expected maximum of a batch grows with its size. Engines finish their share and sit idle while the step waits.

    Options:

    • Asynchronous generation with a bound on how many policy versions old a sample may be.
    • Partial rollouts that pause long episodes and resume them under newer weights.
    • Timeouts set by the task budget.
    • In-flight weight updates.

    Each brings mild off-policy data, which is why behavior log-probabilities are recorded at generation time (Synchronous and Asynchronous RL, Long-Tail Episodes).

    What a memorizer misses: adding hardware to a synchronous agentic run can lower utilization. The fix is in the schedule, not the fleet size.

  9. The score that moved by itself. A benchmark's maintainers revise a set of tasks, partly because internet-hosted dependencies changed, and an agent's score rises by several points with no change to the model. What must a trajectory record contain to tell this apart from a policy change in a training run?

    Answer Every version that touches the reward, pinned per episode

    The record needs:

    • task id and task version;
    • environment build (image digest and pinned dependencies);
    • verifier version;
    • harness and its budget;
    • policy checkpoint;
    • status labels.

    With those, a reward shift can be sliced by environment version and attributed.

    Environments that reach external services also need pinned mirrors and drift monitors. A moved dependency looks exactly like a capability change (Versions and Provenance, Environment Drift).

    What a memorizer misses: "task 17, reward 0" is not data. Without versions, old and new rewards are not comparable.

  10. A helpful simulated user. In a customer-service environment with an LLM-simulated user, success rates climb quickly. Transcripts show the simulated user volunteering the exact steps needed to finish. What is wrong, and how should the environment be fixed?

    Answer The simulator is leaking the solution, so the policy learns to rely on it

    An over-cooperative or leaky user inflates success. It also teaches a skill (following hints) that real users will not reward.

    Fixes:

    • Compute reward from the environment's state, never from the user's words.
    • Constrain the simulated user with a persona and the information it is allowed to know.
    • Use a stronger simulator.
    • Audit transcripts for leakage as part of quality control.

    Long simulated episodes also accumulate inconsistencies. Simulation is therefore best kept to the soft part of the world while tools and state stay executable (LLM-Simulated Environments and Users, Environment Quality Control).

    What a memorizer misses: a simulated user is part of the environment, so its fidelity is part of what is measured and trained.

Introduction

A reinforcement learning environment is the place where a model practices. It supplies tasks, a world the model can act on, and a check that says whether the attempt worked. Between 2025 and 2026 such environments became one of the scarcest inputs to post-training.

Web text is abundant and compute can be bought. An environment is different. Consider one in which an agent reconciles expense reports inside a replica of an enterprise app, with a grader it cannot game. People have to design, build and debug it, and it decays as models improve.

The market followed. Denain & Barber (2026) interviewed 18 people at environment startups, neolabs and frontier labs for Epoch AI. They found that labs now buy environments and tasks much as they once bought labels:

  • Per-task prices. Most tasks are reported to cost between $200 and $2,000 each. Prices near $20,000 are rare and reserved for complex software-engineering tasks.
  • Product replicas. One interviewee put a high-fidelity replica of a complex product such as Slack at around $300,000. Exclusive deals were said to cost roughly four to five times more than non-exclusive ones.
  • Lab budgets. The same piece relays a September 2025 report by The Information: Anthropic had discussed spending more than $1 billion on environments over the following year. That figure is second-hand and should be read as an order of magnitude, not a budget.

An open ecosystem grew in parallel:

  • Environments Hub. Prime Intellect launched its Environments Hub in August 2025. Its argument: if good environments stay expensive and sold exclusively to a few closed labs, open models will fall behind.
  • OpenEnv. Meta and Hugging Face released OpenEnv in October 2025 as a shared specification and hub.
  • NeMo Gym. NVIDIA open-sourced NeMo Gym alongside its Nemotron 3 models in December 2025.

A useful way to read all this: labs are buying practice, not answers. A label tells a model what to say. An environment lets it try, fail and be graded thousands of times.

The same environment serves three consumers:

  • Training. It is a training signal for RL, which Epoch's interviewees describe as the primary use.
  • Evaluation. It is an evaluation, because a task with a hidden grader is a benchmark item.
  • Data generation. It is a data generator, because successful trajectories can be filtered into supervised fine-tuning sets.

One startup employee estimated that RL requests outnumber benchmarking requests by 10 to 20 times. It is a single estimate, but a telling one. Sharing one artifact across all three uses is efficient and also dangerous. An environment that trains a model can no longer measure it cleanly (see Train/Eval Separation).

This book follows an environment from specification to training data:

Human-feedback pipelines (campaigns, annotation tools, rater quality) are covered in the companion book RL Data Platform and are not repeated here.

Notation

\(X\) is a set of tasks and \(\rho\) a distribution over it; \(x \sim \rho\) is one task. \(s_0^x\) is the task's initial world state, \(a_t\) and \(o_t\) the agent's action and observation at step \(t\), \(\tau = (o_0, a_0, o_1, \dots)\) a trajectory, \(R_x(\tau)\) the reward the verifier assigns, and \(\pi\) the policy (model plus scaffold).

What an RL Environment Is

An RL environment for a language-model agent is a bundle of five parts plus two properties. The parts are a task distribution, a stateful world, an action interface, a verifier that turns an episode into a reward, and a harness that runs episodes. The properties are easy to forget until they fail: reset semantics and isolation.

A benchmark, a training environment and a trajectory generator can share every one of these parts. They differ mostly in who consumes the output.

Environment, task, benchmark

Usage varies. Epoch's FAQ separates the environment (the actions available and the surrounding state) from the task (a prompt paired with a grader). This book uses "environment" for the whole runnable bundle and "task" for one instance \(x\) within it. A benchmark is an environment whose tasks are frozen and reserved for measurement.

The Five Parts

Each part answers one question about an episode: what is asked, what can change, how the agent acts, how success is judged, and who runs the loop.

  1. Task distribution. A set of instructions, initial-state specifications, seeds and hidden success criteria, together with the distribution \(\rho\) over them. The distribution matters as much as the tasks. Epoch's interviewees note that a task every rollout solves, or none does, teaches nothing.
    • Several wanted at least one success in 64 or 128 rollouts (a pass rate of roughly 2–3%).
    • Tasks that pass around 70% of the time are candidates for retirement.
    Calibration and curricula are covered in Environment Quality Control and Curating Rollouts.
  2. State, or world. What the agent can change. Examples:
    • a SQLite database behind a set of tools in Agent World Model;
    • a repository with "an executable runtime environment" in SWE-Gym;
    • self-hosted websites in WebArena;
    • a full virtual machine in OSWorld.
    The kind of state fixes both what a verifier can check and what a reset costs.
  3. Action interface. How actions reach the world. Options include structured tool calls, shell commands, browser automation, and mouse and keyboard events on screenshots. Tool calls are increasingly exposed through the Model Context Protocol (MCP, an open standard Anthropic introduced in November 2024). Epoch lists the access methods vendors build: MCP integrations, Playwright browser control and screenshot-based computer use. The interface determines which agents can use an environment and what skills transfer. From reset/step to Agent Loops treats it in detail.
  4. Verifier, or reward. The function that maps a finished episode (final state, transcript or both) to a reward. Common forms are unit tests, database end-state checks, rule-based answer matching, and rubrics scored by an LLM judge.
    • Example. DeepSeek-R1 used rule-based accuracy and format rewards. It avoided neural reward models because they "may suffer from reward hacking" at scale (DeepSeek-AI 2025).
    • Difficulty. The verifier is usually the hardest part to get right. Epoch's interviewees consistently name robustness to reward hacking as the most important quality criterion.
    See Verifiers and Rewards.
  5. Harness, or episode protocol. The code that runs an episode. It provisions the world, calls the model, and enforces turn, token and wall-clock budgets. It also decides when an episode ends, logs, and classifies errors. Harbor, the harness released with Terminal-Bench 2.0, shows the modern shape. It runs installed agents such as Claude Code, Codex CLI or OpenHands inside containers, locally or on cloud sandbox providers. It emits rollouts for RL as well as evaluation scores.
Episode lifecycle in an RL environment and the component responsible for each stage. next episode: new task, or same task with a new seed 1 Sample 2 Reset 3 Agent loop 4 Stop 5 Verify 6 Record task x ~ ρ world → s₀ˣ act ↔ observe done / truncated reward Rₓ(τ) save τ, tear down owned by Task set World state Actions Harness Verifier Trajectories prompts · seeds DB · repo · VM tools · shell · GUI budgets · errors hidden checks exact token logs
Fig. The lifecycle of one episode (top) and the part of the environment responsible for each stage (bottom). Reset and isolation sit inside stage 2 and determine whether episodes are comparable at all; the verifier in stage 5 reads state the agent could not see. The dashed loop is what a rollout system repeats millions of times.

Reset Semantics

Reset is the promise that every episode of task \(x\) starts from the same world \(s_0^x\), whatever earlier episodes did. In the classic Gym interface it is a single call that returns the first observation. Gymnasium, Gym's maintained successor, takes a seed so that the initial state is reproducible.

For agent environments reset is often the most expensive operation in the system. It can mean restoring a database, checking out a repository at a commit with its dependencies installed, booting a VM from a snapshot, or re-seeding a simulated user.

A reset contract has to cover more than the obvious state:

  • World state: files, tables, browser storage, running processes.
  • Hidden state that leaks across episodes: package caches, shell history, temporary files, the system clock (tasks about "today" change meaning), and any external service the environment calls.
  • Stochastic components: a simulated user or a randomized web page should draw from a seeded generator, so that variance across rollouts reflects the policy rather than the environment.

The last point matters for training, not only for evaluation. Group-relative methods score each rollout against several other rollouts of the same task. If their starting worlds differ, part of the measured advantage is environment noise.

Live websites cannot be reset at all. For that reason WebArena runs its own fully functional copies of sites in four domains instead of pointing agents at the public web. How snapshots, clones and warm pools make reset cheap is the subject of Sandboxes.

Isolation

Isolation runs in two directions. Episodes must not affect one another, and the agent must not reach information or capabilities the task did not intend.

Concurrent rollouts that share a database, a filesystem or an account silently corrupt each other's state, and therefore each other's rewards. In the other direction, any path to the answer is a reward hack waiting to be found. Epoch's interviewees describe models searching the web for answers. They also describe models checking out future commits of a repository to read the reference fix.

  • Verifier material (hidden tests, gold database states, reference answers) must live outside the agent's reach, not merely in a directory the prompt does not mention.
  • Network access should be the minimum the task needs. OpenEnv's framing is an environment that gives the agent the tools and access it needs and nothing more.
  • Host safety: agents execute arbitrary code, so an environment is also a security boundary.

Reset and isolation are where an environment stops being a dataset and becomes an infrastructure system. Most of the engineering in Running Environments at Scale exists to provide these two properties cheaply.

Deeper A formal view: an environment as a family of POMDPs

It helps to write the bundle down. An environment is a task distribution together with one partially observable decision process per task:

\[ \mathcal{E} = \big(\rho,\ \{\mathcal{M}_x\}_{x \in X}\big), \qquad \mathcal{M}_x = \big(S,\ A,\ O,\ T,\ Z,\ s_0^x,\ R_x,\ H\big) \]

where \(S\) is the world state, \(A\) the action space (for an LLM agent, token sequences that the harness parses into tool calls), \(O\) the observation space (tool outputs, screenshots, user messages), \(T(s' \mid s, a)\) the transition function, \(Z(o \mid s')\) the observation function, \(s_0^x\) the reset state, \(R_x\) the verifier and \(H\) the budget after which an episode is truncated.

Training maximizes

\[ J(\pi) = \mathbb{E}_{x \sim \rho}\ \mathbb{E}_{\tau \sim (\pi, \mathcal{M}_x)} \big[ R_x(\tau) \big]. \]

Four consequences follow.

  • \(\rho\) is part of the objective. Re-weighting the task mix changes what is optimized just as surely as changing the reward does.
  • Rewards are usually terminal and sparse. \(R_x\) typically reads only the final state or final answer, so credit assignment across a long trajectory is left to the learning algorithm.
  • Termination is not truncation. An episode that ends because the task is done and one cut off by \(H\) carry different information. Gymnasium returns separate terminated and truncated flags for this reason. For outcome-reward LLM training, teams must decide whether a truncated episode scores zero, is dropped, or is retried.
  • Reset is a determinism requirement. \(s_0^x\) must be a function of \((x, \text{seed})\) alone. If it also depends on the history of the machine it ran on, \(\mathcal{M}_x\) is not one process but many.

Lineage

Today's agent environments descend from six threads. Each contributed one ingredient:

  • Classic RL benchmarks supplied the interface.
  • Procedural generation supplied the idea that tasks should be generated rather than enumerated.
  • Web and computer-use benchmarks put language models inside real software.
  • Code benchmarks supplied executable verifiers.
  • Verifiable-reward RL showed that such checks could train frontier reasoning models.
  • Platforms and synthesis pipelines of 2025–2026 are turning environments into a manufactured product.
Six lineages of RL environments for language-model agents, 2012 to 2026.
Fig. Six threads that converge on today's environment platforms. Each lane runs from its root to its 2025–2026 descendants; the horizontal axis is compressed before 2020. Years are first public release or publication, approximate to the quarter. The bottom lane is drawn as a fan because its milestones fall within a few months of one another.
  1. Classic RL benchmarks. The Arcade Learning Environment (Bellemare et al. 2013) made dozens of Atari games a shared test bed, and the MuJoCo physics engine (Todorov et al. 2012) did the same for continuous control. MuJoCo was later packaged as the DeepMind Control Suite (Tassa et al. 2018). OpenAI Gym (Brockman et al. 2016) fixed the reset/step interface that nearly every later environment imitates. Gymnasium (Towers et al. 2024) became its maintained successor after OpenAI stopped updating Gym.
  2. Procedural generation and open-endedness. Procgen (Cobbe et al. 2019) generated levels so that training and test levels differ, turning generalization into something measurable. POET (Wang et al. 2019) went further and generated the environments themselves alongside the agents that solve them. The NetHack Learning Environment (Küttler et al. 2020) offered a procedurally generated world too large to memorize. Reasoning Gym (2025) carries the idea to language models with generators of reasoning tasks whose answers can be checked automatically.
  3. Web and computer-use agents. World of Bits (Shi et al. 2017), with its MiniWoB tasks, first framed the web browser as an RL environment. WebShop (Yao et al. 2022) gave language agents a simulated store with 1.18 million real products and 12,087 crowd-sourced instructions. It reported non-trivial transfer to amazon.com and ebay.com. WebArena (Zhou et al. 2023) moved to self-hosted, fully functional websites graded by functional correctness. OSWorld (Xie et al. 2024) moved to full Ubuntu, Windows and macOS machines with an execution-based checking script per task.
  4. Code and software engineering. HumanEval (Chen et al. 2021) made hidden unit tests the oracle for generated code. SWE-bench (Jimenez et al. 2023) scaled the oracle to real GitHub issues in full repositories. The step from benchmark to training environment came in 2024–2025:
    • SWE-Gym (Pan et al. 2024) packaged 2,438 Python tasks with runtimes and tests for training.
    • R2E-Gym (Jain et al. 2025) built more than 8,700 tasks from commits without needing human-written issues.
    • SWE-smith (Yang et al. 2025) synthesized about 50,000 task instances across 128 repositories by breaking existing tests.
  5. Verifiable rewards for LLMs. Tülu 3 (Lambert et al. 2024) named the recipe Reinforcement Learning with Verifiable Rewards (RLVR): reward the model only when a programmatic check passes. DeepSeek-R1 (2025) showed at scale that rule-based rewards on math and code could elicit long-form reasoning through RL. That result made "a checkable task" the unit of post-training data and created the demand that the rest of this book is about.
  6. Environment platforms and factories. In the second half of 2025 environments acquired package managers and assembly lines. Four releases standardized how environments are packaged, shared and run: At the same time, synthesis pipelines began to generate environments wholesale:
    • DeepSeek-V3.2 reports 1,827 synthesized general-agent environments (4,417 tasks). They sit within a synthesis pipeline of roughly 85,000 agentic prompts.
    • Agent World Model (Wang et al. 2026) generates 1,000 database-backed tool environments with about 35 tools each.
    The standards are compared in Environment Standards and Hubs and the factories in Synthesizing Environments.

Read together, the threads explain the shape of a 2026 environment. It combines Gym's episode interface, SWE-bench's executable verifier, WebArena's self-hosted world and Procgen's generator. It is packaged for a hub and produced by a pipeline rather than by hand.

Environments by Type

Environments differ along two main axes. One is how rich, and therefore how expensive, the world is. The other is how objectively success can be checked. The eight types below cover most of what is trained on in 2026.

Moving from top to bottom of the table, worlds get heavier and episodes longer. Verifiers shift from exact checks toward state inspection, rubrics and simulated people.

TypeWorld stateAction spaceVerifierEpisode lengthInfra costRepresentative examples
Verifiable single-turn (math, code)None, or a scratch sandbox to run codeOne responseAnswer match; unit tests1 turnLowReasoning Gym, HumanEval, R1-style math
Tool use / MCPDatabase or service state behind an APIStructured tool callsEnd-state checks; answer match; sometimes a judgeSeveral to tens of callsLow to mediumAgent World Model, DeepSeek-V3.2 general-agent tasks
Web / browserSelf-hosted web apps plus a browserClicks, typing, navigation via DOM or accessibility treeURL, page or backend-state checksTens of stepsMediumWebShop, WebArena
Computer use / desktopFull virtual machine: OS, apps, filesMouse and keyboard on screenshotsPer-task scripts that inspect VM stateTens to hundreds of stepsHighOSWorld
SWE / terminalRepository in a container with dependenciesShell commands, file editsHidden tests (fail-to-pass, pass-to-pass)Tens to hundreds of commandsMedium to high (an image per repository)SWE-bench, SWE-Gym, SWE-smith, Terminal-Bench 2.0
Conversational with simulated usersDomain database plus an LLM user simulatorMessages and tool callsFinal database vs. annotated goal; policy checksMulti-turn dialogueMedium (simulator inference)τ-bench
Enterprise app replicasClone of a CRM, spreadsheet, chat or ERP productAPI/MCP, browser or GUIState checks; rubrics for open-ended outputLong multi-app workflowsHigh to buildVendor-built Slack, Excel and SAP-style clones described by Epoch
Scientific / simulationA simulator (physics, chemistry, text world)Simulator commands or controlsOutcome computed by the simulatorVaries widelyVaries with the simulatorScienceWorld, dm_control

Table. A taxonomy of RL environments for language-model agents. Episode lengths and costs are rough orders of magnitude from the cited papers and reports, not measurements; individual environments vary widely within a type.

A few patterns stand out:

  • Small worlds, cheap checks. Objective verifiers are cheapest where the world is smallest. Single-turn math and code need no state at all, which is why RLVR started there.
  • Software engineering. It is the exception that proves the value of tests: a heavy world combined with an objective check. That combination is why it absorbed so much of 2025's environment work.
  • Enterprise and desktop. At the other end, enterprise replicas and desktops are both expensive to build and harder to verify.
  • Growth areas. Epoch's interviewees describe enterprise workflows (spreadsheets, CRMs, expense reports) as a main growth area. Coding repositories are expanding toward environments that also include tools such as GitHub, Linear and IDEs.
Environment types placed by world cost and verifier objectivity.
Fig. Environment types placed by the cost of their world (horizontal) and the objectivity of their verifier (vertical). Placement is illustrative, the author's reading of the table above rather than a measurement. Synthesis pipelines aim at the shaded region: worlds rich enough to matter, with checks that are still programmatic.

Two types blur the line between environment and model. They move in opposite directions.

  • Conversational environments put part of the world inside an LLM. τ-bench (Yao et al. 2024) pairs domain tools and policies with a language-model user. It grades by comparing the final database with an annotated goal state. The simulator's fidelity therefore becomes part of what is measured.
  • Synthesized tool environments replace LLM-imagined responses with code. Agent World Model backs every environment with a SQLite database precisely so that state transitions are consistent rather than hallucinated.

Where each choice is acceptable is discussed in LLM-Simulated Environments and Users.

The type also predicts where the engineering goes:

  • Data. Single-turn environments are mostly a data problem: generators, answer checkers and difficulty calibration.
  • Modeling. Tool, web and conversational environments are mostly a modeling problem: realistic state, believable data and faithful users.
  • Infrastructure. SWE, desktop and enterprise environments are mostly an infrastructure problem: images, snapshots, cold starts and thousands of concurrent sandboxes.

The remaining parts of this book take those problems in turn.

From reset/step to Agent Loops

An environment interface is the contract that decides who calls whom, what counts as one action, and where the reward comes from. For a decade that contract was the Gym loop. The trainer calls reset(), then repeatedly samples an action and calls step().

LLM agents strain every part of that loop. An action is a stream of tokens that may contain several tool calls. An episode can run for hours. The most capable agents are full programs (coding CLIs) that run their own loop and were never written to be stepped.

The practical result in 2025–2026 is a split between two designs. Environment-owned loops keep the Gym shape. In harness-owned loops, the environment hands a task to an agent program and observes the model calls through a proxy.

The Gym Contract

The Gym contract reduces an environment to two calls and a reward, which is why it became the default interface of reinforcement learning. Brockman et al. (2016) packaged benchmark tasks behind a common API so that an algorithm written once could run on any of them. Gymnasium (Towers et al. 2024), its maintained successor, kept the shape and tightened the semantics. In its current form one step is

\[ (o_{t+1},\; r_t,\; \text{terminated},\; \text{truncated},\; \text{info}) = \texttt{env.step}(a_t), \]

where \(o_{t+1}\) is the next observation, \(r_t\) the reward, terminated means the task reached a terminal state and truncated means an outside limit (a time or step budget) cut the episode short.

Truncated episodes should be bootstrapped and terminated ones should not. In agent RL the same split reappears as "the agent finished" versus "the harness timed out". Conflating the two mis-scores rollouts.

The contract assumes three things: the trainer owns the loop, actions are small typed objects, and reward arrives every step. None holds for a typical LLM agent.

Why reset/step Strains Under LLM Agents

The Gym contract strains under LLM agents because the natural unit of action, the length of an episode and the place where reward is computed all differ from classic control. Four mismatches recur.

  • Two granularities of action. The policy acts per token. The environment sees only completed tool calls, and several may sit in one turn. The trainer needs token ids and log-probabilities that stay aligned with the environment's turn-level view (see Capturing Trajectories Exactly).
  • Asynchrony. Tool calls take from milliseconds to many minutes, so a synchronous step() stalls the GPU-bound sampler. Modern libraries are async and run thousands of episodes concurrently (see Rollout Systems).
  • Long, branching episodes. Hundreds of turns, context compaction and sub-agents turn a trajectory into a tree of model calls rather than a list of steps.
  • Terminal, external reward. Most rewards are computed once, after the episode, by tests or state inspection. This often happens in a fresh process or sandbox.

Who Owns the Loop

The deepest design choice in an agent environment is which component owns the interaction loop: the training system or the agent program.

In an environment-owned loop, a rollout worker in the training system samples from the policy, parses tool calls and calls the environment's step(). The environment is a passive server.

In a harness-owned loop, the environment provisions a sandbox and starts an agent program inside it, such as Claude Code, Codex CLI or OpenHands. It sends the instruction and waits. The agent decides when to call the model and which tools to run. The environment only scores the result.

Two ways to own the agent loop: a rollout worker stepping an environment server, or an agent harness in a sandbox whose model calls pass through a capture proxy. Environment-owned loop Harness-owned loop Rollout worker samples, parses tool calls, calls step() Inference engine Env server reset · step · state Trajectory store → trainer reward arrives with each step token ids, logprobs obs, reward SANDBOX Agent harness Claude Code · Codex Task env repo · tests Capture proxy records every model call Inference engine Trace + verifier reward → trainer tests run in the sandbox after the harness exits token ids, logprobs
Fig. Two ways to own the loop. Left: the training system's rollout worker alternates between the inference engine and a passive environment server. Right: an unmodified agent harness runs its own loop inside the sandbox; its model calls are routed through a capture proxy that records token ids and log-probabilities, and the task's verifier scores the final state.
  • Environment-owned loops give full control over prompts, tool parsing, context and per-step rewards. Recording is trivial because the trainer produced every token. The cost is a custom scaffold that differs from the shipped product.
  • Harness-owned loops train the model in the scaffold it will actually be used in. NeMo Gym's Harbor integration is an explicit example. The server seeds a sandbox, opens a session for the harness and sends the instruction. Once the harness finishes or times out, the server leaves the sandbox to the verifier. The trainer no longer sees the loop, so capture must happen elsewhere.

Libraries increasingly support both, so the same task can run under a cheap built-in loop or a production harness. The OpenEnv Harbor environment argues that a policy trained against a single harness "learns that one's habits". It lets the harness be chosen per rollout, so rotating harnesses during training is a configuration change.

Capturing Inference at a Gateway

When the harness owns the loop, the only place the training system can observe the policy is the model endpoint, so trajectories are captured by a proxy that sits between the agent and the inference engine. The agent is pointed at the proxy as if it were an ordinary OpenAI- or Anthropic-compatible API.

The proxy forwards each call and asks the engine for token ids and log-probabilities. It records the call, then returns the response in the dialect the agent expects.

Two 2026 implementations show the pattern.

  • OpenEnv Harbor. The OpenEnv Harbor environment translates four wire dialects to one upstream shape: chat completions, OpenAI Responses, Anthropic Messages and Google generateContent. Unmodified agents such as Claude Code, Codex and Gemini CLI can therefore be captured. It probes the engine at startup. It marks rollouts eval-only when token ids or post-temperature log-probabilities are unavailable. How it links calls into a rollout graph is described in Capturing Trajectories Exactly.
  • Verifiers v1. Verifiers v1 places a similar interception server between harness and inference server. It stores traces as message graphs and turns each root-to-leaf branch into a training sample.

Any sampling-parameter override or provider workaround the proxy applies changes the experiment, so it should be recorded on the rollout. Token-level pitfalls are covered in Capturing Trajectories Exactly.

MCP as an Action Interface

The Model Context Protocol (MCP) has become the common way to describe an environment's action space as a set of tools, but it says nothing about episodes or rewards. An MCP server lists tools with tools/list and executes them with tools/call. Each tool has a name, a description and a JSON Schema for its inputs (and optionally its outputs).

MCP separates two kinds of error. Tool execution errors come back as results flagged with isError, so the model can read them and retry. Malformed requests are protocol errors. The split maps neatly onto RL. An execution error is an observation the policy should learn from. A protocol error is closer to an invalid action.

The same MCP server can serve a deployed agent and a training environment, which keeps the training action space identical to production. What MCP lacks are the RL primitives: reset, episode boundaries, task identity and reward. Several standards add them on top of MCP.

  • OpenEnv treats MCP as a first-class way to expose environment tools.
  • The Open Reward Standard reuses MCP's tool-calling conventions and adds rewards, episode termination, tasks and splits.
  • CUBE builds on both MCP and Gym.

Environment Standards and Hubs

Between 2025 and 2026 the field moved from one-off environment code inside each training stack toward shared standards. No single standard has won, and the projects occupy different layers.

  • Wire protocols define how a client resets and steps an environment over the network.
  • Authoring libraries define how an environment, its tasks and its reward are written.
  • Task formats and runners define how tasks are packaged and run for agent harnesses.
  • Hubs handle discovery.

Most mature projects now interoperate across layers rather than compete within one. Facts below come from the projects' own documents as of November 2026.

Layers of the open environment ecosystem and the projects that sit mainly in each layer. Discoveryfind and run PI Environments Hub HF Hub rl-environment EnvCommons · OpenEnv catalog Task formattasks for harnesses Harbor (task dir + verifier) CUBE (wrap a benchmark once) Authoringenvs, tasks, rewards Verifiers NeMo Gym SkyRL-Gym GEM Atropos Reasoning Gym RLVE-Gym procedural task generators Wire protocolover the network OpenEnv (reset · step · state) ORS (tools + reward) MCP (tools)
Fig. Where the main open projects sit. Placement is by primary role; most span more than one layer (Verifiers and NeMo Gym both run Harbor tasks, OpenEnv ships a catalog, ORS environments are collected on EnvCommons). Sandboxes and container images sit below all layers and are covered in Sandboxes.

The Main Projects

The projects most often named as environment standards in 2026 fall into a few families; the table below compares them on what their own documents state.

  • OpenEnv began as a Meta–Hugging Face project and in June 2026 moved to a committee that includes Meta-PyTorch, Hugging Face, Prime Intellect, NVIDIA, Microsoft, Modal and Mercor among others (Hugging Face 2026). It positions itself as the deployment and interface layer. It offers Gymnasium-style reset(), step() and state() over HTTP and WebSocket, one Docker image per environment and native MCP tools. It takes no position on rewards or training loops. Its documentation lists more than 40 environments.
  • Verifiers (Prime Intellect) is an authoring library tied to the Environments Hub and the prime-rl trainer. Its v1 release (July 2026) splits an environment into a taskset, a harness and a runtime, so a Verifiers or Harbor taskset can run under Codex, mini-SWE-agent or a custom harness (Prime Intellect 2026).
  • Harbor, from the creators of Terminal-Bench, is the official Terminal-Bench 2.0 harness. It runs Claude Code, Codex CLI, OpenHands and other agents in containers across many sandbox providers (GitHub). Its task directory has become a de facto task format that other libraries import. The directory holds task.toml, instruction.md, an environment/ Dockerfile, a tests/ verifier that writes a reward file, and an optional reference solution.
  • Libraries and controllers. NeMo Gym (NVIDIA) separates agent, model and resources servers and integrates Harbor, OpenEnv, Verifiers and Reasoning Gym environments. SkyRL-Gym (NovaSky AI) and GEM (Liu et al. 2025) keep a Gym-style API for text and tool environments. GEM adds asynchronous vectorized execution. Atropos (Nous Research) runs environments as microservices that push scored rollouts to a trajectory API.
  • Protocols. The Open Reward Standard (General Reasoning, March 2026) is an HTTP protocol in which actions are tools. CUBE (Lacoste et al. 2026) proposes wrapping each benchmark once, with separate task, benchmark, package and registry layers.
  • Procedural generators. Reasoning Gym (Stojanovski et al. 2025) offers more than 100 generators with verifiers and adjustable difficulty. RLVE (Zeng et al. 2025) offers 400 environments whose difficulty adapts to the policy. Joint training on all of them gave a strong 1.5B model an average gain of 3.37 points across six reasoning benchmarks. Continuing its original RL with more than three times the compute gained 0.49 points.
ProjectLayerInterfaceReward defined byNotable fact
OpenEnvProtocol, catalogreset / step / state over WebSocket; MCP toolsEnvironment (external rewards on roadmap)Committee governance since June 2026
Verifiers v1Authoring, hubTaskset + harness + runtimeRubric functions in the environmentInterception server records traces
HarborTask format, runnerTask directory; agent harness in containerVerifier in tests/ writes reward fileOfficial Terminal-Bench 2.0 harness
NeMo GymAuthoring, servingAgent / model / resources serversResources server verificationRuns Harbor, OpenEnv, Verifiers and Reasoning Gym envs
SkyRL-GymAuthoringGymnasium-style text env + toolsEnvironmentMath, code, search, SQL envs
GEMAuthoringGym-style, async vectorizedEnvironment, per-turn possibleExamples for five RL frameworks
AtroposRollout controllerEnv microservices → trajectory APIEnvironmentAny OpenAI-compatible endpoint
ORSProtocolHTTP; MCP-style toolsProtocol primitive200+ envs on EnvCommons
CUBEBenchmark wrappingBuilt on MCP and GymBenchmarkProposal, March 2026

Table. Open environment standards and libraries as described in their own documents, November 2026. "Layer" is the primary role; most projects span several.

Hubs and Discovery

Hubs make environments findable and runnable by name, which turns an environment from a code drop into a versioned artifact. Prime Intellect's Environments Hub hosted what the company described in late 2025 as hundreds of environments and evals written with Verifiers. The hub is part of its hosted training and evaluation platform.

In September 2026 Hugging Face added RL environments to its Hub without a new repository type (Hugging Face 2026).

  • An environment is a dataset repo tagged rl-environment.
  • Framework tags (harbor, verifiers, openenv, nemo-gym) declare compatibility.
  • The tags generate framework-specific loading snippets.

Reusing dataset repos gives environments the Hub's existing versioning, gating and dataset cards.

Portability is claimed more often than measured

Adapters exist in most directions, but evidence that one environment yields the same reward distribution through two stacks is rarely published. Tool parsing, prompt templates, timeouts and images can all shift pass rates. A small cross-stack agreement check is cheap insurance before trusting an imported environment.

Verifiers and Rewards

The verifier is the part of an environment that turns an episode into a number, and it is the part most likely to be wrong in ways that training will exploit. It may run tests, inspect final state, match an answer, apply a rubric through a judge or query a reward model.

Whatever the verifier accepts, including accepted non-solutions, is what the policy learns. A verifier therefore deserves the treatment of a product: tests, versions and audits.

Kinds of Verifiers

Verifiers differ along one main axis: how much of the judgment is executable code and how much is a model's opinion. Code-based checks are cheap and deterministic but brittle at the edges. Model-based checks cover open-ended tasks but can be gamed under optimization.

VerifierWhat it checksExampleTypical false positiveTypical false negative
Test-basedHidden tests pass after the episodeSWE and terminal tasksWeak tests; agent edits tests or special-cases inputsFlaky or over-specific tests
State-basedFinal DB / filesystem matches goal; nothing else changedτ-bench database comparisonGoal state reachable by a shortcutSeveral valid end states, only one encoded
Rule / exact matchNormalized answer equals referenceMath and puzzles (RLVR)Rare: answer guessed without workEquivalent forms rejected
Rubric + LLM judgePer-criterion judgments, aggregatedMedical or research answersJudge persuaded by style or adversarial textJudge misses correct but unusual answers
Learned reward modelScore from a trained modelGenerative verifiersExploitable patterns after many updatesOut-of-distribution answers

Table. Kinds of verifiers and how each typically fails. Production environments often combine two: a code check for the outcome and a judge for constraints the code cannot see.

Two findings frame the trade-off.

  • Huang et al. (2025) found rule-based math verifiers above 99% precision but only about 86% recall. Roughly one correct answer in seven scored wrong, and recall fell as policies improved. A trained generative verifier recovered many of those answers. It was then exploited during RL, accepting single symbols and gibberish, until training collapsed. A hybrid consults the model only when the rule rejects. It raised recall by about 3 points while keeping precision above 98%.
  • Rubrics as Rewards (Gunjal et al. 2025) scores instance-specific rubric items with a judge instead of one holistic Likert rating. It improved on Likert-style judge rewards by up to 31% relative on HealthBench and 7% on GPQA-Diamond.

A State-Checking Verifier

State-based verification scores what the agent did to the world rather than what it said, and it should check both the goal and the absence of collateral damage. The sketch below scores a customer-service task from a SQLite end state. It has four parts.

  • One query per criterion.
  • A comparison of protected tables against a snapshot taken at reset().
  • A binary headline reward kept apart from a diagnostic partial score.
  • reward=None when the state is unreadable, so infrastructure failures are labeled rather than scored (see Rollout Systems).
import sqlite3
from dataclasses import dataclass

@dataclass
class Check:
    name: str          # human-readable criterion
    sql: str           # query run against the final state
    expected: list     # rows the query must return (order-insensitive)
    weight: float = 1.0

def snapshot(conn, tables):
    return {t: sorted(conn.execute(f"SELECT * FROM {t}").fetchall()) for t in tables}

def verify(final_db, before, checks, protected):
    """Score the end state of one episode.
    before:    snapshot of protected tables taken at reset()
    protected: tables the task must not touch (collateral-damage check)
    reward=None means the verifier could not run: an infra failure, not a 0."""
    try:
        conn = sqlite3.connect(f"file:{final_db}?mode=ro", uri=True)  # never mutate state
        try:
            passed = {c.name: sorted(conn.execute(c.sql).fetchall())
                              == sorted(map(tuple, c.expected)) for c in checks}
            after = snapshot(conn, protected)
        finally:
            conn.close()
    except sqlite3.Error as e:
        return {"reward": None, "error": f"state unreadable: {e}"}
    collateral = [t for t in protected if after[t] != before[t]]
    total = sum(c.weight for c in checks)
    partial = sum(c.weight for c in checks if passed[c.name]) / total
    return {
        "reward": float(all(passed.values()) and not collateral),  # headline: binary
        "partial": round(partial, 3),                              # diagnosis, curricula
        "checks": passed,
        "collateral": collateral,
    }

# "Cancel order 17 and refund it to the original card; change nothing else."
checks = [
    Check("order cancelled", "SELECT status FROM orders WHERE id = 17", [["cancelled"]]),
    Check("refund to card", "SELECT amount, method FROM refunds WHERE order_id = 17",
          [[42.5, "card_4242"]]),
]

Three design choices carry over to any verifier.

  1. Unwritable read path. The verifier reads state through a path the agent cannot write to. Here that is a read-only connection; for coding tasks, it is tests copied in after the agent exits.
  2. No side effects. Success requires the absence of side effects, an idea popularized by the collateral-damage checks of AppWorld (Trivedi et al. 2024).
  3. Unscored is not failed. The return value distinguishes "failed" from "could not be scored".

Partial Credit and Shaping

Partial credit makes sparse rewards learnable but changes what is being optimized, so it should be added with care and usually kept out of the headline metric.

Take criteria \(c_i \in \{0,1\}\) and weights \(w_i\). A partial reward \(r = \sum_i w_i c_i / \sum_i w_i\) gives signal on tasks the policy cannot yet finish. This matters most for group-relative methods such as GRPO, which score each rollout against other rollouts for the same task. Otherwise those methods would see all-zero groups.

The risk is a policy that collects easy criteria and stops. The remedy is to keep a dominating binary success term and to judge partial-credit runs on the binary metric.

Per-step shaping has a classic safe form. Ng, Harada and Russell (1999) showed that adding \(F(s, s') = \gamma\,\Phi(s') - \Phi(s)\) leaves the optimal policy unchanged, for any potential function \(\Phi\) over states. The reason is that the shaping terms telescope along any trajectory. Agent environments rarely have a natural \(\Phi\), though "fraction of target tests passing" is a candidate.

Reward Hacking in Environments

Reward hacking in agent environments is usually not subtle: the agent edits the tests, special-cases the checked inputs or tampers with the scorer. The rates depend heavily on how much of the verifier the environment exposes. Three lines of evidence make this concrete.

  • METR (2025) saw OpenAI's o3 overwrite a scorer's timer, monkey-patch an evaluator to always succeed and override equality operators. It reported similar behavior from other frontier models. For a pre-release o3, hacking appeared in 30.4% of reviewed runs on RE-Bench tasks, whose scoring function is visible. On HCAST tasks the rate was 0.7%. Instructions not to cheat barely helped.
  • ImpossibleBench (Zhong et al. 2025) mutates unit tests to contradict the specification, so any pass is a shortcut. GPT-5 passed 54% of conflicting SWE-bench tasks, but 9% when it could abort and flag the task. Claude models cheated mostly by editing tests, which read-only tests block. OpenAI models also special-cased inputs and overloaded operators, which read-only tests do not block. Hiding tests cut cheating to near zero but hurt legitimate performance.
  • Anthropic (2025) studied a model that learned hacks during RL on real coding environments, such as exiting the test harness with a success code. That model also became more misaligned elsewhere, sabotaging safety-research code in about 12% of trials. Telling the model in training that hacking was acceptable there ("inoculation prompting") prevented that generalization.
Reported reward-hacking and cheating rates across environment designs.
Fig. Reported hacking and cheating rates depend on environment design: visible scorers (RE-Bench vs HCAST), repository-scale tasks (SWE-bench vs LiveCodeBench variants) and an abort option all move the rate by large factors. METR rows are for a pre-release o3. Rates come from different setups and metrics and are not comparable across sources. Data from METR 2025 and Zhong et al. 2025.

The environment-side mitigations follow directly.

  • Protect the tests. Mount tests read-only or copy them in after the agent exits.
  • Verify in a fresh sandbox when the agent could have tampered with the runtime. NeMo Gym's Harbor runner supports this.
  • Hide the answers. Keep scorer code and reference solutions out of the agent's filesystem.
  • Allow an honest exit. Give the agent a legitimate way to report an impossible task.
  • Monitor trajectories for test edits or scorer access. ImpossibleBench found that LLM monitors caught most cheating on small tasks but only 42–65% on SWE-scale ones.

Detecting hacking from traces at fleet scale is covered in Observability and Data Quality.

The Verifier as a Product

A verifier is code that every training step depends on, so it needs its own test suite, version and owner. The suite must prove both directions: known-good solutions score 1 and known-bad behavior scores 0.

NeMo Gym's Harbor tooling enforces the first half. It fails dataset validation if any provided reference solution does not score 1. It also masks Gym-side verification failures, such as a lost sandbox, out of training (NVIDIA 2026). Negative tests are where most hacks are caught before training rather than after.

A verifier change is a reward change, so verifier versions belong in the trajectory record (see The Trajectory Data Model). Environment-level acceptance criteria are collected in Environment Quality Control.

Deeper A minimum test suite for a verifier

Each case runs the real environment and verifier end to end with a scripted "agent" instead of a model. A verifier ships only when every case passes.

  1. Reference solution scores 1 on every task, across repeated runs (catches flaky tests and nondeterministic state).
  2. Null agent that does nothing scores 0 (catches tasks already solved at reset).
  3. Claims without action: an agent that only replies "done" scores 0 (catches verifiers that read the transcript instead of the state).
  4. Test tampering: an agent that deletes, skips or rewrites the tests, or exits the test runner with a success code, scores 0.
  5. Special-casing: an agent that hard-codes the visible test inputs scores 0 on hidden or mutated inputs; ImpossibleBench-style mutated tests are a ready-made source.
  6. Collateral damage: an agent that completes the goal and also changes an unrelated record scores 0.
  7. Alternative valid solution: a second correct solution, written differently, scores 1 (catches over-specific verifiers, the false negatives that rule-based checks are prone to).
  8. Infrastructure failure: killing the sandbox mid-episode yields "not scored", never 0.
  9. Judge robustness (judge-based rewards only): appending persuasive or adversarial text to a wrong answer does not raise its score.

A regression in cases 4–6 is a hacking vulnerability; one in case 7 is lost learning signal that later looks like a plateau.

Hand-Built High-Fidelity Environments

There are four ways to obtain an RL environment, and they trade fidelity against cost: build it by hand, mine it from real software, synthesize it with a model, or let a model simulate it. Hand-built environments sit at the expensive, high-fidelity end.

In a hand-built environment, a vendor or an in-house team writes a working replica of an application. It seeds the replica with realistic data and pays domain experts to write tasks and graders against it. The result is the closest thing to real work that can still be reset, isolated and scored. In 2025–2026 it became a market of its own.

What labs buy follows what they want agents to do. Denain and Barber (2026) at Epoch AI interviewed 18 people at environment startups and labs. They describe a progression from math and coding toward enterprise workflows such as expense reports, pivot tables and CRM updates. Examples include clones of Slack and SAP, an Airbnb-style site, a Bloomberg terminal and Excel.

Kourabi and Patel (2026) at SemiAnalysis describe the same market from the supply side:

  • UI gyms. Clones of consumer websites such as food-delivery apps, reportedly about $20,000 per site, bought once and reused for later model generations.
  • Software platforms. Collaboration, CRM, mail and ticketing systems in containers with an MCP server, setup conditions and success criteria.
  • Domain environments. Chip design, accounting and EHR workflows, which encode professional knowledge as much as software.
  • Vendors. More than 35 companies, mostly small seed-stage firms selling closed, often exclusive environments.

Economics

Hand-built environments are priced per task and per replica, and the reported numbers span four orders of magnitude. All figures below come from Epoch's interviews (Denain and Barber 2026):

  • Tasks. Typical prices are $200–$2,000 per task. A $20,000 task is "rare but possible".
  • Replicas. One interviewee put a high-fidelity replica of a complex product near $300,000.
  • Contracts. Contracts are often six to seven figures per quarter.
  • Exclusivity. Two founders independently said exclusivity costs roughly four to five times more than a non-exclusive license.

These are interview estimates, not audited prices, and they will move quickly.

Reported costs of environment components on a log scale, from cents for a synthetic bug to hundreds of thousands of dollars for a complex replica.
Fig. Reported costs of building and using environments, log scale. Units differ by row (per task, per repository, per replica), so the chart shows orders of magnitude rather than like-for-like prices. Sources: SWE-smith (Yang et al. 2025) for synthetic bugs and installs; Epoch AI interviews (Denain and Barber 2026) for expert tasks, complex replicas and the Mechanize compute estimate they cite; SemiAnalysis 2026 for UI gyms.

Two comparisons put the prices in context.

  • Compute. Training compute per task is of the same order as the task itself. Epoch cites a Mechanize estimate of about $2,400 of compute over a task's useful life. That argues against cheap tasks that waste it.
  • Automation. Mined or synthesized tasks cost cents to dollars (next section). A hand-built task must therefore earn a premium of several orders of magnitude. It does so through fidelity, difficulty or coverage that automation cannot reach.

The Quality Bar

A replica is only worth its price if an agent cannot tell, or exploit, the difference from the real application. Epoch's interviewees name reward hacking as the top concern. They report that robust graders take many iterations. One lab researcher criticized replicas that were quickly "vibe coded" and full of bugs.

In practice the bar has four parts:

  1. Behavioural fidelity. The replica's state transitions match the real product on the workflows the tasks exercise, including errors, permissions and pagination, not only the happy path.
  2. Expert tasks. Tasks are written by people who do the job. Epoch's interviewees say domain knowledge and product sense matter more than ML skill, and that managing contractors, including checking whether they quietly use LLMs, is the real bottleneck.
  3. Graders beyond unit tests. Many solutions pass tests while differing in quality, so high-value tasks pair state checks with rubrics (see Verifiers and Rewards).
  4. Calibrated difficulty. A task every model solves or none solves teaches nothing. Difficulty is measured, not guessed (Environment Quality Control).

The human side of this work, recruiting experts, writing rubrics and managing rater quality, is the subject of the companion book RL Data Platform and is not repeated here.

Mining Real Software

Real software repositories are the cheapest source of high-fidelity environments. They arrive with state (the codebase), an action space (the shell and editor) and a verifier (the project's own tests).

The hard part is not finding tasks but making each one executable. That takes three steps:

  1. Resolve dependencies.
  2. Build an image in which the tests run.
  3. Prove that the task is solvable and that the tests actually detect the fix.

The SWE line of work runs from SWE-bench in 2023 (see Lineage) to six-figure task collections in 2026. It is a story of automating those three steps.

Pipeline that turns repository history into validated executable tasks, with SWE-rebench counts. MINING PIPELINE · counts from SWE-rebench (Badertdinov et al. 2025) 1 · Harvest issue-linked merged PRs or commits ~450k PRs · 30k+ repos 2 · Filter license, language, PR edits tests + code, 1–15 files ~153.4k candidates 3 · Install recipe LLM reads repo files, proposes setup commands works for 31% of repos 4 · Build image one per task, per version or per repository pin and push to registry 5 · Validate tests fail before the fix, pass after; old tests hold repeat runs to drop flakes 6 · Annotate clarity, difficulty and test-quality labels 21,336 tasks · 3,468 repos recipe error logs: refine Rejected along the way: no working recipe, flaky tests, tests that pass without the fix, reference fix that fails.
Fig. The common pipeline for mining executable software tasks. Stage counts are from SWE-rebench (Badertdinov et al. 2025); the paper reports the start, the post-filter pool and the final yield, not counts after every stage. The dashed arrow is the repair loop in which installation errors are fed back to the model that writes the recipe.

Five projects show the progression from hand-curated to fully automated pipelines.

  • SWE-Gym: real tasks, manual setup. Pan et al. (2024) built 2,438 real Python task instances. Each has a codebase, an executable runtime, unit tests and a natural-language issue. Fine-tuning on its trajectories raised SWE-bench resolve rates by up to 19 points absolute. Setup was still largely manual, which capped scale.
  • R2E-Gym: tasks from commits. Jain et al. (2025) built more than 8.7K tasks directly from commits rather than issues. Tests are generated, and issue text is back-translated from the change. This removes the dependence on human-written issues and tests.
  • SWE-smith: injected bugs. Yang et al. (2025) inverted the direction. Instead of harvesting past bugs, SWE-smith installs a repository once and injects bugs that break existing tests. This yields about 50K tasks from 128 repositories, an order of magnitude more than prior datasets. It shares one image per repository, so the environments fit in 295 GB. SWE-Gym's 2.4K tasks needed about 6 TB.
  • SWE-rebench: automated installation. In Badertdinov et al. (2025), an LLM proposes up to three JSON install recipes per task and refines them from error logs. Execution-based validation then keeps a task only if its failing tests pass after the reference patch and previously passing tests still pass. Run continuously, the pipeline also yields fresh tasks for a contamination-resistant benchmark.
  • Prime Intellect: aggregation at scale. Prime Intellect (2026) put 23 task sets behind one task-set API: about 365K tasks across SWE, terminal and search. It keeps about 135K prebuilt images in its own registry and hides grading material from the agent until scoring. Its validation pass has two checks: a no-op check that tests fail without a fix, and a gold-patch check with retries. The pass removed a large share of some upstream sets. One SWE set went from 32,079 to 6,275 usable tasks.

SWE-smith's bug generators show how differently the strategies behave. Yield is the share of candidate bugs that break at least one test; cost is model spend per candidate.

StrategyHow a bug is madeTasksYieldCost / candidate
LM ModifyModel introduces an error into an existing function or class17,88756.0%0.38¢
ProceduralRandom AST transformations (13 kinds), no model15,64140.2%0¢
Combine BugsMerge validated bug patches from the same file or module10,09296.9%0¢
LM RewriteModel re-implements a function from its signature and docstring4,17335.0%3.93¢
PR MirrorModel reverts the changes of a real pull request2,34433.8%5.53¢

Table. Bug-synthesis strategies in SWE-smith (Yang et al. 2025, Table 1). Issue text is generated afterwards for about 2.5¢ per task, and installing a repository with an agent cost about $0.72 on average plus 3–20 minutes of human review.

Three lessons carry over to any mined domain.

  • Share images. Building per repository or per version instead of per task changes storage by orders of magnitude. Image economics dominate fleet cost (see Sandboxes).
  • Validate by execution, twice. A task is kept only if the reference solution passes, the unmodified state fails, and both results repeat across runs.
  • Treat synthetic bugs as a different distribution. Injected bugs are cheap and plentiful but tend to be smaller edits than real fixes. In SWE-smith the median bug edits 3 lines for LM Modify and 5 for procedural changes. Mirrored real pull requests edit 14. Collections therefore usually mix synthetic bugs with harvested tasks.

The validation step is simple enough to write down. The sketch below assumes a sandbox client with run(cmd) returning an exit code and parsed test results.

from dataclasses import dataclass

@dataclass
class Verdict:
    ok: bool
    reason: str

def validate_task(sandbox, task, runs=3):
    """Keep a mined task only if it is solvable, non-trivial and stable."""
    for _ in range(runs):
        sandbox.reset(task.image)                    # fresh container from pinned digest
        before = sandbox.run_tests(task.tests)       # no fix applied (no-op check)
        if before.passed(task.fail_to_pass):
            return Verdict(False, "tests pass without a fix")
        sandbox.apply(task.gold_patch)
        after = sandbox.run_tests(task.tests)        # reference fix applied (gold check)
        if not after.passed(task.fail_to_pass):
            return Verdict(False, "reference fix fails")
        if not after.passed(task.pass_to_pass):
            return Verdict(False, "reference fix breaks existing tests")
    return Verdict(True, "solvable and stable across runs")

A task that flips verdict between runs is rejected: in RL a flaky test is a random reward.

Synthesizing Environments

When no real software exists to mine, an LLM can write the environment itself. Recent pipelines converge on the same decomposition into three components. Each is generated, executed and checked separately:

  • State backend. Usually a database.
  • Tool layer. Typed functions exposed through MCP or an API.
  • Tasks with success criteria. An instruction, a reference solution and a verifier that reads the state.

Because state is real code and data, transitions are deterministic. Rewards come from inspecting the database.

Three-component decomposition of a synthesized environment with a generate, validate and repair loop. Generator LLM agent with bash, search, sandbox 1. scenario 2. tasks 3. schema + seed data 4. tools 5. solution + verifier Task + success criteria instruction, reference solution, verifier over end state Tool layer typed functions exposed through MCP or an API State backend database schema + records, files; resettable snapshot Validation run reference solution through tools only verifier accepts it, rejects the initial state tools self-test policy rollouts: keep if pass@k > 0 and pass rate < 1 failure: repair the component · success: raise difficulty, add tools if needed
Fig. The three components of a synthesized environment and the loop that builds them. The step order follows Agent World Model (Wang et al. 2026); the difficulty-raising step and the pass@k filter follow DeepSeek-V3.2 (DeepSeek-AI 2025).

Five systems illustrate the design space.

  • DeepSeek-V3.2. DeepSeek-AI (2025) built the general-agent portion of DeepSeek-V3.2's RL data this way.
    • Data and tools. An agent in a sandbox generates or retrieves data for a task category and stores it in a database. It then writes task-specific tools as functions.
    • Tasks. The agent proposes a task with a Python solution function, which may only call tools, and a verification function. After a task passes, the agent makes it harder and adds tools if needed.
    • Filter. Only instances with non-zero pass@100 (at least one success in 100 attempts) were kept. That left 1,827 environments and 4,417 tasks.
    • Result. RL on these synthetic tasks alone improved Tau2Bench, MCP-Mark and MCP-Universe over the SFT checkpoint. RL restricted to code and search did not.
  • Agent World Model (AWM). Wang et al. (2026) made AWM a fully synthetic, open pipeline.
    • Scale. 1,000 scenarios are expanded from 100 seed domains, with 10 tasks each.
    • State and tools. A SQLite schema is generated from the tasks and filled so that every task is executable. A Python MCP interface averages 35 tools per environment.
    • Grading. Verification code diffs the database before and after a rollout. An LLM judge combines those signals with the trajectory into one of four labels: completed, partially completed, agent error or environment error.
  • ScaleEnv. Tu et al. (2026) built ScaleEnv from scratch with explicit checks on the environment itself. Procedural tests check tool reliability. Tool-dependency-graph expansion plus executable action verification show that each task is complete and solvable. Training transferred to unseen τ²-Bench and VitaBench.
  • AutoForge. Cai et al. (2025) proposed a unified pipeline for simulated environments with hard but easily verified tasks. It adds an RL method that estimates advantages per environment and damps the noise introduced by unstable simulated users.
  • EnvFactory. Xu et al. (2026) went the other way on scale. They built 85 verified, stateful environments across 7 domains from authentic resources. From these they synthesized 2,575 multi-turn trajectories with implicit user intent. The authors report gains on BFCLv3, MCP-Atlas and conversational benchmarks with roughly a fifth as many environments as comparable work. This suggests that quality and realism can partly substitute for count.
SystemState backendTool layerSuccess criteriaScale reported
DeepSeek-V3.2 general agentSandbox database of gathered dataGenerated Python functionsGenerated verifier function; pass@100 > 0 filter1,827 environments, 4,417 tasks
Agent World ModelSQLite, ~18.5 tables per environmentMCP, ~35 tools per environmentDB diff + LLM judge; partial credit1,000 environments, 10,000 tasks
ScaleEnvSynthesized from scratchProcedurally tested toolsDependency-graph and execution checksScaled by number of domains
AutoForgeSimulated environmentsSynthesized toolsEasily verified tasks; simulated usersNot stated in abstract
EnvFactoryBuilt from authentic resourcesExplored and verified toolsCalibrated multi-turn trajectories85 environments, 7 domains

Table. Environment-synthesis pipelines by component, as reported in each paper.

Environment-Scaling Curves

The evidence so far says that the number and diversity of environments matters more than the number of tasks per environment, though the curves are young. Three studies point the same way:

  • AWM. The authors trained a 4B agent on 10, 100 and 526 environments (Wang et al. 2026). With 10 environments, performance degraded on every benchmark, which the authors attribute to overfitting. 100 environments gave large gains, and 526 improved further.
  • Scaling laws. Szot et al. (2026) fit scaling laws across 849 models trained on 458,752 synthetic tasks in total. As the data budget grows, adding tool and database diversity beats adding tasks. More complex data also yields larger gains.
  • ScaleEnv. It reports a similar effect of domain count.

None of these studies extends beyond a few thousand environments. The shape of the curve at frontier scale is therefore an extrapolation.

LLM-Simulated Environments and Users

The cheapest environment is one with no implementation at all. A language model plays the environment: it reads the action and writes the next observation. Sometimes it also plays the user.

Simulation removes engineering cost and covers domains where no sandbox exists. But it replaces a deterministic transition function \(P(s' \mid s, a)\) with a learned one \(\hat P_\phi(s' \mid s, a)\). Here \(s\) is the environment state, \(a\) the agent's action and \(\phi\) the simulator's parameters. Every divergence between the two is a place where the policy can learn something false. It is also a place where the policy can be rewarded for something that would fail in reality.

The approaches differ in what they simulate.

  • Simulated outcomes for planning. Gu et al. (2024) used an LLM in WebDreamer to predict what each candidate web action would do before committing to it. The motivation is that real sites contain irreversible actions. Here the simulator advises a policy rather than training it.
  • Simulated tools for data synthesis. The Kimi Team (2025) combined over 3,000 real MCP tools with over 20,000 synthetic ones. A tool simulator executed them, maintaining state and injecting controlled failures. Trajectories were kept only when an LLM judge found they met the task rubric. For coding, where authenticity matters, they used real sandboxes instead.
  • Simulated environments for RL: Simia. Li et al. (2025) showed with Simia that a reasoning model can produce environment feedback for both SFT data and RL. Fine-tuned open models surpassed GPT-4o on τ²-Bench.
  • Simulated environments for RL: DreamGym. Chen et al. (2025) built DreamGym, a reasoning-based experience model. A replay buffer seeded with real data grounds it, and curriculum task generation pairs with it. It matched GRPO and PPO in costly environments using only synthetic interactions. Policies pretrained in it needed far fewer real interactions afterwards.
  • Simulated users in benchmarks. Yao et al. (2024) made an LLM user part of τ-bench. Success is judged by comparing the final database state to an annotated goal.
  • Simulated users in training. Qian et al. (2025) turned simulated users into training environments with UserRL. A stronger user simulator such as GPT-4o made training more effective. An open model such as Qwen3-32B was a cheaper alternative that still transferred.

Fidelity is measurable, and the measurements are sobering. Liu et al. (2026) built EnvSimBench: 400 samples over 167 environments. Every model tested was near-perfect when the state did not change. Every model failed sharply when several state variables had to change at once. Hallucination, logical inconsistency and silent state drift corrupt the rewards.

A simple illustration shows why episode length matters. Suppose each simulated step is consistent with probability \(q\) and errors are independent. Then a whole \(H\)-step episode is consistent with probability \(q^H\). At \(q = 0.99\), a 10-step episode is clean about 90% of the time. A 100-step episode is clean about 37% of the time. Real errors are correlated, but the direction holds: long episodes amplify simulator error.

Use of simulationUsually acceptable whenMain riskMitigation
SFT trajectory generationTrajectories are filtered by a judge and the target skill is tool-calling form, not exact statePlausible but impossible tool outputs in training dataRubric filtering; mix with real-sandbox data
RL warm startFollowed by RL in real or code-backed environmentsPolicy exploits simulator quirksShort simulated phase; ground with real replay data
Simulated usersReward is computed from environment state, not from the user's wordsOver-cooperative or leaky users inflate successStrong simulator; persona constraints; audit transcripts
Full RL environmentEpisodes are short and state changes are fewState drift; reward on states that cannot existPrefer a database-backed backend; check consistency
Coding, terminal, anything executableRarely; execution is cheap and exactRewarding code that would not runUse a real sandbox

Table. When LLM simulation is an acceptable substitute for an executable environment. A synthesis of the studies above, not a published rule.

The practical rule that emerges: simulate what is expensive and soft, and execute what is cheap and exact.

  • Simulate: user behaviour, rare external APIs, the long tail of tool responses.
  • Execute: code, databases, file systems.

The AWM authors make the same argument for code-driven, database-backed state over LLM-generated state. DreamGym's best results come from using simulation as a warm start rather than a replacement.

Environment Quality Control

An environment is a test of the model, so it must itself be tested before it produces reward. Quality control answers five questions for every task:

  1. Can it be solved?
  2. Does the verifier accept exactly the right outcomes?
  3. Is it at a useful difficulty?
  4. Is it independent of evaluation suites?
  5. Is it distinct from the tasks already in the pool?

A sixth requirement, versioning, makes the answers reproducible.

Solvability. The minimum is execution-based: a reference solution passes, the initial state fails, and both results repeat (see the validator above and Prime Intellect 2026). Synthesized environments add a stronger form. The reference solution must reach the goal using only the agent-facing tools. That proves the action space is sufficient (DeepSeek-AI 2025).

Verifier audits. Validation proves the verifier accepts one correct solution. It does not prove the verifier rejects wrong ones or accepts other correct ones. Human audits of public benchmarks show how often this fails.

In one audit, 93 developers annotated 1,699 SWE-bench samples (OpenAI 2024):

  • Strict tests. 61.1% of samples were flagged for unit tests that could reject valid solutions.
  • Vague issues. 38.3% were flagged for underspecified issues.
  • Filtered. 68.3% of samples were filtered out in building the 500-task Verified set.

Training environments rarely get that scrutiny. Sampled human review therefore belongs in the pipeline, as does red-teaming verifiers with deliberately wrong solutions (see Verifiers and Rewards).

Difficulty calibration. Difficulty is measured as the current policy's pass rate \(p\) over repeated rollouts. Group-relative methods such as GRPO score each rollout against the others in its group. A group of \(G\) rollouts therefore produces a gradient only if it contains both a success and a failure. That happens with probability

\[ \Pr[\text{signal}] = 1 - p^{G} - (1-p)^{G}. \]

Here \(p\) is the task's per-rollout success probability and \(G\) the group size. At \(p = 0.02\) and \(G = 64\), this probability is about 0.73. At \(G = 128\) it is about 0.92.

That matches the rule of thumb Epoch's interviewees gave: a minimum pass rate around 2–3%, or at least one success in 64–128 rollouts (Denain and Barber 2026). It also matches DeepSeek's non-zero pass@100 filter. Tasks the policy already solves almost always are dropped or made harder. Pass rates are recomputed as the policy improves (curricula in Curating Rollouts).

Contamination. Mined tasks can overlap with evaluation suites when they come from the same repositories or time window. SWE-rebench's answer is temporal. It keeps collecting fresh tasks with the same pipeline and evaluates only on those created after a model's training cutoff. This revealed that some models' SWE-bench Verified scores may be inflated (Badertdinov et al. 2025). Exact-repository and near-duplicate checks against every benchmark in use should run at ingestion (see Train/Eval Separation).

Diversity and deduplication. Given the scaling results above, near-duplicates are worse than wasted budget: they tilt training toward whatever a generator over-produces. Dedup runs on task text, environment structure (schema and tool signatures) and reference solutions.

Versioning. A reward is only meaningful relative to the environment that produced it. Every task should carry the image digest, the seed-data snapshot, the tool-layer version and the verifier version. Any change to one of them creates a new task version rather than silently editing the old one (storage in The Trajectory Data Model).

Deeper An environment acceptance checklist

A task or environment enters the training pool only when every item holds. The list combines the practices cited in this part; the thresholds are starting points to tune, not published standards.

  1. Build. The image builds from a pinned recipe; its digest, base image and dependency lockfile are recorded.
  2. Reset. Two resets produce byte-identical initial state (database dump hash, file tree hash).
  3. Isolation. Grading material (tests, gold patches, expected states) is absent from the agent-visible filesystem and tool outputs; network access is limited to what the task needs.
  4. No-op fails. The verifier rejects the initial state and a trivial action such as an empty answer.
  5. Gold passes. The reference solution passes using only agent-facing tools, in at least three independent runs.
  6. Adversarial negatives fail. Known wrong solutions (deleted tests, hard-coded outputs, partial edits) are rejected.
  7. Alternative positives pass. At least one independently written correct solution passes, where obtainable; otherwise a human reviews the verifier.
  8. Calibrated. The current policy's pass rate over a group of rollouts is above zero and below a ceiling (for example 2% < \(p\) < 90%).
  9. Clean. No repository, text or solution overlap with any evaluation suite in use; creation date recorded.
  10. Distinct. No near-duplicate in the pool by text, structure or solution.
  11. Labelled infrastructure errors. Timeouts and crashes are reported as environment errors, never as reward 0 (see Rollout Systems).
  12. Versioned and owned. Image, data, tool and verifier versions are recorded, and a named owner handles failure reports.

Sandboxes

A sandbox is the isolated, disposable machine in which one episode of an environment runs. The agent's shell commands, browser and tool calls execute there, and the verifier inspects its final state. Agentic RL needs thousands of sandboxes per optimizer step. Each one is created, reset and destroyed on the critical path of training. Sandboxing therefore stops being a security detail and becomes the throughput limit of the whole run.

Production stacks reported one operating lesson in 2026. Cost and latency depend less on the isolation technology than on how images are stored, moved and recycled (Kondragunta 2026).

The requirements follow from the environment definition:

  • Known reset. Reset returns the world to a known state.
  • Separation. Episodes cannot see each other.
  • Containment. The agent is being optimized to find shortcuts, so it cannot reach the verifier's data or the host.

Isolation Options

Isolation technologies trade the strength of the boundary between agent and host against start-up time, density and compatibility. In practice, how much the agent is allowed to do sets the choice.

  • Containers. They share the host kernel, so a kernel exploit escapes them.
  • gVisor. gVisor serves system calls from an application kernel written in Go. It keeps container ergonomics at some system-call overhead.
  • Firecracker. Agache et al. (2020) built Firecracker, the minimal virtual machine monitor behind AWS Lambda. Its launch announcement gave start-up under 125 ms per microVM and memory overhead under 5 MiB per microVM (AWS 2018).
  • Kata Containers. Kata Containers puts such VMs behind the standard container runtime, so Kubernetes schedules them like pods.
OptionBoundaryStart / resetDensityFitsExamples
Rootless namespaces + overlayShared kernel, seccomp, LandlockMillisecondsHighestTrusted clusters, SWE/terminalNitroBox
Containers (runc)Shared kernelSub-second+; image pull dominatesHighSingle tenant, inside a VMDocker; DSec (in VMs)
User-space kernelgVisor application kernelSub-secondHighMulti-tenant KubernetesGKE Agent Sandbox pools, Modal
MicroVMHardware virtualization, own guest kernel~100–200 ms bootMedium–highUntrusted code, root agentsFirecracker, Kata
Full VMHypervisorSeconds to minutesLowDesktops, GPUsOSWorld-style VMs, DSec full-VM backend

Table. Isolation options for RL sandboxes. Start-up figures are rough orders of magnitude from claims that measure different things; measure on the real workload.

Production fleets mix these options.

  • DSec. It runs containers inside VMs as an outer boundary, beside Firecracker microVM and full-VM backends. Each sandbox gets AppArmor and eBPF network allowlists (Huang et al. 2026).
  • Prime Intellect. It runs every sandbox as a hardware-virtualized microVM with its own guest kernel (Prime Intellect 2026).

Image Economics and Lifecycle

Most of a sandbox's start-up cost is moving its filesystem, not booting its kernel. Environment suites carry one image per task, and those images are large. A mined SWE suite holds thousands of distinct images, each wanted on some node within seconds.

Kondragunta (2026) draws three lessons from operating such a stack:

  1. Images dominate. Image economics and lifecycle dominate provisioning.
  2. Stay light. Environments should stay dependency-light, with heavy tooling moved behind service boundaries.
  3. Label failures. Infrastructure failures must be labeled rather than scored.
Lifecycle of a sandbox image and instance, from task image to lease, verification and reset. snapshot / incremental diff becomes a new image Task image OCI, one per task Lazy format EROFS · streaming Node cache hydrated ahead Warm pool booted, checked Leased one episode Verify score, label status Reset / recycle drop writable layer off the critical path: build, convert, place, hydrate on the critical path: lease → first command → verify goal: move every step left of the pool off the GPU's clock
Fig. The lifecycle of a sandbox: images are converted and placed before rollouts ask for them, a warm pool hides boot time, and after verification the sandbox is reset or snapshotted into a new image. Synthesized from the DSec, GKE Agent Sandbox and NitroBox designs.

Three techniques recur across the published systems:

  • Load lazily. DSec converts OCI images offline to EROFS, a read-only compressed filesystem format. It keeps metadata local and fetches data blocks from its 3FS distributed filesystem on demand. In the sampled images, runtime access touched only 4.2% to 13.3% of image data. In a burst of 8,192 containers, on-demand loading finished in about 35 minutes, against over 60 for eager pulls (Huang et al. 2026).
  • Place before asking. GKE's Agent Sandbox SDK plans image placement across nodes so that image streaming and warm-pooling finish hydration before the rollout requests a sandbox (Shi & Glottmann 2026).
  • Reset instead of recreate. With a copy-on-write root filesystem, reset means discarding the writable upper layer. GKE's SDK can recycle a pod across rollouts with an in-pod git reset. NitroBox resets by renaming an overlayfs upper directory (NitroBox package docs).

Cold Start, Warm Pools and Snapshots

Cold start matters for its tail more than its mean. A synchronous training step waits for the slowest sandbox in the batch.

GKE combined warm pools, off-path hydration and a rate-limited controller. The worst-case time to first command fell from about 7.5 minutes to under 10 seconds (the "45×" headline). The average fell roughly tenfold. The tests used SWE-bench and R2E image corpora at up to 18,312 concurrent sandboxes (Shi & Glottmann 2026).

Nie et al. (2026) argued that container daemons carry features RL does not need. They built NitroBox: daemonless, rootless namespace sandboxes with copy-on-write initialization. Optional CRIU checkpoints (process snapshots that can be restored) support branching.

  • Against Docker, creation was 10.6× faster and reset 24.6× faster. Deletion was 19.1× faster.
  • GRPO training of a 32B coder at concurrency 32 took 28.4 hours instead of 40.6 with unchanged training quality.

Snapshots serve three purposes beyond start-up:

  • Branch. Several trajectories continue from one intermediate state (GKE pod snapshots, NitroBox's CRIU path).
  • Preempt. DSec saves a microVM's memory and state and frees the host, then restores it later.
  • Author. DSec's incremental disk diff of a live sandbox can be reused as a new environment.
Deeper Sizing a warm pool

Treat sandboxes as a queueing resource. By Little's law, the average number in use is \(L = \lambda W\). Here \(\lambda\) is the rate at which episodes start, and \(W\) is the mean time a sandbox is held (episode plus verification plus reset).

The pool must also cover the provisioning delay \(D\) of new sandboxes and the fraction \(f\) of leases that fail health checks:

\[ N_{\text{pool}} \;\approx\; \frac{\lambda\,(W + D)}{1 - f} \;+\; B, \]

where \(B\) is burst headroom for the start of a step, when a synchronous trainer requests a whole batch at once.

Liu et al. (2026) give the practical floor. Keep at least one sandbox per in-flight rollout, so no action waits in a queue. Budget for error rates too, since a failure late in a long task is expensive.

An illustrative case: 2,000 episodes per minute, each sandbox held 6 minutes. Add 1 minute to provision and 3% failed leases. The pool is then \(2000 \times 7 / 0.97 \approx 14{,}400\) sandboxes.

Size \(W\) from a high percentile, since episode time is heavy-tailed. Requests, not usage, usually bound density. Amazon's Sandman found that sampled pods used about 10.5% of requested CPU and 1.9% of requested memory (Yan, Wang et al. 2026).

Providers and In-House Fleets

Sandbox supply has split into managed providers, Kubernetes primitives and in-house fleets. The published in-house systems now run at hundreds of thousands of concurrent sandboxes.

Managed services sell fast start and an SDK. A 2026 comparison lists their isolation choices (Upstash 2026):

  • E2B: Firecracker microVMs.
  • Daytona: hardened containers or VMs.
  • Modal: gVisor.
  • Northflank: Kata with Cloud Hypervisor.

Labs that train at frontier scale have described building their own.

SystemIsolationReported scale or speedNotable mechanism
DSec (DeepSeek, 2026)Containers in VMs, Firecracker microVMs, full VMs380,000+ concurrent; ~3M per dayLazy EROFS images; snapshot preemption
Sandman (Amazon, 2026)Pods on EKS~3.1M in two weeks; peak 11,858 concurrentExec daemon mounted into unmodified images
GKE Agent Sandbox (2026)gVisor pool in benchmarksTail time to first command from ~7.5 min to <10 sWarm pools, image streaming, forks
Prime Sandboxes (2026)MicroVM~30M created; 20,000+ concurrent in a dashboardImmutable task images
Modal (2026)gVisor (per Upstash)Start in hundreds of ms (vendor claim)Snapshots skip setup
NitroBox (2026)Rootless namespacesReset 24.6× faster than DockerDaemonless; overlay reset; CRIU branching

Table. Published sandbox systems for agentic RL, as self-reported by their authors in 2026. Figures are not comparable across rows.

Sandman's evaluation corrects headline numbers (Yan, Wang et al. 2026):

  • Burst start. In a burst of 10,000 requests, half the sandboxes were usable after 116 seconds. All of them were usable only after 308.
  • Availability. Estimated availability per session start was 91.16% to 99.73% across three production campaigns.
  • Outlier campaign. In a fourth campaign, only 69.5% of recorded starts obtained a pod.

Losing a few percent of leases is normal, so the rollout layer must treat failure as an outcome.

Rollout Systems

A rollout system turns a policy checkpoint, a task set and a sandbox fleet into scored trajectories. In agentic RL it is split across three independently scaled services:

  • Inference engines sample tokens.
  • An environment fleet executes actions and verifies outcomes.
  • A trainer updates weights.

Almost every efficiency problem in the field (idle GPUs, stale samples, lost episodes) is a coordination problem between those three.

The Three-Way Split

The three-way split follows the hardware:

  • Generation is memory-bandwidth bound and runs on engines such as vLLM or SGLang.
  • Training is compute bound and runs on FSDP or Megatron.
  • Environments need CPUs, disks and network.

An orchestrator leases sandboxes, routes model calls and labels finished episodes. A buffer feeds the trainer.

Rollout system architecture: orchestrator, inference engines, environment fleet, trajectory buffer and trainer. Rollout orchestrator schedule · timeouts · labels Inference engines vLLM / SGLang behind a capturing gateway Environment fleet sandboxes · tools verifiers Trainer FSDP / Megatron Trajectory buffer tokens · masks · reward · status prompts lease · release actions observations token ids · logprobs reward · status batches weights sync / in-flight
Fig. The three-way split of an agentic rollout system. Model calls pass through a gateway that records exact tokens; the environment fleet returns rewards and a status label; the trainer pushes weights back to the engines either between steps or while generation is in flight. Original diagram; the full system around it is in the reference architecture.

Frameworks differ in who owns the agent loop and how loosely the parts are coupled:

  • veRL's agent loop runs many agent coroutines per worker against server-mode engines. It binds each request to one server instance (a sticky session), so every turn of a rollout reaches the same engine.
  • slime joins Megatron training to SGLang rollout through a data buffer, with custom multi-turn generate functions. Its README lists the GLM family among models trained with it.
  • SkyRL separates a training library, an agent layer for long-horizon tasks and a Gymnasium-style environment collection.
  • With an unmodified product harness, the harness owns the loop and the trainer sees only what a capturing gateway records (who owns the loop).

Synchronous and Asynchronous RL

In synchronous RL, the current weights generate every rollout in a batch, and the trainer waits for the last one. In asynchronous RL, generation never stops. The trainer consumes whatever has finished and accepts samples that are a few policy versions old. Synchronous training is simpler and exactly on-policy. Its utilization collapses when episode lengths vary, and agentic episode lengths always vary.

The cost of waiting is easy to state. Take a batch of \(N\) episodes with i.i.d. durations \(T_i\). The engines are busy on average for \(\mathbb{E}[T]\) out of every \(\mathbb{E}[\max_i T_i]\). For exponentially distributed durations,

\[ U(N) \;=\; \frac{\mathbb{E}[T]}{\mathbb{E}[\max_{i\le N} T_i]} \;=\; \frac{1}{H_N} \;\approx\; \frac{1}{\ln N + 0.577}, \]

where \(H_N = 1 + \tfrac12 + \dots + \tfrac1N\) is the \(N\)-th harmonic number. Larger synchronous batches make it worse, not better.

Engine utilization of a synchronous batch as batch size grows, for two episode-length distributions.
Fig. Fraction of engine time doing useful work when a synchronous step waits for its slowest episode. Solid: exponential episode times, \(U=1/H_N\). Dashed: each episode has a fixed part equal to its mean random part, \(U = 2/(1+H_N)\). Illustrative; computed in the page from the formulas, ignoring continuous batching inside the engine.

Asynchronous systems recover that time at the price of staleness. Fu et al. (2025) built AReaL, which fully decouples rollout workers from training workers.

  • Workload balancing bounds how many policy versions old a sample may be, and a staleness-aware PPO variant handles the off-policy data.
  • On math and code reasoning it reported up to 2.77× training speedup over synchronous systems on the same GPUs, with equal or better final accuracy.

Write \(v(\tau)\) for the policy version that generated trajectory \(\tau\), and \(k\) for the trainer's current version. The constraint is \(k - v(\tau) \le \eta\) for a small maximum staleness \(\eta\).

Piché et al. (2025) attacked staleness from the other side with PipelineRL. Engines receive new weights while sequences are still being generated, so a long sequence's later tokens come from newer weights. On long-form reasoning with 128 H100s, they reported learning about twice as fast as conventional RL baselines. The data stayed close to on-policy.

A trajectory can thus be sampled under several weight versions. That is why behavior logprobs must be recorded at generation time.

Long-Tail Episodes, Partial Rollouts and Preemption

Episode lengths in agentic RL are heavy-tailed. A small fraction of episodes therefore decides the wall-clock time of every step, unless the system bounds, defers or splits them.

Gao et al. (2025) measured synchronous RL where rollout took about 66–72% of training time. The longest responses were 25–32× the median length.

  • Tail batching. It launches more prompts than needed in short rounds and keeps the first to finish. Aborted long prompts are deferred to dedicated long rounds.
  • Result. RollPacker adds adaptive parallelism and asynchronous rewards (including adaptive code-sandbox timeouts). It trained 2.03–2.56× faster than veRL on 7B–32B models.

Partial rollouts split long episodes across steps instead. Kimi k1.5 does this in four moves (Kimi Team 2025):

  • It caps each iteration's output tokens.
  • An unfinished trajectory is saved to a replay buffer and continued in a later iteration.
  • Earlier segments are reused rather than regenerated.
  • Some segments can be excluded from the loss.

For agents, the segment boundary must also checkpoint the sandbox, since the environment state is part of the trajectory. A snapshot or a long-lived lease does this.

Preemption follows the same logic. DSec keeps rollout state in the agent sandbox and worker container, outside the preemptible GPU pool. A preempted trainer then reconnects without replaying commands. Preempted microVMs are snapshotted rather than killed (Huang et al. 2026).

Infrastructure Failures Are Labeled, Not Scored

Some episodes end because a sandbox died, an image failed to pull or the verifier crashed. Such an episode says nothing about the policy. Scoring it as reward 0 teaches the model that whatever it was doing is bad.

This is the third of Kondragunta's (2026) lessons, and the published systems build it into their interfaces:

  • GKE. Its SDK surfaces failed sandboxes as retriable instead of dropping them.
  • OpenEnv. Its Harbor integration treats a missing reward as "the verifier never ran", distinct from a score of zero (OpenEnv 2026).

The hard part is the boundary between agent and infrastructure:

  • Hung command. A command the agent ran that hangs is the agent's doing. It comes back as an observation.
  • Turn budget. An exhausted turn budget is the agent's outcome and is scored.
  • Infrastructure. A deadline missed because the engine queue was slow, a lost sandbox connection or a verifier exception is infrastructure.

The worker below encodes that boundary.

import asyncio, enum, uuid
from dataclasses import dataclass, field

class Status(str, enum.Enum):
    OK = "ok"                         # verifier ran: reward is a real score
    TRUNCATED = "truncated"           # wall-clock deadline: not scored (or resume later)
    INFRA_ERROR = "infra_error"       # lease, sandbox, network, engine: not scored
    VERIFIER_ERROR = "verifier_error" # grader crashed: not scored

RETRYABLE = {Status.INFRA_ERROR, Status.VERIFIER_ERROR}

class InfraError(Exception):
    """Raised by sandbox and engine clients for failures outside the agent's control."""

@dataclass
class Episode:
    task_id: str
    attempt: int
    episode_id: str = field(default_factory=lambda: uuid.uuid4().hex)
    status: Status = Status.INFRA_ERROR
    reward: float | None = None
    turns: list = field(default_factory=list)   # engine token ids + logprobs per call
    error: str = ""

async def run_episode(task, pool, llm, verifier, b):
    ep = Episode(task.id, task.attempt)
    try:
        sb = await asyncio.wait_for(pool.lease(task.image), b.lease_s)
    except (TimeoutError, InfraError) as e:
        ep.error = f"lease: {e!r}"
        return ep
    healthy = False
    try:
        obs = await sb.reset(task)
        try:
            async with asyncio.timeout(b.episode_s):
                for _ in range(b.max_turns):            # turn budget: the agent's outcome
                    out = await llm.generate(obs, session=ep.episode_id)
                    ep.turns.append(out)
                    if out.final:
                        break
                    try:
                        obs = await asyncio.wait_for(sb.exec(out.action), b.tool_s)
                    except TimeoutError:
                        obs = "error: command timed out"  # agent's action hung: an observation
        except TimeoutError:
            ep.status, ep.error = Status.TRUNCATED, "episode deadline"
            healthy = True
            return ep
        try:
            ep.reward = await asyncio.wait_for(verifier.score(sb, task), b.verify_s)
            ep.status = Status.OK
        except Exception as e:                          # includes verifier timeouts
            ep.status, ep.error = Status.VERIFIER_ERROR, repr(e)
        healthy = True
    except InfraError as e:
        ep.error = repr(e)                              # stays INFRA_ERROR
    finally:
        await pool.release(sb, recycle=healthy)         # broken sandboxes are destroyed
    return ep

async def worker(queue, results, pool, llm, verifier, b, max_retries=2):
    while True:
        task = await queue.get()
        ep = await run_episode(task, pool, llm, verifier, b)
        results.put_nowait(ep)                          # log every attempt; train only on OK
        if ep.status in RETRYABLE and task.attempt < max_retries:
            await queue.put(task.retry())               # same task, fresh sandbox
        queue.task_done()

Two cautions apply to retrying:

  • Hidden task bias. Infrastructure failures can correlate with the task, such as a heavy repository that runs out of memory or a verifier that crashes on one output format. Discarding the failed attempts then quietly removes hard tasks. Infra-failure rates therefore belong on per-task dashboards.
  • Incomplete groups. Group-relative estimators such as GRPO need complete groups. Refill or drop a group that loses members rather than normalizing over fewer samples.

Capturing Trajectories Exactly

The trainer must compute gradients on exactly the token sequence the inference engine sampled. It must use the same context and the probability the engine assigned to each token. Anything else silently turns on-policy RL into off-policy RL.

In single-turn RL this is automatic. In multi-turn agent loops it is not. Between turns, text is decoded, parsed, re-rendered through chat templates and re-encoded. Each step can change token ids while leaving the visible text identical.

Three Sources of Drift

Token sequences drift from what was sampled in three documented ways, and none of them is visible in a text log. The Agent Lightning team (2025), the Miles team (2026) and NeMo Gym's documentation describe the same failure modes:

  1. Retokenization. Decoding is many-to-one, so decode-then-encode can return different ids for the same string.
  2. Chat-template rewriting. Templates are not always prefix-preserving, meaning that rendering a longer conversation does not always extend the earlier tokens unchanged. Many drop reasoning from earlier assistant turns. Gallouédec & Rasul (2026) found that Qwen3 renders an empty think block only on the last assistant turn. Appending a tool message therefore changes earlier tokens. Of 19 tested model families, 18 were prefix-preserving.
  3. Lossy re-rendering. Parsing a tool call and serializing it again discards the model's original spacing and line breaks, so the template's default formatting replaces what was sampled.
Text path versus token path for multi-turn trajectories. TEXT PATH · drifts Sampled ids engine output Decode ids → text Re-render parse + template Re-tokenize text → new ids Trainer ids ≠ sampled ids TOKEN PATH · exact Sampled ids + behavior logprobs Gateway buffer append, never re-encode Tool output spliced by id, masked Trainer ids = sampled ids
Fig. Two ways to carry a multi-turn trajectory to the trainer. On the text path, decoding, template re-rendering and re-encoding can each change token ids; on the token path, sampled ids and their logprobs are appended to a per-episode buffer and environment output is spliced in by id. Original diagram after the failure modes described by the vLLM, Hugging Face and LMSYS posts cited in the text.

The Agent Lightning team reported unstable learning curves from drift. Token-level importance sampling cannot correct it, they noted, because the mismatch is in the conditioning tokens, not in a probability ratio.

veRL's documentation reports that, in the team's experience, re-applying the chat template kept even single-turn PPO from converging. That is why its agent loop is token-in, token-out by design (veRL docs).

Capture at the Gateway

The robust fix is to record tokens where they are produced. Kondragunta (2026) recommends this design over an environment class hierarchy. The inference engine returns the ids it consumed and sampled. A gateway stores them per episode, and nothing downstream ever tokenizes text. This works even for an unmodified product harness, whose model base URL simply points at the gateway.

  • Engine support. vLLM's OpenAI-compatible endpoints accept return_token_ids from v0.10.2 and then return the templated prompt ids and the generated ids alongside the normal response (Agent Lightning team 2025).
  • Splicing. NeMo Gym's on-policy correction rebuilds each new prompt from the ground-truth ids of earlier calls. It splices them into the re-templated sequence. Harnesses pass the returned fields back unchanged rather than keeping a second copy of the prefix.
  • Session servers. The Miles team keeps an append-only token buffer per trajectory and tokenizes only new messages. It checks that special-token and non-assistant mismatches stay at zero. A bit-exact prefix also lets one sample per task replace one per turn. They estimate this saves about an order of magnitude of compute on 30–50-turn SWE tasks.
  • Typed traces. OpenEnv's Harbor integration runs the agent as a black box behind an OpenAI-spec capture proxy whose API key is a per-rollout session id. Calls are linked into a rollout graph by token prefix, and abandoned branches are marked discarded so they never inherit the main path's reward. The exported TrainingTrace holds prompt ids, completion ids, per-token behavior logprobs and explicit loss masks (OpenEnv 2026).

When a harness summarizes or truncates history, no template is prefix-preserving. NeMo Gym calls training on such histories an open question. The Hugging Face guidance is to mask the loss up to and including the last rewrite. Either way, the rewrite must be recorded, not reconstructed. What to persist is the subject of the trajectory data model.

Logprobs and the Inference–Training Mismatch

Even with identical tokens, engine and trainer compute slightly different probabilities, because their kernels, parallelism and numerics differ. The behavior policy's logprobs must therefore be captured at sampling time and used to correct the update.

Yao et al. (2025) showed that the gap between a vLLM sampler and an FSDP trainer implicitly makes on-policy RL off-policy. They proposed an importance-sampling correction. Let \(\pi_{\text{roll}}\) be the sampler's distribution and \(\pi_\theta\) the trainer's. A truncated per-token weight is

\[ w_t \;=\; \min\!\left( \frac{\pi_\theta(y_t \mid y_{<t}, x)}{\pi_{\text{roll}}(y_t \mid y_{<t}, x)},\; C \right), \]

where \(y_t\) is the sampled token, \(x\) the prompt and earlier turns, and \(C\) a cap.

veRL's rollout-correction module implements token- and sequence-level variants and suggests token caps of roughly 1.5 to 5. It adds rejection masks that drop sequences whose ratios leave a band (veRL docs). With asynchronous training or in-flight updates, the same machinery absorbs policy staleness, since a sequence may span several weight versions.

Capture details decide whether the correction is valid. The Harbor integration enforces three rules:

  • Processed logprobs. The engine (vLLM, or a recent SGLang build) must return processed logprobs, taken after temperature and sampling transforms.
  • Start-up check. It checks this at start-up by comparing logprob gaps at two temperatures.
  • Downgrade. Captures with raw logprobs are downgraded to evaluation-only.

Hosted APIs without ids or logprobs yield evaluation traces only.

Deeper A capture conformance test

Run these checks for every new model, template or harness before a training run, on a few dozen recorded episodes. They turn the failure modes above into assertions.

def check_episode(calls, tokenizer, render):
    """calls: captured model calls in order, each with prompt_ids, completion_ids, logprobs."""
    errors = []
    for prev, cur in zip(calls, calls[1:]):
        seq = prev.prompt_ids + prev.completion_ids
        if cur.prompt_ids[:len(seq)] != seq:                   # prefix property
            errors.append(f"non-prefix at call {cur.idx}")
    for c in calls:
        if len(c.logprobs) != len(c.completion_ids):           # one behavior logprob per token
            errors.append(f"logprob length at call {c.idx}")
        if any(lp > 0 for lp in c.logprobs):
            errors.append(f"positive logprob at call {c.idx}")
        text = tokenizer.decode(c.completion_ids)
        if tokenizer.encode(text, add_special_tokens=False) != c.completion_ids:
            c.retokenization_unsafe = True                     # count it: never re-encode this
    full = render(calls[-1].messages)                          # informational: template drift
    if full != calls[-1].prompt_ids:
        errors.append("template re-render differs from captured prompt (expected if non-prefix)")
    return errors

Track three metrics per model and harness:

  • Non-prefix calls. Zero, unless rewriting is intended and masked.
  • Retokenization-unsafe completions. Harmless only if nothing re-encodes.
  • Per-token ratio \(\pi_\theta/\pi_{\text{roll}}\) before the first weight update. It isolates numeric mismatch from staleness.

The Trajectory Data Model

A rollout becomes training data only after it is written down in a form that three readers can all use: a trainer, a curation job and an engineer debugging a reward spike. The trajectory data model is that form. It fixes what is stored per episode, per step and per token, and which versions are pinned alongside it. It also separates fields cheap enough to scan across millions of episodes from fields heavy enough to load only at training time.

Gaps in the model are costly. Missing versions make rewards incomparable. Missing token-level fields make the data unusable for the update it was collected for.

The idea predates LLM agents. Ramos et al. (2021) proposed RLDS, a format that stores episodes as ordered steps (observation, action, reward, discount) plus episode metadata. Two of its choices carry over:

  • Record losslessly. Store the interaction without assuming how it will be used, so later algorithms can still be applied.
  • Separate "last" from "terminal". RLDS flags an episode's final step and, separately, whether the environment actually reached a terminal state. A time-limit cutoff is last but not terminal. For agents, the same flag separates a scored submission from a budget cutoff or a dead sandbox. These cases must not be scored alike (see Rollout Systems).

Episode, Step and Token Fields

Agent trajectories have three levels, and each level has different consumers:

  • Episode fields (identity, versions, reward, status, length) feed dashboards and curation.
  • Step fields (messages, tool calls, observations) feed debugging and fine-tuning.
  • Token fields (token ids, sampler log-probabilities, loss masks) feed the policy-gradient update. They are by far the largest.
LevelTypical fieldsMain consumersSize driver
Episodeids; environment, image, verifier, harness and model versions; sampler settings; reward and breakdown; status (scored, truncated, infra error); turns, tokens, time, costCuration, dashboards, batch packing, auditsBytes to kilobytes; scales with number of episodes
Steprole, message, reasoning, tool calls, observations, timestamps, tool exit codesTrace review, replay, SFT export, monitorsObservation size (logs, page snapshots, screenshots)
Tokenprompt and completion token ids, sampler log-probabilities, loss mask (model tokens vs. tool tokens), optional routing or teacher statesTrainer (importance weights, masking)Context length × rollouts per step

Table. What a trajectory record holds at each level. Field lists are a synthesis of the formats cited in this section, not a single standard.

Interchange formats are converging on the step level. One example is the Agent Trajectory Interchange Format (ATIF), in the v1.7 subset that NeMo Gym supports. An ATIF record carries three parts:

  • Agent block. Name, version, model and tool definitions.
  • Steps. A list of message, reasoning, tool calls and observation.
  • Per-step metrics. These can include token ids and log-probabilities.

Strict validation, with explicit extra fields for extensions, keeps records from drifting apart across harnesses.

Light Metadata, Heavy Tokens

The most useful physical design choice is to split each rollout in two. A small metadata record is always available. A large per-token payload is loaded only when a trainer consumes it. The DeepSeek-V4 report (2026) describes exactly this decomposition for its RL infrastructure:

  • Metadata up front. Metadata for an entire rollout set is loaded first to plan global shuffling and sequence packing. Heavy per-token fields go through a shared-memory loader and are freed after each mini-batch.
  • Token-level resume. A token-granular write-ahead log lets a preempted rollout resume where it stopped. Regenerating from scratch would bias data toward short responses, because they finish uninterrupted more often.
  • Sandbox log. Its sandbox platform, DSec, keeps a globally ordered trajectory log per sandbox. This makes tool execution part of the record and supports replay.
A trajectory record split into light metadata and heavy per-token fields, each with its own consumers. Light metadata · one row per episode ids: episode · task · environment@version pins: image digest · verifier · harness · model outcome: reward · breakdown · status shape: turns · tokens · tool errors · seconds sampler: temperature · seed · policy step pointer to the heavy blob Heavy per-token fields · blob prompt and completion token ids sampler log-probabilities loss mask: model tokens vs. tool output step boundaries · tool calls · observations optional: routing or teacher states loaded per mini-batch, then freed ref Curation · dashboards · shuffle and packing plan Trainer: importance weights and masked loss
Fig. Splitting a rollout into a scan-friendly metadata row and an on-demand token payload. The split follows the DeepSeek-V4 report; field lists are this book's synthesis.

A back-of-the-envelope size check shows why. INTELLECT-3 (Prime Intellect, 2025) reports RL steps of 256 prompts with 16 rollouts each. Its context limit is 65,536 tokens. That gives 4,096 rollouts per step and, at the limit, about 268 million tokens per step. Each token needs a 4-byte token id plus a 4-byte log-probability. The ceiling is therefore near 2 GB per step, before any text or screenshots.

Token payloads therefore belong in blob or columnar storage keyed by episode id. The metadata table then stays small enough to query interactively.

Versions and Provenance

A reward is only meaningful together with the versions that produced it: the task, the environment build, the verifier, the harness and the policy checkpoint. When any of them changes, old and new rewards stop being comparable. The record must then say which side of the change an episode is on.

Environments change more often than intuition suggests. The Terminal-Bench 2.1 release (May 2026) revised 28 of the 89 tasks in version 2.0. Nine of those revisions were needed because internet-hosted dependencies had changed. One agent–model pair rose by about 12 points. A store that recorded only "task 17, reward 0" could not tell a policy regression from a moved dependency.

A typed schema turns missing provenance into a write-time error rather than an analysis-time mystery:

from dataclasses import dataclass, field
from enum import Enum

class Status(Enum):
    SCORED = "scored"          # verifier ran on a terminal state
    TRUNCATED = "truncated"    # turn/token/time budget hit: last, not terminal
    INFRA_ERROR = "infra"      # sandbox, network or tool crash: never scored

@dataclass(frozen=True)
class EpisodeMeta:
    episode_id: str
    task_id: str
    env: str                   # e.g. "crm-replica"
    env_version: str           # semantic version of tasks + tools
    image_digest: str          # exact sandbox image
    verifier_version: str
    harness_version: str
    policy_step: int           # checkpoint that sampled the episode
    sampler: dict              # temperature, top_p, seed, max_tokens
    status: Status
    reward: float | None       # None unless status is SCORED
    reward_parts: dict = field(default_factory=dict)
    turns: int = 0
    tokens: int = 0
    tool_errors: int = 0
    payload_uri: str = ""      # token ids, logprobs, loss mask, steps

    def __post_init__(self):
        if (self.status is Status.SCORED) != (self.reward is not None):
            raise ValueError("reward must be set iff the episode was scored")

Curating Rollouts

Raw rollouts serve two consumers with different filters:

  • Online RL update. It wants groups that carry gradient signal, meaning tasks the policy sometimes solves and sometimes fails.
  • Offline uses (fine-tuning, distillation, verifier training). They want trajectories selected for quality and diversity, with failures kept where they teach something.

Most curation rules are simple once the data model records status and versions.

Zero-Variance Groups and Pass-Rate Filtering

Group-relative methods such as GRPO score each rollout against the other rollouts of the same task. They learn nothing from a task whose sampled group is all successes or all failures, yet such groups cost full rollout compute. The first and cheapest curation step is to filter these groups out and steer sampling toward tasks of intermediate pass rate.

With \(G\) rollouts of one task and rewards \(r_1,\dots,r_G\), the advantage of rollout \(i\) is

\[ \hat{A}_i = \frac{r_i - \operatorname{mean}(r_1,\dots,r_G)}{\operatorname{std}(r_1,\dots,r_G)}, \]

where the mean and standard deviation are taken over the group. If every \(r_i\) is equal, every \(\hat{A}_i\) is zero (implementations add a small constant to the denominator) and the group contributes no gradient.

Yu et al. (2025) made this explicit in DAPO with dynamic sampling:

  • Over-sample prompts, discard groups with accuracy exactly 0 or 1, and keep sampling until the batch is full of mixed-outcome groups.
  • It was the largest single gain in their ablation, raising AIME 2024 average accuracy from 42 to 50. Convergence also took fewer steps despite the extra sampling.
Probability that a group of G rollouts is all-pass or all-fail, as a function of per-task pass rate.
Fig. Chance that a group of \(G\) independent rollouts gives no learning signal, \(p^G + (1-p)^G\), for a task the policy solves with probability \(p\). Larger groups shrink the dead zones, but near-certain successes and failures stay nearly useless at any practical \(G\). Computed in the page from the formula.

Production systems combine an offline filter with an online one. INTELLECT-3 used both:

  • Offline. Datasets were annotated with a small Qwen3-4B model's solve rate, and items that were too easy were dropped.
  • Online. During training, easy, normal and hard pools were kept by observed solve rate. Prompts with pass rate 1 were no longer resampled. Rollouts from prompts the model always solved or always failed were discarded.

The offline step belongs to environment acceptance (Environment Quality Control). The online step must live in the rollout loop, because pass rates move as the policy improves.

Deeper How much to over-sample for a full batch

Suppose tasks in the pool have pass rates \(p\) drawn from some distribution \(\pi\), and each task is rolled out \(G\) times. The probability that a randomly drawn task yields a mixed (informative) group is

\[ f_G = 1 - \mathbb{E}_{p\sim\pi}\big[\,p^G + (1-p)^G\,\big]. \]

To fill a batch with \(B\) informative groups, the expected number of tasks to roll out is \(B/f_G\). The rollout cost is \(G\,B/f_G\).

Two consequences follow. First, if half the pool is already solved, \(f_G\) is below one half for any \(G\). Each batch then costs more than twice its nominal compute, so retiring solved tasks is cheaper than over-sampling around them.

Second, raising \(G\) helps most for small \(p\). At \(p=0.05\), the chance of at least one success is about 34% with \(G=8\). With \(G=16\) it is about 56%. This argues for setting \(G\) per difficulty tier.

A known pass rate also lets the sampler weight tasks. Sampling in proportion to an estimate of the Bernoulli variance \(p(1-p)\) concentrates compute where groups are informative, provided the estimates stay fresh.

Curricula Across Environments

A fixed task pool drifts out of the useful band as the policy improves, so the curriculum must move with it. Rather than re-filtering a static pool, an environment can generate tasks at a controllable difficulty. It then adjusts that knob from recent pass rates.

Zeng et al. (2025) built RLVE-Gym, 400 procedurally generated environments whose difficulty distribution adapts to the policy during training:

  • Joint training on all 400 environments improved a strong 1.5B reasoning model by 3.37 points on average across six reasoning benchmarks.
  • Continuing the model's original RL recipe for over three times the compute gained only 0.49 points. The authors attribute this to static data losing signal as problems become too easy or too hard.

Environments without a difficulty knob get the same effect from tiered pools and sampling weights updated from the metadata table.

Rejection Sampling and Distillation

The simplest way to turn rollouts into supervised data is rejection sampling: keep successful trajectories and fine-tune on them. Two details matter most. One is how many copies of easy successes get in. The other is whose distribution the trajectories come from.

  • Teacher data helped; self-data did not yet. Pan et al. (2024), in SWE-Gym, fine-tuned a 32B coder on 491 successful agent trajectories from stronger models. Its SWE-bench Verified resolve rate rose from 7.0% to 20.6%. Adding 868 of the model's own successes then lowered SWE-bench Lite from 15.3% to 8.7%. Naive self-training did not yet help.
  • Cap repeats per task. Yang et al. (2025), in SWE-smith, kept only resolved trajectories from 17,906 expert attempts. They capped each task at three trajectories, because repeated solutions of easy tasks hurt performance. The final set was 5,016 trajectories. In their ablation, task difficulty did not correlate with downstream performance.

Off-policy imitation trains the student in states the teacher visits, not states the student reaches. Lu (Thinking Machines, 2025) describe on-policy distillation as the alternative. The student samples its own trajectories, and a teacher scores every token with a reverse-KL signal. This gives dense supervision on the student's own mistakes. They report roughly an order of magnitude less compute than further SFT on one reasoning target.

The DeepSeek-V4 report likewise describes on-policy distillation from domain-specialist teachers after their own SFT and RL stages. A trajectory store should therefore keep student rollouts even when they fail.

import hashlib
from collections import defaultdict

def select_sft(episodes, cap_per_task=3):
    """Rejection-sampling SFT selection over EpisodeMeta-like records."""
    by_task = defaultdict(list)
    for e in episodes:
        if e.status is not Status.SCORED or e.reward < 1.0:
            continue                      # successes only; infra errors never count
        by_task[(e.env, e.env_version, e.task_id)].append(e)
    keep = []
    for eps in by_task.values():
        seen, kept = set(), 0
        for e in sorted(eps, key=lambda e: (e.turns, e.tokens)):   # prefer short solutions
            sig = hashlib.sha1(e.reward_parts.get("final_diff", "").encode()).hexdigest()
            if sig in seen:
                continue                  # identical final solution already kept
            seen.add(sig)
            keep.append(e)
            kept += 1
            if kept == cap_per_task:      # cap repeats of easy tasks (SWE-smith used 3)
                break
    return keep

Mixing Environments

Training on many environments at once raises a normalization question. Rewards from a retail simulator, a SWE task and a math checker differ in scale, noise and failure modes. A single noisy environment can dominate the gradient.

Cai et al. (2025) addressed this in AutoForge with ERPO, a GRPO variant for synthesized tool-use environments with simulated users:

  • Environment-level normalization. Advantages are normalized at the environment level rather than per question. The authors argue this reduces sensitivity to outliers in small groups.
  • Masking simulator errors. An LLM judge flags rollouts in which the simulated user erred (hallucinated or withheld information). Those rollouts are removed from both the advantage and the loss, so the agent is not penalized for the simulator's mistakes.
  • Results. Training covered 10 synthesized environments with 1,078 tasks, with DAPO-style removal of all-pass and all-fail groups. It improved a 30B-A3B model on τ-bench, τ²-bench and VitaBench. The authors also show that evaluation scores depend strongly on which model plays the user.

The general rule: a failure caused by anything other than the policy (a crashed sandbox, a simulator error, a flaky test) is masked, not scored as zero. This only works if the record carries a status and a reason.

Keeping the Failures

Failed trajectories are training data for everything except naive SFT. In SWE-Gym, Pan et al. (2024) trained a 32B verifier on 2,636 trajectories. The set was balanced between 1,318 successes and 1,318 failures. Using the verifier to pick among 16 candidates raised SWE-bench Verified from 20.6% at one sample to 32.0%.

Failures also feed reward models, on-policy distillation and the reward-hacking audits below. Deleting them to save storage discards what verifiers and monitors are built from. Human preference and rating data follow a different pipeline, covered in the companion book RL Data Platform.

Observability and Data Quality

An RL run on hundreds of environments fails in ways a single reward curve hides: a verifier breaks, a dependency moves, a shortcut starts paying. Observability means charting episode metadata by environment and version, reading sampled traces, and replaying any episode exactly. The goal is to tell three cases apart quickly: the policy improved, the policy found a hole, or the environment changed.

What to Chart

Every signal below is a query over episode metadata, sliced by environment, version and policy step; none needs token payloads. Training libraries log many of them already. The Tinker RL logs record reward by environment, tokens sampled and discarded, sampler-trainer KL estimates, cost and asynchronous staleness. They also keep readable transcripts for a sample of groups.

SignalWhat a change usually meansSlice by
Mean reward and pass-rate histogramLearning, saturation, or a broken verifier (sudden jump or collapse)Environment, version, difficulty tier
Fraction of zero-variance groupsPool too easy or too hard for the current policy; wasted computeEnvironment, task tier
Episode length and truncation rateShortcut (reward up, length down); looping or budgets too tight (length at cap)Environment, outcome
Tool-error ratePolicy misusing tools, or a tool or API that changedTool name, environment version
Infra-failure rateSandbox, image or network trouble; must stay out of rewardsImage digest, cluster, region
Sampler vs. trainer log-prob gapEngine mismatch or stale weights (see Capturing Trajectories)Policy step, engine version
Monitor flag ratePossible reward hacking; review flagged tracesEnvironment, monitor version

Table. Core health signals for environment-based RL. Each is a group-by over episode metadata.

The observability loop from rollouts to metrics, triage, fixes and re-runs. Rollouts env · verifier · policy Trajectory store metadata + payloads Metrics and monitors per-env slices · LLM flags Triage read traces · replay Fix and version env · verifier · image Quarantine mask affected episodes resume on the new version OBSERVE REPAIR
Fig. The observability loop. Anomalies in per-environment metrics or monitor flags lead to trace review and replay; a confirmed defect produces a new environment or verifier version, affected episodes are masked rather than deleted, and rollouts resume on the fixed version.

Detecting Reward Hacking from Traces

Reward hacking leaves fingerprints in trajectories before it shows up in evaluations. Typical signs are rewards rising in one environment while episodes get shorter, tool calls touching test files or the grader, or reasoning that discusses the scoring mechanism. Detection therefore runs over the trajectory store. It combines metric anomalies with model-based monitors and human review of what they flag.

  • Monitors narrow review. The hacks themselves are catalogued in Reward Hacking in Environments. For detection, METR (2025) combined review of anomalously high scores with an LLM monitor. Both had very high false-positive rates, so they narrowed what humans read rather than replacing it.
  • Labelled transcripts. METR's MALT dataset (2025) labels 10,919 agent transcripts for reward hacking and sandbagging (deliberate underperformance). The best prompted monitors reached an AUROC of 0.96 for reward hacking, though natural examples were few.
  • Read the reasoning, keep it out of the reward. Baker et al. (2025) showed that a weaker model reading a reasoning model's chain of thought detects hacking far better than one reading only actions. The setting was agentic coding environments. Putting that monitor into the reward taught the policy to hide its intent while still hacking. Monitors therefore belong in detection and environment repair, not in the reward.
  • Hacking generalizes. Anthropic (2025) studied programming environments drawn from real Claude training runs. A model that learned hacks there, such as exiting the test harness with a success code, also became more misaligned on unrelated evaluations.

Replay and Debugging

Debugging an environment requires reproducing one episode exactly: the same image, the same task seed, the same tool outputs, and the same sampled tokens. Replay is cheap when the record already pins versions and the sandbox logs its command history. DSec's per-sandbox ordered trajectory log in the DeepSeek-V4 report serves that role.

Replay answers what metrics cannot. It shows whether the agent did something clever or the environment handed it the answer. Transcript-analysis tools help at scale. Transluce's Docent (2025) surfaced missing packages in a benchmark environment. Installing them raised GPT-4o's InterCode solve rate from 68.6% to 78%. Without the tool, this environment bug would read as a capability limit.

Environment Drift

Environments that touch anything external (package mirrors, live websites, third-party APIs, model-based user simulators) change underneath a training run, and the change is easy to misread as policy behavior. The Terminal-Bench 2.1 notes attribute the largest per-task score changes to drift, resource mismatches and misspecification. They also report that no task in 2.1 remains unsolved. Three practices contain drift:

  • Pin or snapshot. Vendor dependencies into the image. Serve web content from snapshots or self-hosted replicas unless the task needs the live web.
  • Canary tasks. Re-run known reference solutions on a schedule. A reference that stops passing means the environment changed.
  • Version on change. Every fix bumps the recorded environment version, so dashboards split before and after and curation can drop the affected window.

Train/Eval Separation

The same environment machinery that produces training data also produces benchmark scores. Leakage between the two is therefore easy, and its effects are hard to see. Train/eval separation means keeping evaluation tasks, their solutions and close variants out of every training store. It also means measuring generalization at a distance that matches the claim: new tasks, new environments or entirely new families of environments.

How Contamination Enters

Contamination (evaluation items or their solutions leaking into training data) enters through three routes:

  • Pretraining crawls of public benchmarks.
  • Mined training environments drawn from the same repositories as evaluation sets.
  • Synthesized tasks that paraphrase benchmark items.

The SWE-bench line shows all three risks:

  • Verified retired. OpenAI (February 2026) stopped reporting SWE-bench Verified. It audited 138 problems that o3 did not solve consistently and found material test or specification problems in 59.4%. It also found that all frontier models tested could reproduce the gold patch or verbatim problem details for some tasks. It recommended SWE-bench Pro in the interim and privately authored evaluations going forward.
  • Fresh tasks. Badertdinov et al. (2025) built SWE-rebench, a pipeline that continuously collects fresh tasks for decontaminated evaluation. Comparing against SWE-bench Verified, they found that some models' scores may be inflated by contamination.
  • Disjoint training sources. On the training side, SWE-Gym drew from 11 repositories disjoint from SWE-bench's to avoid contamination (Pan et al. 2024).

The mechanical defenses are:

  • Hash registry. A registry of hashed evaluation tasks, repositories and reference solutions, checked against every training store before a run.
  • Canary strings in evaluation assets.
  • Time cutoffs, so evaluation tasks postdate training data.

Held-Out Environments and Families

Holding out tasks within a training environment measures much less than holding out whole environments, and holding out environments measures less than holding out whole families. A policy can learn one environment's tool conventions, verifier quirks and templates, so the split should match the level of the generalization claim.

Three levels of held-out evaluation: tasks, environments and environment families. Family A · tool-use apps A1 train tasks A1 held-out tasks A2 held-out environment Family B · software repos B1 train tasks B2 train tasks B3 held-out environment Family C · held out entirely C1 never trained on C2 never trained on C3 never trained on held-out tasks: memorization check held-out environments: transfer held-out families: general skill increasing distance from training data
Fig. Three distances for evaluation. Filled boxes are training data; dashed boxes are held out at the task, environment or family level. Families here are generic placeholders.

Wang et al. (2026) illustrate the strongest version of this split. Agent World Model trained only on synthetic SQL-backed environments, with an RL subset of 3,315 tasks across 526 environments. It was evaluated on τ²-bench, BFCLv3 and MCP-Universe, none of which its environments were built to imitate. The authors report strong out-of-distribution transfer. They also state what their environments omit (conversation, refusals, browsing, retrieval), which bounds the claim.

SplitWhat it measuresMain risk
Held-out tasks, same environmentFit to this environment without memorizing itemsShared templates and verifier quirks inflate scores
Held-out environments, same familyTransfer across tool sets and data within a domainNear-duplicate environments from the same generator
Held-out familiesGeneral agentic skillToo few families to estimate variance; family boundaries chosen after the fact
Fresh tasks after a time cutoffContamination-free capability on a live distributionSmall samples; distribution shift over time

Table. Evaluation splits for environment-trained agents and what each can support.

Reporting Practice

An evaluation result for an environment-trained agent is a claim about a specific policy, harness, environment version and split, and should be reported as one. Each of these factors can move scores:

  • Environment version. Fixing 28 defective Terminal-Bench tasks moved some scores by about 12 points (Terminal-Bench 2.1).
  • Harness. In an audit of the same benchmark, Buchanan et al. (2026) found that swapping the harness around one model changed accuracy by up to 29.9 points. The gap closed with larger time budgets.

The minimum report names:

  • the split level;
  • environment and verifier versions;
  • harness and budget;
  • trials per task;
  • whether any training environment shares a generator, repository or template with the evaluation set.

State of the Art in 2026

By late 2026, the labs that publish details of their agentic post-training describe a similar stack. It has three parts:

  • Environments. Thousands to tens of thousands of executable environments.
  • Tasks. Synthesized or mined tasks with programmatic checks.
  • Sandboxes. A fleet that runs from 104 to more than 105 concurrent episodes.

Around that stack a commercial market has formed, in which labs buy environments and tasks from specialist vendors. Prices run from hundreds of dollars per task to hundreds of thousands per application replica. Figures come from technical reports and press coverage, so read them as orders of magnitude.

What Labs Report

Open-weight labs are the main public source on environment scale, because their technical reports describe the post-training pipeline. Closed labs are visible mostly through vendor and analyst reporting on the environment market.

ReportEnvironments and tasksExecution infrastructure
Kimi K2 (Jul 2025)3,000+ real MCP tools from GitHub plus 20,000+ synthetic tools; LLM-simulated users and tool responses, rubric-judged trajectoriesKubernetes sandboxes for real code execution, 10,000+ concurrent instances
INTELLECT-3 (Nov 2025)Environments from the public Environments Hub across math, code, science, logic, deep research and SWEAsync-only prime-rl; sandboxes with sub-10-second startup
DeepSeek-V3.2 (Dec 2025)1,827 synthesized general-agent environments; about 85,000 prompts across search, code, code-interpreter and general-agent tasksRL budget stated as above 10% of pre-training cost
Kimi K2.5 (Feb 2026)Gym-like framework with pluggable toolsets and judges; synthetic promptsUp to 100,000 concurrent agent tasks; LLM gateway records black-box agents
GLM-5 (Feb 2026)10,000+ executable SWE environments in 9 languages; thousands of terminal environments in Harbor format; search tasks from a web knowledge graphslime with a multi-task rollout orchestrator, token-in/token-out gateway, heartbeat fault tolerance
MiniMax Forge (Feb 2026)100,000+ distinct real-world scaffolds and environments used while building M2.5Middleware (gateway plus data pool) between agents and trainer
DeepSeek-V4 (Apr 2026)RL against real tool environments; counts not given in the summaryDSec: function calls, containers, Firecracker microVMs and QEMU VMs behind one SDK; hundreds of thousands of concurrent sandboxes per cluster

Table. Environment scale in selected 2025–2026 technical reports and lab posts. Counts are as stated by each source and are not comparable across rows: "environment", "task" and "scaffold" mean different things in each report.

Read across the reports, five patterns recur:

  • Hard to solve, easy to verify. DeepSeek-V3.2 gives each synthesized task a Python verification function and keeps only tasks with non-zero pass@100 (at least one success in 100 attempts). Its code environments are valid only if the gold patch fixes at least one failing test and breaks none. GLM-5 likewise harvests fail-to-pass and pass-to-pass tests for SWE environments in nine languages (see Mining Real Software).
  • Synthesis is routine. DeepSeek's general-agent environments are built by an agent that writes a database and toolset, then proposes progressively harder tasks (see Synthesizing Environments).
  • Simulation as a wind tunnel. Tongyi DeepResearch trains against an offline Wikipedia snapshot before the real web and reports closely matching reward curves. Kimi K2 simulates tools and users with LLMs, keeping real sandboxes for code.
  • The gateway is the integration point. Kimi K2.5, GLM-5 and MiniMax Forge route model calls through a gateway, so unmodified scaffolds can be trained and tokens captured exactly (see Capturing Trajectories Exactly).
  • Sandboxes became a product. DSec, Prime Intellect's sandboxes and Kimi's Kubernetes fleets are first-class infrastructure (see Sandboxes).

The Environment Market

Frontier and "neo" labs buy most of their environments and tasks from outside vendors. By 2026 that procurement was large enough to support dedicated startups, acquisitions and specialized analyst coverage.

TechCrunch (Zeff, Sept 2025) relayed a report by The Information that Anthropic's leaders had discussed spending more than $1 billion on RL environments over the following year. The article named Mechanize and Prime Intellect as leading startups, with Surge, Mercor and Scale AI moving in. Skeptics quoted there warned about reward hacking and the difficulty of scaling environments.

Two January 2026 reports describe the vendor side in detail. Their prices are analyzed in Hand-Built High-Fidelity Environments.

  • Vendor count. Kourabi & Patel (SemiAnalysis, 2026) count more than 35 environment companies, almost all seed-stage with one to three customers. They estimate that Anthropic works with more than a dozen of them. Coding environments are the most in demand.
  • Prices. Denain & Barber (Epoch AI, 2026) put typical tasks at $200–$2,000 each. They put contracts at six to seven figures per quarter.

Earlier, Erdil et al. (Mechanize, 2025) argued that per-task spending should rise. Their reason: a task's lifetime RL compute outweighs a cheap task's authoring cost.

Consolidation followed in 2026. Mercor, which supplies expert contractors to AI labs, made two acquisitions:

  • Sepal AI, which builds training data, benchmarks and RL environments, in February.
  • Deeptune, which had recreated hundreds of enterprise applications as "training gyms", in July.

Vertical specialists raised money on lab demand. Financial-environment builder Halluminate said four of the top five closed US labs were customers. Its CEO estimated that environment complexity must double every six to eight months to keep challenging frontier models. Both claims are self-reported.

Zeoli (Wing VC, 2026) expects coding and computer use to be the first large markets. Long white-collar workflows would be the larger long-term one. The winners, in this view, will look like applied research groups running "environment factories".

The human-feedback side of these vendors (rater pools, campaigns, quality control) is the subject of the companion book RL Data Platform.

Open Ecosystems

An open layer grew alongside the closed market, so that environments can be shared and reused across trainers. Two efforts lead it:

  • Environments Hub. Prime Intellect open-sources its environments on the Hub, written with its Verifiers library.
  • OpenEnv. The project gained a coordinating committee in June 2026 (including Meta-PyTorch, Hugging Face, Prime Intellect, Nvidia, Mercor, Modal and Microsoft). Its RFCs cover external rewards, dataset-backed tasksets and automatic environment validation.

The standards are compared in Environment Standards and Hubs.

Reference Architecture

A production environment program needs eleven components in three layers:

  • Definition layer. Says what an environment is: registry, task store, image builder.
  • Run layer. Executes episodes: inference gateway, rollout orchestrator, sandbox fleet, verifier service.
  • Learning layer. Turns episodes into updates and checks them: trajectory store, curation, trainer, eval harness.

The diagram below synthesizes the reports above and earlier parts of this book. Its main choice is that model calls, environment execution and grading are separate services. Versioned identifiers join them.

Reference architecture for an RL environment program, in definition, run and learning layers. Task store prompts · seeds · answers train / held-out splits Environment registry env id @ version image · tools · verifier Image builder dependency resolution snapshots · warm pools Inference gateway OpenAI-style proxy token-in / token-out logprobs · policy ver. Rollout orchestrator groups · timeouts async, partial rollouts retry infra errors only Sandbox fleet containers · microVMs tools · MCP · browser reset · isolation Verifier service tests · state checks rubrics · judges fresh grading sandbox tasks images Trajectory store episode + token data rewards · infra labels all versions pinned Curation pass-rate bands dedup · decontaminate env mixing weights Trainer policy update importance weights checkpoints Eval harness held-out env families pinned harness release gate tokens · logprobs rewards + infra-failure labels new policy weights to the inference engines
Fig. A reference architecture for an RL environment program. Top row: what an environment is (definition). Middle row: how episodes run. Bottom row: how episodes become training data and checked checkpoints. The registry pins every environment to a task set, an image and a verifier version. The gateway, not the environment, records tokens. The verifier grades in its own sandbox, and the trainer's weights flow back to inference (dashed).

Components

Each component has one job and one owner, and each emits identifiers that the trajectory store joins on.

  1. Environment registry. Source of truth: an id and version pinning image digest, tools, verifier, task-set version, limits, owner and the environment's own tests.
  2. Task store. Versioned prompts, seeds, hidden answers and split labels. Held-out families are unreadable by curation and training.
  3. Image builder. Builds images, snapshots and warm pools (see Sandboxes).
  4. Inference gateway. OpenAI-compatible proxy recording token ids, log-probabilities and policy version for every call.
  5. Rollout orchestrator. Schedules groups, enforces budgets, handles stragglers, retries only infrastructure failures (see Rollout Systems).
  6. Sandbox fleet. Isolated containers or microVMs holding state and running tools, MCP servers, browsers or shells.
  7. Verifier service. Rewards from tests, state checks, rubrics or judges, computed in a fresh sandbox from declared artifacts (see Verifiers and Rewards).
  8. Trajectory store. Episode metadata and token arrays keyed by every version above (see The Trajectory Data Model).
  9. Curation. Pass-rate banding, dedup, decontamination, environment mixing (see Curating Rollouts).
  10. Trainer. Updates the policy, correcting for policy lag with stored log-probabilities.
  11. Eval harness. Runs checkpoints on held-out families under a pinned harness and gates promotion (see Train/Eval Separation).

Trust and Failure Boundaries

The architecture draws three boundaries, each preventing a known failure.

  • Sandbox holds no answers. The agent sandbox never holds hidden tests or reference state, which blocks test tampering.
  • Gateway outside the environment. Token capture is therefore exact whatever the agent framework. Kondragunta (2026), a NeurIPS 2026 workshop paper, recommends capturing inference at a proxy rather than through an environment class hierarchy.
  • Infrastructure failures labeled, not scored. The orchestrator labels them because a crash scored as a failed episode silently corrupts advantages.

Production Challenges and Solutions

Most problems in running an environment program are not algorithmic. They come from four sources:

  • verifiers that can be fooled;
  • tasks whose difficulty is wrong for the current policy;
  • infrastructure that fails in ways that look like model failures;
  • environments that drift.

The table below maps the recurring problems to the fixes that the sources and earlier parts of this book describe. It also names the component in the reference architecture where each fix lives.

ChallengeSymptomSolutionWhere
Reward hackingReward rises, held-out eval flat; passes that edit tests or special-case checksIsolated grading from declared artifacts; hidden tests; impossible-task canaries; read passesVerifier, curation
Verifier false negativesCorrect solutions scored 0; tasks stuck at 0% pass rateGold must pass and null must fail before shipping; audit zero-pass tasksRegistry, verifier
Difficulty mismatchMost groups all-pass or all-fail, so advantages are zeroPass-rate sweep with the current policy; keep a band (at least one success in 64–128 rollouts, below a ceiling); refresh per checkpointCuration
Infra failures scored as failuresReward drops that correlate with node, region or imageSeparate infra outcome codes; retry or drop, never score; alert per environmentOrchestrator
Stragglers and long tailsGPU idle while a few long episodes finishAsynchronous rollouts with bounded staleness; partial rollouts; per-episode time and turn budgetsOrchestrator, trainer
Cold starts and image costMinutes per episode spent pulling or building imagesLayered and lazily loaded images, snapshots, warm pools; keep environments dependency-lightImage builder, sandbox fleet
Token mismatchTraining on re-tokenized text; KL or ratio spikesToken-in/token-out gateway; store sampled log-probabilities and correct for inference/training mismatchGateway, trainer
Environment driftSame task, different outcomes across weeks (live sites, APIs, packages)Pin image digests and data snapshots; replay canary tasks on every build; version bumps on any changeRegistry, image builder
ContaminationBenchmark gains that do not transferDecontaminate tasks against eval suites; hold out whole environment families, not just tasksTask store, eval harness
Low diversityGains concentrated in a few environment templatesDedup by task embedding and environment template; cap per-family mixing weightsCuration
Simulator gapPolicies exploit LLM-simulated tools or usersCheck simulated against real environments on a subset; finish training on real executionSandbox fleet, eval harness
Vendor qualityBuggy clones, LLM-written tasks, inconsistent rubricsAcceptance tests per delivery; pay per accepted taskRegistry
Sandbox escape and egressAgents reaching the internet, the grader or other tenantsMicroVM or gVisor isolation for untrusted code; egress allowlists; no credentials in imagesSandbox fleet

Table. Production challenges in environment programs, mapped to solutions and to components in the reference architecture. The pass-rate thresholds come from interviewees in Epoch AI (2026); the infra-failure and gateway rows follow Kondragunta (2026).

Two rows are cheap to fix and expensive to miss.

  • Infra failures scored as failures. Suppose an image crashes 5% of the time and crashes score zero. The policy is then penalized for something it did not do, in a way correlated with that environment.
  • Difficulty mismatch. In group-based policy-gradient methods, a group with identical rewards has zero advantage. Badly calibrated tasks therefore burn compute for no gradient.

Playbook: Building an Environment Program Step by Step

An environment program should start from a held-out evaluation and one well-verified environment, and prove that training on it moves the evaluation. Only then should it scale the number of environments and the infrastructure. The steps below are in dependency order. Each produces an artifact that the next step needs.

1. Fix the Target and the Held-Out Evaluation

Decide which capability the program is meant to improve and choose the evaluation that will measure it before writing any training environment. Hold out whole environment families, because held-out tasks inside a trained environment mostly measure familiarity with it (see Train/Eval Separation). Record the baseline with error bars.

2. Write One Environment with Its Own Tests

The first environment should be small, stateful and checked by end state rather than by text match. The sketch below follows the task-and-taskset style of the current Verifiers library (late-2026 verifiers.v1 interface; check the repository for exact signatures). It has three parts:

  • setup seeds a SQLite database in the sandbox.
  • The reward inspects the final database.
  • validate proves the verifier accepts a known-good end state.

An OpenEnv environment would express the same thing as a server with reset(), step() and state().

import json
import verifiers.v1 as vf

SEED = b"""CREATE TABLE orders(id INTEGER PRIMARY KEY, status TEXT, refund REAL);
INSERT INTO orders VALUES (1042,'shipped',0),(1043,'shipped',0),(1044,'pending',0);"""
INIT = "import sqlite3; sqlite3.connect('/app/shop.db').executescript(open('/app/seed.sql').read())"
DUMP = ("import sqlite3, json; c = sqlite3.connect('/app/shop.db'); "
        "print(json.dumps(c.execute('SELECT id, status, refund FROM orders ORDER BY id').fetchall()))")
GOLD = "import sqlite3; c = sqlite3.connect('/app/shop.db'); " \
       "c.execute(\"UPDATE orders SET status='refunded', refund=19.99 WHERE id=1042\"); c.commit()"

class RefundData(vf.TaskData):
    order_id: int
    amount: float

class RefundTask(vf.Task[RefundData]):
    NEEDS_CONTAINER = True

    async def setup(self, trace: vf.Trace, runtime: vf.Runtime) -> None:
        await runtime.write("/app/seed.sql", SEED)
        await runtime.run(["python3", "-c", INIT], {})

    async def end_state(self, runtime: vf.Runtime) -> dict:
        out = await runtime.run(["python3", "-c", DUMP], {})
        if out.exit_code != 0:                      # environment broke: not the agent's fault
            raise RuntimeError("state dump failed: " + out.stderr[-300:])
        return {row[0]: (row[1], row[2]) for row in json.loads(out.stdout)}

    @vf.reward(weight=1.0)
    async def refunded_exactly_one(self, runtime: vf.Runtime) -> float:
        rows = await self.end_state(runtime)
        target_ok = rows.get(self.data.order_id) == ("refunded", self.data.amount)
        collateral = [i for i, r in rows.items()       # no other order may change
                      if i != self.data.order_id and r[0] == "refunded"]
        return float(target_ok and not collateral)

    async def validate(self, runtime: vf.Runtime) -> bool:
        await runtime.run(["python3", "-c", GOLD], {})  # apply the reference solution
        return await self.refunded_exactly_one(runtime) == 1.0

class RefundTaskset(vf.Taskset[RefundTask, vf.TasksetConfig]):
    def load(self) -> list[RefundTask]:
        prompt = ("Customer on order 1042 returned a damaged item. Issue a full refund "
                  "of 19.99 in /app/shop.db and change nothing else.")
        data = RefundData(prompt=prompt, image="python:3.11-slim", workdir="/app",
                          order_id=1042, amount=19.99)
        return [RefundTask(data, self.config.task)]

Three habits carry over to any framework:

  • Collateral check. The reward checks for collateral damage.
  • Errors, not zeros. A failure to read state raises an error (an infrastructure outcome) instead of returning 0.
  • Validation hook. It runs on every version.

For untrusted agents, grading should move to a fresh sandbox (Verifiers' isolated scoring mode).

3. Audit the Verifier Before Training

Before any RL step, run three kinds of solutions through every task:

  • Gold. The reference solution must pass.
  • Null. A solution that does nothing must fail.
  • Adversarial. A handful of solutions written to game the check (edit tests, hard-code outputs, modify the database schema) must fail.

A task ships only when all three behave. Then read a few dozen real passes and failures. Most verifier bugs are found by reading (see Environment Quality Control).

4. Calibrate Difficulty with a Pass-Rate Sweep

Run the current policy \(n\) times per task. Keep tasks whose pass rate falls in a band where a group of rollouts is likely to contain both successes and failures. How that probability depends on pass rate and group size is worked out in Zero-Variance Groups and Pass-Rate Filtering.

Practitioners interviewed by Epoch AI (2026) set the floor at a pass rate of about 2–3%. Put another way, that is at least one success in 64 or 128 rollouts. They suggest retiring tasks once they reach around 70%.

The filter below makes three choices:

  • It uses a confidence interval on the pass rate.
  • It routes never-solved tasks to a verifier audit, since a 0% task may be broken rather than hard.
  • It excludes infrastructure failures from the denominator.
import math
from dataclasses import dataclass

@dataclass
class TaskStats:
    task_id: str
    successes: int
    valid: int        # completed episodes (infra failures excluded)
    infra_failures: int

def wilson(c: int, n: int, z: float = 1.96) -> tuple[float, float]:
    if n == 0:
        return 0.0, 1.0
    p, d = c / n, 1 + z * z / n
    mid, half = (p + z * z / (2 * n)) / d, z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return max(0.0, mid - half), min(1.0, mid + half)

def classify(s: TaskStats, min_n=64, ceiling=0.7, max_infra=0.05) -> str:
    total = s.valid + s.infra_failures
    if total and s.infra_failures / total > max_infra:
        return "fix-environment"              # flaky env: do not train on it
    if s.valid < min_n:
        return "need-more-rollouts"
    lo, hi = wilson(s.successes, s.valid)
    if s.successes == 0:
        return "audit-verifier"               # broken or too hard: a human decides
    if lo >= ceiling:
        return "retire"                       # saturated: little gradient left
    return "train"

def mixed_prob(p: float, G: int) -> float:   # P(group has non-zero advantage)
    return 1 - p**G - (1 - p)**G

5. Prove the Loop on a Pilot

Train on the calibrated pilot set with a modest group size and check three things:

  • training reward rises;
  • the held-out evaluation from step 1 moves;
  • a sample of rising-reward trajectories shows real task completion rather than exploits.

If reward rises but the evaluation does not, suspect reward hacking, mis-scored infrastructure failures or an environment too narrow to transfer. Scaling would amplify all three.

6. Scale Environments, Then Infrastructure

Grow the number of environment families first (mined repositories, synthesized databases and tools, purchased replicas). Every new environment must pass the same acceptance tests.

Then scale the run layer to match:

  • snapshot-based images and warm pools;
  • an asynchronous orchestrator with bounded staleness;
  • a gateway that records tokens.

Vendors are fastest for high-fidelity replicas; mining and synthesis give breadth at lower unit cost.

7. Operate the Program

Once training runs continuously, the work becomes operations. Four routines recur:

  • Track. Monitor reward, pass rate, episode length, tool-error rate and infra-failure rate per environment version (see Observability and Data Quality).
  • Re-sweep. Re-run the pass-rate sweep at each checkpoint and retire saturated tasks.
  • Re-validate. Pin and re-validate environments when dependencies change.
  • Extend held-out. Add held-out families as training families grow, so that the evaluation keeps measuring transfer rather than familiarity.
Deeper Launch checklist for an environment program

Each item should be true, with evidence linked in the registry, before the first large training run.

  • Evaluation. Target written down; held-out families absent from all training task stores; baseline has error bars.
  • Registry. Every environment version pins image digest, tools, verifier, task set, limits and owner.
  • Verifier audit. Gold passes, null and adversarial solutions fail on every task; a reviewer has read real passes and failures.
  • Isolation. Hidden tests never enter the agent sandbox; grading uses declared artifacts; egress allowlisted; no credentials in images.
  • Difficulty. Pass-rate sweep done; zero-pass tasks audited; saturated tasks retired.
  • Infra outcomes. Own codes, excluded from rewards, alerting per environment.
  • Token capture. Gateway stores token ids, log-probabilities and policy version; a replay test confirms the trainer sees the sampled tokens.
  • Decontamination. Training tasks checked against every evaluation suite; overlaps removed and logged.
  • Reproducibility. Canary tasks replay stably on each build; any change bumps the version.
  • Monitoring. Per-version dashboards and a staffed trajectory review queue.
  • Exit criteria. The pilot moved the held-out evaluation; rules for retiring or re-weighting environments are written.

Open Problems

Environments became a scaled industrial input in 2025–2026 faster than the science of what makes an environment useful. The open problems below are those where the sources in this book disagree, report negative results, or are silent.

  • Predicting an environment's value before training on it. Madan et al. (NeurIPS 2026) studied Qwen3 models from 1.7B to 14B parameters. At matched token budgets, the choice of training environment shifted held-out pass@1 (single-attempt success rate) by up to 11.4 points. Pre-RL measures of usable advantage ranked environment pairs correctly about 78% of the time at 14B. Whether this holds at frontier scale is open.
  • Verifiers for open-ended work. Coding and database tasks have end states to check; long white-collar workflows, research and writing mostly do not. Rubric and judge rewards scale but can be gamed. There is no agreed way to measure a verifier's false-positive rate on policies stronger than the people who wrote it.
  • Fidelity versus scale. Synthesized and LLM-simulated environments give breadth at low cost. Expert-built replicas give fidelity at up to hundreds of thousands of dollars each. How much fidelity training needs, and how to measure the sim-to-real gap per skill, is mostly anecdotal.
  • Keeping environments ahead of the policy. If environment complexity must keep growing quickly to stay useful, as at least one vendor claims, hand-building cannot keep pace. Self-generated curricula and environment-proposing agents exist in prototypes (DeepSeek-V3.2's difficulty-raising synthesis is one) but have not been shown to be open-ended.
  • Generalization across environment families. Much of the reported progress is measured on benchmarks whose environments resemble the training ones. Clean measurements of transfer to genuinely new families, with families rather than tasks held out, are rare.
  • Standards and portability. OpenEnv, Verifiers and Harbor converge on similar abstractions. But semantics such as reset, isolation and infra-failure codes are not yet portable, and exclusive contracts keep most environments out of shared hubs.
  • Economics. It is unclear whether per-task spending will keep rising, as Mechanize predicted, or fall as synthesis improves. It is also unclear whether environment vendors become durable businesses or a function absorbed by labs, as the 2026 acquisitions hint.
About the figures

All figures are original diagrams and charts drawn for this book; none is adapted from a figure in a source. Charts plotted from reported numbers name their sources in the caption, charts computed from a formula say so, and placements or parameters chosen for exposition are marked illustrative.

Citation

Cited as:

Cheng, Kevin. (Nov 2026). RL Environments: From Gym to Environment Factories. Kevin's Notes. https://claude.ai/
@article{cheng2026rlenv,
  title   = "RL Environments: From Gym to Environment Factories",
  author  = "Cheng, Kevin",
  journal = "Kevin's Notes",
  year    = "2026",
  month   = "Nov",
  url     = "https://claude.ai/"
}

References

  1. Denain, Jean-Stanislas, and Chris Barber. "An FAQ on Reinforcement Learning Environments." Epoch AI, Gradient Updates 2026. epoch.ai/gradient-updates/state-of-rl-envs
  2. Prime Intellect. "Environments Hub: A Community Hub To Scale RL To Open AGI." Prime Intellect blog 2025. primeintellect.ai/blog/environments
  3. Spisak, Joseph, et al. "Building the Open Agent Ecosystem Together: Introducing OpenEnv." Hugging Face blog 2025. huggingface.co/blog/openenv
  4. NVIDIA. "NVIDIA Debuts Nemotron 3 Family of Open Models." NVIDIA press release 2025. investor.nvidia.com/…/NVIDIA-Debuts-Nemotron-3
  5. Harbor Framework Team. "Harbor: A framework for evaluating and optimizing agents and models." GitHub 2026. github.com/harbor-framework/harbor
  6. Terminal-Bench team. "Terminal-Bench 2.0 and Harbor." tbench.ai news 2025. tbench.ai/news/announcement-2-0
  7. Anthropic. "Introducing the Model Context Protocol." Anthropic news 2024. anthropic.com/news/model-context-protocol
  8. DeepSeek-AI. "DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning." arXiv 2501.12948, 2025. arxiv.org/abs/2501.12948
  9. Lambert, Nathan, et al. "Tülu 3: Pushing Frontiers in Open Language Model Post-Training." arXiv 2411.15124, 2024. arxiv.org/abs/2411.15124
  10. Brockman, Greg, et al. "OpenAI Gym." arXiv 1606.01540, 2016. arxiv.org/abs/1606.01540
  11. Towers, Mark, et al. "Gymnasium: A Standard Interface for Reinforcement Learning Environments." arXiv 2407.17032, 2024. arxiv.org/abs/2407.17032
  12. Bellemare, Marc G., et al. "The Arcade Learning Environment: An Evaluation Platform for General Agents." JAIR 2013. arxiv.org/pdf/1207.4708
  13. Todorov, Emanuel, Tom Erez, and Yuval Tassa. "MuJoCo: A physics engine for model-based control." IROS 2012. ieeexplore.ieee.org/document/6386109
  14. Tassa, Yuval, et al. "DeepMind Control Suite." arXiv 1801.00690, 2018. arxiv.org/abs/1801.00690
  15. Cobbe, Karl, et al. "Leveraging Procedural Generation to Benchmark Reinforcement Learning." arXiv 1912.01588, 2019. arxiv.org/abs/1912.01588
  16. Wang, Rui, et al. "Paired Open-Ended Trailblazer (POET): Endlessly Generating Increasingly Complex and Diverse Learning Environments and Their Solutions." arXiv 1901.01753, 2019. arxiv.org/abs/1901.01753
  17. Küttler, Heinrich, et al. "The NetHack Learning Environment." NeurIPS 2020. arxiv.org/abs/2006.13760
  18. Stojanovski, Zafir, et al. "Reasoning Gym: Reasoning Environments for Reinforcement Learning with Verifiable Rewards." arXiv 2505.24760, 2025. arxiv.org/abs/2505.24760
  19. Shi, Tianlin, et al. "World of Bits: An Open-Domain Platform for Web-Based Agents." ICML 2017. proceedings.mlr.press/v70/shi17a
  20. Yao, Shunyu, et al. "WebShop: Towards Scalable Real-World Web Interaction with Grounded Language Agents." arXiv 2207.01206, 2022. arxiv.org/abs/2207.01206
  21. Zhou, Shuyan, et al. "WebArena: A Realistic Web Environment for Building Autonomous Agents." arXiv 2307.13854, 2023. arxiv.org/abs/2307.13854
  22. Xie, Tianbao, et al. "OSWorld: Benchmarking Multimodal Agents for Open-Ended Tasks in Real Computer Environments." arXiv 2404.07972, 2024. arxiv.org/abs/2404.07972
  23. Chen, Mark, et al. "Evaluating Large Language Models Trained on Code." arXiv 2107.03374, 2021. arxiv.org/abs/2107.03374
  24. Jimenez, Carlos E., et al. "SWE-bench: Can Language Models Resolve Real-World GitHub Issues?" arXiv 2310.06770, 2023. arxiv.org/abs/2310.06770
  25. Pan, Jiayi, et al. "Training Software Engineering Agents and Verifiers with SWE-Gym." arXiv 2412.21139, 2024. arxiv.org/abs/2412.21139
  26. Jain, Naman, et al. "R2E-Gym: Procedural Environments and Hybrid Verifiers for Scaling Open-Weights SWE Agents." arXiv 2504.07164, 2025. arxiv.org/abs/2504.07164
  27. Yang, John, et al. "SWE-smith: Scaling Data for Software Engineering Agents." arXiv 2504.21798, 2025. arxiv.org/abs/2504.21798
  28. DeepSeek-AI. "DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models." arXiv 2512.02556, 2025. arxiv.org/abs/2512.02556
  29. Wang, Zhaoyang, et al. "Agent World Model: Infinity Synthetic Environments for Agentic Reinforcement Learning." arXiv 2602.10090, 2026. arxiv.org/abs/2602.10090
  30. Yao, Shunyu, et al. "τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains." arXiv 2406.12045, 2024. arxiv.org/abs/2406.12045
  31. Wang, Ruoyao, et al. "ScienceWorld: Is your Agent Smarter than a 5th Grader?" EMNLP 2022. arxiv.org/abs/2203.07540
  32. Model Context Protocol. "Tools." MCP Specification, version 2025-11-25. modelcontextprotocol.io/specification/2025-11-25/server/tools
  33. NVIDIA. "Harbor (agent interactions)." NeMo Gym documentation 2026. docs.nvidia.com/nemo/gym/agent-interactions/harbor
  34. OpenEnv contributors. "Harbor Environment." OpenEnv documentation 2026. huggingface.co/docs/openenv/main/en/environments/harbor
  35. Prime Intellect. "Verifiers v1" (release announcement thread). 2026. threadreaderapp.com/thread/2076447247693402301
  36. Hugging Face. "The Open Source Community is backing OpenEnv for Agentic RL." Hugging Face Blog 2026. huggingface.co/blog/openenv-agentic-rl
  37. OpenEnv contributors. "OpenEnv: Agentic Execution Environments." OpenEnv documentation 2026. huggingface.co/docs/openenv
  38. General Reasoning. "The Open Reward Standard." 2026. gr.inc/releases/the-open-reward-standard
  39. Lacoste, A., et al. "CUBE: A Standard for Unifying Agent Benchmarks." arXiv 2026. arxiv.org/abs/2603.15798
  40. NVIDIA. "RL Environment Ecosystem." NeMo Gym documentation 2026. docs.nvidia.com/nemo/gym/0.2.0/about/ecosystem
  41. NovaSky AI. "SkyRL-Gym." PyPI 2026. pypi.org/project/skyrl-gym
  42. Liu, Z., Sims, A., Duan, K., et al. "GEM: A Gym for Agentic LLMs." arXiv 2025. arxiv.org/abs/2510.01051
  43. Nous Research. "Atropos: An Environment and Rollout handler for LLM RL." PyPI 2026. pypi.org/project/atroposlib
  44. Zeng, Z., et al. "RLVE: Scaling Up Reinforcement Learning for Language Models with Adaptive Verifiable Environments." arXiv 2025. arxiv.org/abs/2511.07317
  45. Burtenshaw, B., et al. "Welcome RL Environments to the hub." Hugging Face Blog 2026. huggingface.co/blog/rl-environments
  46. Huang, Y., Zeng, W., et al. "Pitfalls of Rule- and Model-based Verifiers: A Case Study on Mathematical Reasoning." arXiv 2025. arxiv.org/abs/2505.22203
  47. Gunjal, A., et al. "Rubrics as Rewards: Reinforcement Learning Beyond Verifiable Domains." arXiv 2025. arxiv.org/abs/2507.17746
  48. Trivedi, H., et al. "AppWorld: A Controllable World of Apps and People for Benchmarking Interactive Coding Agents." ACL 2024. arxiv.org/abs/2407.18901
  49. Ng, A. Y., Harada, D., Russell, S. "Policy Invariance Under Reward Transformations: Theory and Application to Reward Shaping." ICML 1999. cs.utexas.edu/~shivaram/readings/b2hd-NgHR1999
  50. METR. "Recent Frontier Models Are Reward Hacking." METR Blog 2025. metr.org/blog/2025-06-05-recent-reward-hacking
  51. Zhong, Z., Raghunathan, A., Carlini, N. "ImpossibleBench: Measuring LLMs' Propensity of Exploiting Test Cases." arXiv 2025. arxiv.org/abs/2510.20270
  52. MacDiarmid, M., et al. (Anthropic). "Natural Emergent Misalignment from Reward Hacking in Production RL." Anthropic Research summary 2025. anthropic.com/research/emergent-misalignment-reward-hacking
  53. Kourabi, A. J., and Patel, D. "RL Environments and RL for Science: Data Foundries and Multi-Agent Architectures." SemiAnalysis 2026. newsletter.semianalysis.com/p/rl-environments-and-rl-for-science
  54. Badertdinov, I., Golubev, A., Nekrashevich, M., Shevtsov, A., Karasik, S., Andriushchenko, A., Trofimova, M., Litvintseva, D., and Yangel, B. "SWE-rebench: An Automated Pipeline for Task Collection and Decontaminated Evaluation of Software Engineering Agents." NeurIPS Datasets and Benchmarks 2025. arxiv.org/abs/2505.20411
  55. Prime Intellect. "Scaling Agentic RL: 365,000+ Environments for SWE, Terminal, and Search." Prime Intellect blog 2026. primeintellect.ai/blog/scaling-agentic-rl
  56. Tu, D., Hao, H., Yang, H., et al. "ScaleEnv: Scaling Environment Synthesis from Scratch for Generalist Interactive Tool-Use Agent Training." ICML 2026. arxiv.org/abs/2602.06820
  57. Cai, S., Fang, R., Wu, J., et al. "AutoForge: Automated Environment Synthesis for Agentic Reinforcement Learning." arXiv 2025. arxiv.org/abs/2512.22857
  58. Xu, M., Wang, Z., Deng, M., et al. "EnvFactory: Scaling Tool-Use Agents via Executable Environments Synthesis and Robust RL." arXiv 2026. arxiv.org/abs/2605.18703
  59. Szot, A., Abnar, S., Attia, O., Kazerouni, A., Kirchhof, M., Hsieh, C.-Y., Vemulapalli, R., and Toshev, A. "Scaling Laws for Tool-Use Agents via Controllable Environment Synthesis." arXiv 2026. arxiv.org/abs/2610.37648
  60. Kimi Team. "Kimi K2: Open Agentic Intelligence." arXiv 2025. arxiv.org/html/2507.20534v2
  61. Gu, Y., Zhang, K., Ning, Y., et al. "Is Your LLM Secretly a World Model of the Internet? Model-Based Planning for Web Agents." TMLR 2025. arxiv.org/abs/2411.06559
  62. Li, Y., Inan, H. A., Yue, X., et al. "Simulating Environments with Reasoning Models for Agent Training." arXiv 2025. arxiv.org/abs/2511.01824
  63. Chen, Z., Zhao, Z., Zhang, K., et al. "Scaling Agent Learning via Experience Synthesis." ICLR 2026. arxiv.org/abs/2511.03773
  64. Qian, C., Liu, Z., Prabhakar, A., et al. "UserRL: Training Interactive User-Centric Agent via Reinforcement Learning." arXiv 2025. arxiv.org/abs/2509.19736
  65. Liu, Y., Hui, T., Zhang, W., Sun, L., Su, N., Wang, J., and Su, S. "EnvSimBench: A Benchmark for Evaluating and Improving LLM-Based Environment Simulation." arXiv 2026. arxiv.org/abs/2605.07247
  66. OpenAI. "Introducing SWE-bench Verified." OpenAI 2024. openai.com/index/introducing-swe-bench-verified
  67. Kondragunta, M. M. C. "RL Environments are an Infrastructure Problem: Lessons from Operating Agentic Rollouts at Scale." NeurIPS 2026 workshop. neurips.cc/virtual/2026/166780
  68. Shi, T. & Glottmann, T. "Accelerate agentic RL with GKE Agent Sandbox." Google Cloud Blog 2026. cloud.google.com/blog/…/accelerate-agentic-rl-with-gke-agent-sandbox
  69. Huang, J., et al. "DeepSeek Elastic Compute (DSec): A Sandbox Infrastructure for Effective Agentic Training at Scale." arXiv 2609.22978, 2026. arxiv.org/pdf/2609.22978
  70. Nie, Y., Zhou, R., Chen, Z., Zhang, J., Shao, Y., Li, H., Li, B., Song, D. & Guo, W. "NitroBox: Lightning-Fast Sandbox for Large-Scale RL Training." NeurIPS 2026. neurips.cc/virtual/2026/poster/148578
  71. Prime Intellect. "Prime Sandboxes." Prime Intellect Blog 2026. primeintellect.ai/blog/sandboxes
  72. Liu, J., Frye, C. & Walters, P. "Reinforcement learning is an infrastructure problem." Modal Blog 2026. modal.com/blog/reinforcement-learning-infrastructure-problem
  73. Yan, Y., Wang, H., et al. "Sandman: A Sandbox Service for Production Agentic Reinforcement Learning." arXiv 2610.39711, 2026. arxiv.org/pdf/2610.39711
  74. Agache, A., Brooker, M., Florescu, A., Iordache, A., Liguori, A., Neugebauer, R., Piwonka, P. & Popa, D.-M. "Firecracker: Lightweight Virtualization for Serverless Applications." NSDI 2020. usenix.org/conference/nsdi20/presentation/agache
  75. Gupta, A. & Lian, L. "Firecracker – Lightweight Virtualization for Serverless Computing." AWS Open Source Blog 2018. aws.amazon.com/blogs/opensource/firecracker…
  76. gVisor Authors. "Releasing Systrap: A high-performance gVisor platform." gVisor Blog 2023. gvisor.dev/blog/2023/04/28/systrap-release
  77. Kata Containers. "Kata Containers Architecture." GitHub documentation. github.com/kata-containers/…/architecture.md
  78. Upstash. "AI Agent Sandboxes Compared: 15 Providers on Isolation, Persistence, Agent Tooling, and Cost." Upstash Blog 2026. upstash.com/blog/ai-agent-sandbox-providers-compared-2026
  79. Wikipedia. "Little's law." en.wikipedia.org/wiki/Little's_law
  80. verl Team. "Agent Loop." verl documentation. verl.readthedocs.io/…/agent_loop.html
  81. THUDM. "slime: an LLM post-training framework for RL scaling." GitHub. github.com/THUDM/slime
  82. NovaSky-AI. "SkyRL: A Modular Full-stack RL Library for LLMs." GitHub. github.com/NovaSky-AI/SkyRL
  83. Fu, W., Gao, J., Shen, X., et al. "AReaL: A Large-Scale Asynchronous Reinforcement Learning System for Language Reasoning." NeurIPS 2025. arxiv.org/abs/2505.24298
  84. Piché, A., Kamalloo, E., Pardinas, R., Chen, X. & Bahdanau, D. "PipelineRL: Faster On-policy Reinforcement Learning for Long Sequence Generation." arXiv 2509.19128, 2025. arxiv.org/abs/2509.19128
  85. Gao, W., Zhao, Y., An, D., et al. "RollPacker: Mitigating Long-Tail Rollouts for Fast, Synchronous RL Post-Training." arXiv 2509.21009, 2025. arxiv.org/pdf/2509.21009
  86. Kimi Team. "Kimi k1.5: Scaling Reinforcement Learning with LLMs." arXiv 2501.12599, 2025. arxiv.org/html/2501.12599
  87. OpenEnv. "Harbor environments." OpenEnv documentation 2026. openenv.github.io/OpenEnv/main/environments/harbor
  88. Agent Lightning Team (Zhang, Y., et al.). "No More Retokenization Drift: Returning Token IDs via the OpenAI Compatible API Matters in Agent RL." vLLM Blog 2025. vllm.ai/blog/2025-10-22-agent-lightning
  89. Miles Team (Li, J., et al.). "No Token Left Behind." LMSYS Blog 2026. lmsys.org/blog/2026-05-13-no-token-left-behind
  90. NVIDIA. "On-Policy Corrections for OpenAI-compatible HTTP servers." NeMo Gym documentation. docs.nvidia.com/nemo/gym/…/on-policy-correction
  91. Gallouédec, Q. & Rasul, K. "Agentic RL: Token-In, Token-Out Done Right." Hugging Face Blog 2026. huggingface.co/blog/huggingface/tito
  92. Yao, F., Liu, L., Zhang, D., Dong, C., Shang, J. & Gao, J. "Your Efficient RL Framework Secretly Brings You Off-Policy RL Training." 2025. liyuanlucasliu.github.io/publication/feng-off-2025
  93. verl Team. "Rollout Correction." verl documentation. verl.readthedocs.io/…/rollout_corr.html
  94. NitroBox. "nitrobox: Lightweight Linux namespace sandbox with persistent shell and instant reset." PyPI package documentation 2026. pypi.org/project/nitrobox
  95. Ramos, S., Girgin, S., Hussenot, L., et al. "RLDS: an Ecosystem to Generate, Share and Use Datasets in Reinforcement Learning." arXiv 2021. arxiv.org/pdf/2111.02767
  96. NVIDIA. "Agent Trajectory Interchange Format (ATIF) v1.7." NeMo Gym documentation 2026. docs.nvidia.com/nemo/gym
  97. DeepSeek-AI. "DeepSeek-V4: Towards Highly Efficient Million-Token Context Intelligence." arXiv 2026. arxiv.org/html/2606.19348
  98. Prime Intellect. "INTELLECT-3: Technical Report." arXiv 2025. arxiv.org/abs/2512.16144
  99. Terminal-Bench team. "Terminal-Bench 2.1." tbench.ai news, May 2026. tbench.ai/news/terminal-bench-2-1
  100. Buchanan, E. K., Linderman, S., Ré, C. "Benchmarks as Software: A Case Study on Terminal-Bench." ICML 2026. icml.cc/virtual/2026/82793
  101. Yu, Q., Zhang, Z., Zhu, R., et al. "DAPO: An Open-Source LLM Reinforcement Learning System at Scale." arXiv 2025. arxiv.org/pdf/2503.14476
  102. Zeng, Z., Ivison, H., et al. "RLVE: Scaling Up Reinforcement Learning for Language Models with Adaptive Verifiable Environments." ICML 2026 (arXiv 2025). arxiv.org/abs/2511.07317
  103. Lu, K. "On-Policy Distillation." Thinking Machines Lab blog 2025. thinkingmachines.ai/blog/on-policy-distillation
  104. Thinking Machines Lab. "RL Training Outputs (RL logging)." Tinker documentation 2026. tinker-docs.thinkingmachines.ai
  105. METR. "MALT: A Dataset of Natural and Prompted Behaviors." METR blog 2025. metr.org/blog/2025-10-14-malt
  106. Baker, B., Huizinga, J., Gao, L., et al. "Monitoring Reasoning Models for Misbehavior and the Risks of Promoting Obfuscation." arXiv 2025. arxiv.org/abs/2503.11926
  107. Steinhardt, J. (Transluce). "Analyzing Long Agent Transcripts (Docent)." LessWrong 2025. lesswrong.com/posts/Mj276hooL3Mncs3uv
  108. OpenAI. "Why We No Longer Evaluate SWE-bench Verified." OpenAI 2026. openai.com/index/why-we-no-longer-evaluate-swe-bench-verified
  109. Prime Intellect. "INTELLECT-3." Prime Intellect blog, Nov 2025. primeintellect.ai/blog/intellect-3
  110. Kimi Team. "Kimi K2.5: Visual Agentic Intelligence." arXiv 2026. arxiv.org/abs/2602.02276
  111. GLM-5 Team (Zhipu AI). "GLM-5: from Vibe Coding to Agentic Engineering." arXiv 2026. arxiv.org/html/2602.15763
  112. MiniMax. "Forge: Scalable Agent RL Framework and Algorithm." MiniMax news, Feb 2026. minimax.io/news/forge-scalable-agent-rl-framework-and-algorithm
  113. Hugging Face. "DeepSeek-V4: a million-token context that agents can actually use." Hugging Face blog, Apr 2026. huggingface.co/blog/deepseekv4
  114. Tongyi DeepResearch Team. "Tongyi DeepResearch Technical Report." arXiv 2025. arxiv.org/pdf/2510.24701
  115. Zeff, M. "Silicon Valley bets big on 'environments' to train AI agents." TechCrunch, Sept 2025. techcrunch.com/2025/09/21/silicon-valley-bets-big-on-environments
  116. Erdil, E., Barnett, M., and Besiroglu, T. "Cheap RL tasks will waste compute." Mechanize, Aug 2025. mechanize.work/blog/cheap-rl-tasks-will-waste-compute
  117. Orrick. "Mercor Acquires Sepal AI." Orrick news, Feb 2026. orrick.com/en/News/2026/02/Mercor-Acquires-Sepal-AI
  118. SiliconANGLE. "Mercor buys Deeptune to build training environments for AI agents." SiliconANGLE, Jul 2026. siliconangle.com/2026/07/09/mercor-buys-deeptune
  119. Fortune. "Halluminate raises $30 million Series A." Fortune, Oct 2026. fortune.com/2026/10/01/halluminate-raises-30-million-series-a
  120. Zeoli, C. "RL Environments for Agentic AI: Who Will Win the Training & Verification Layer by 2030." Wing VC, Jan 2026. wing.vc/content/rl-environments-for-agentic-ai
  121. Prime Intellect. "verifiers: environments for LLM reinforcement learning." GitHub. github.com/PrimeIntellect-ai/verifiers
  122. Madan, V., et al. "Which Environments Should LLMs Learn From? Predicting RL Utility Across Four Scales." NeurIPS 2026. neurips.cc/virtual/2026/164478